ソースを参照

Merge pull request #1225 from gleb-urvanov/feature/devops-update

Network testing: run tests without exported state
Mokhtar Naamani 4 年 前
コミット
6beeea3c67
54 ファイル変更2180 行追加1586 行削除
  1. 25 0
      .github/workflows/run-network-tests.yml
  2. 22 0
      devops/ansible/build-and-run-tests-exported-chainspec-playbook.yml
  3. 6 1
      devops/ansible/build-and-run-tests-single-node-playbook.yml
  4. 6 1
      devops/ansible/build-and-run-tests-two-nodes-playbook.yml
  5. 6 1
      devops/ansible/build-image-playbook.yml
  6. 2 2
      devops/ansible/docker-compose.yml
  7. 4 0
      devops/ansible/roles/alter_block_creation_time/tasks/main.yml
  8. 1 1
      devops/ansible/roles/build_docker_image/tasks/main.yml
  9. 16 5
      devops/ansible/roles/install_dependencies/tasks/main.yml
  10. 38 0
      devops/ansible/roles/run_tests_exported_chainspec/tasks/main.yml
  11. 16 5
      devops/ansible/roles/run_tests_single_node/tasks/main.yml
  12. 0 37
      devops/dockerfiles/ansible-node/Dockerfile
  13. 1 1
      devops/dockerfiles/rust-builder/Dockerfile
  14. 4 0
      scripts/alter-block-creation-time.sh
  15. 0 7
      scripts/build-joystream-testing-node-docker-image.sh
  16. 21 0
      testnets/nicaea-exported-state/chain_spec.json
  17. 0 0
      testnets/nicaea-exported-state/content.json
  18. 0 0
      testnets/nicaea-exported-state/forum.json
  19. 0 0
      testnets/nicaea-exported-state/members.json
  20. 99 0
      testnets/nicaea-exported-state/raw_chain_spec.json
  21. 3 1
      tests/network-tests/.env
  22. 9 2
      tests/network-tests/.eslintrc.js
  23. 6 4
      tests/network-tests/package.json
  24. 106 0
      tests/network-tests/src/iznik/services/dbService.ts
  25. 2 4
      tests/network-tests/src/iznik/tests/council/electingCouncilTest.ts
  26. 57 0
      tests/network-tests/src/iznik/tests/councilSetup.ts
  27. 68 0
      tests/network-tests/src/iznik/tests/fixtures/councilElectionHappyCase.ts
  28. 25 25
      tests/network-tests/src/iznik/tests/fixtures/councilElectionModule.ts
  29. 126 0
      tests/network-tests/src/iznik/tests/fixtures/leaderHiringHappyCase.ts
  30. 16 11
      tests/network-tests/src/iznik/tests/fixtures/membershipModule.ts
  31. 283 233
      tests/network-tests/src/iznik/tests/fixtures/proposalsModule.ts
  32. 137 214
      tests/network-tests/src/iznik/tests/fixtures/workingGroupModule.ts
  33. 62 0
      tests/network-tests/src/iznik/tests/leaderSetup.ts
  34. 3 4
      tests/network-tests/src/iznik/tests/membership/membershipCreationTest.ts
  35. 26 36
      tests/network-tests/src/iznik/tests/proposals/contentWorkingGroupMintCapacityProposalTest.ts
  36. 24 35
      tests/network-tests/src/iznik/tests/proposals/electionParametersProposalTest.ts
  37. 42 51
      tests/network-tests/src/iznik/tests/proposals/manageLeaderRoleTest.ts
  38. 24 35
      tests/network-tests/src/iznik/tests/proposals/setLeadProposalTest.ts
  39. 24 35
      tests/network-tests/src/iznik/tests/proposals/spendingProposalTest.ts
  40. 24 35
      tests/network-tests/src/iznik/tests/proposals/textProposalTest.ts
  41. 28 31
      tests/network-tests/src/iznik/tests/proposals/updateRuntime.ts
  42. 24 35
      tests/network-tests/src/iznik/tests/proposals/validatorCountProposalTest.ts
  43. 26 37
      tests/network-tests/src/iznik/tests/proposals/workingGroupMintCapacityProposalTest.ts
  44. 36 85
      tests/network-tests/src/iznik/tests/workingGroup/atLeastValueBugTest.ts
  45. 42 85
      tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsLeadTest.ts
  46. 36 82
      tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsWorkerTest.ts
  47. 35 81
      tests/network-tests/src/iznik/tests/workingGroup/workerApplicationHappyCaseTest.ts
  48. 37 83
      tests/network-tests/src/iznik/tests/workingGroup/workerApplicationRejectionCaseTest.ts
  49. 59 100
      tests/network-tests/src/iznik/tests/workingGroup/workerPayoutTest.ts
  50. 472 166
      tests/network-tests/src/iznik/utils/apiWrapper.ts
  51. 13 10
      tests/network-tests/src/iznik/utils/sender.ts
  52. 0 2
      tests/network-tests/src/nicaea/tests/workingGroup/impl/workingGroupModule.ts
  53. 6 1
      tests/network-tests/tsconfig.json
  54. 32 2
      yarn.lock

+ 25 - 0
.github/workflows/run-network-tests.yml

@@ -0,0 +1,25 @@
+name: run-network-tests
+on:
+  pull_request:
+    types: [labeled]
+  workflow_dispatch:
+
+jobs:
+  run_ansible_tests:
+    if: github.event.label.name == 'run-network-tests' || github.event.action == null
+    name: run network tests using ansible
+    runs-on: ubuntu-latest
+    strategy:
+      matrix:
+        node-version: [12.x]
+    steps:
+      - uses: actions/checkout@v1
+      - uses: actions/setup-node@v1
+        with:
+          node-version: ${{ matrix.node-version }}
+      - name: install toolchain
+        run: curl https://getsubstrate.io -sSf | bash -s -- --fast
+      - name: ansible build and tests
+        run: |
+          cd ./devops/ansible
+          ansible-playbook -i hosts build-and-run-tests-single-node-playbook.yml --become -v

+ 22 - 0
devops/ansible/build-and-run-tests-exported-chainspec-playbook.yml

@@ -0,0 +1,22 @@
+- hosts: 127.0.0.1
+  user: root
+  become: yes
+  become_method: sudo
+
+  tasks:
+
+    - name: install dependencies
+      include_role:
+        name: install_dependencies
+
+    - name: alter block creation time
+      include_role:
+        name: alter_block_creation_time
+
+    - name: build node
+      include_role:
+        name: build_docker_image
+
+    - name: run tests
+      include_role:
+        name: run_tests_exported_chainspec

+ 6 - 1
devops/ansible/build-and-run-tests-single-node-playbook.yml

@@ -4,14 +4,19 @@
   become_method: sudo
 
   tasks:
+
     - name: install dependencies
       include_role:
         name: install_dependencies
 
+    - name: alter block creation time
+      include_role:
+        name: alter_block_creation_time
+
     - name: build node
       include_role:
         name: build_docker_image
-        
+
     - name: run tests
       include_role:
         name: run_tests_single_node

+ 6 - 1
devops/ansible/build-and-run-tests-two-nodes-playbook.yml

@@ -4,14 +4,19 @@
   become_method: sudo
 
   tasks:
+
     - name: install dependencies
       include_role:
         name: install_dependencies
 
+    - name: alter block creation time
+      include_role:
+        name: alter_block_creation_time
+
     - name: build node
       include_role:
         name: build_docker_image
-        
+
     - name: run tests
       include_role:
         name: run_tests_two_nodes

+ 6 - 1
devops/ansible/build-image-playbook.yml

@@ -4,10 +4,15 @@
   become_method: sudo
 
   tasks:
+
     - name: install dependencies
       include_role:
         name: install_dependencies
 
+    - name: alter block creation time
+      include_role:
+        name: alter_block_creation_time
+
     - name: build node
       include_role:
-        name: build_docker_image
+        name: build_docker_image

+ 2 - 2
devops/ansible/docker-compose.yml

@@ -3,7 +3,7 @@ services:
   node_alice:
     image: joystream/node-testing
     container_name: alice
-    entrypoint: ./node --chain=chainspec.json --alice --validator --ws-external --rpc-cors=all
+    entrypoint: ./node --dev --alice --validator --unsafe-ws-external --rpc-cors=all
     ports:
       - "30333:30333"
       - "9933:9933"
@@ -15,7 +15,7 @@ services:
   node_bob:
     image: joystream/node-testing
     container_name: bob
-    entrypoint: ./node --chain=chainspec.json --bob --ws-external --rpc-cors=all
+    entrypoint: ./node --dev --bob --validator --unsafe-ws-external --rpc-cors=all
     ports:
       - "30335:30333"
       - "9935:9933"

+ 4 - 0
devops/ansible/roles/alter_block_creation_time/tasks/main.yml

@@ -0,0 +1,4 @@
+- name: alter block creation time
+  shell: ./scripts/alter-block-creation-time.sh
+  args:
+    chdir: ../../

+ 1 - 1
devops/ansible/roles/build_docker_image/tasks/main.yml

@@ -1,4 +1,4 @@
 - name: create testing node docker image
-  shell: ./scripts/build-joystream-testing-node-docker-image.sh
+  shell: ./scripts/build-joystream-node-docker-image.sh
   args:
     chdir: ../../

+ 16 - 5
devops/ansible/roles/install_dependencies/tasks/main.yml

@@ -1,7 +1,13 @@
-- name: install pip on Debian
+- name: install pip and npm on Debian
   block:
+    - name: create temporary folder
+      file:
+        path: ../../.tmp
+        state: directory
     - name: install pip using apt
       apt: name=python-pip state=present
+    - name: install npm using apt
+      apt: name=npm state=present
   when: ansible_distribution == 'Debian' or ansible_distribution == 'Ubuntu'
 
 - name: install pip on Mac
@@ -11,15 +17,15 @@
         path: ../../.tmp
         state: directory
     - name: get pip installer using curl
-      get_url: 
+      get_url:
         url: https://bootstrap.pypa.io/get-pip.py
         dest: ../../.tmp/get-pip.py
     - name: install pip
       shell: python ../../.tmp/get-pip.py
   when: ansible_distribution == 'MacOSX'
-  always: 
+  always:
     - name: remove pip installer script
-      file: 
+      file:
         path: ../../.tmp/get-pip.py
         state: absent
 
@@ -31,5 +37,10 @@
     name: yarn
     global: yes
 
+- name: Install pyrsistent
+  pip:
+    name: pyrsistent==0.16.0
+
 - name: Install docker compose
-  pip: name=docker-compose
+  pip:
+    name: docker-compose==1.26.2

+ 38 - 0
devops/ansible/roles/run_tests_exported_chainspec/tasks/main.yml

@@ -0,0 +1,38 @@
+- name: run network
+  block:
+    - name: yarn install for joystream types
+      shell: yarn workspace @joystream/types install
+
+    - name: yarn build for joystream types
+      shell: yarn workspace @joystream/types build
+
+    - name: yarn install for network tests
+      shell: yarn workspace joystream-testing install
+
+    - name: run docker container
+      docker_container:
+        name: "joystream-node"
+        image: "joystream/node"
+        ports:
+          - "9944:9944"
+        mounts:
+          - target: /testnet-state
+            source: "{{ playbook_dir }}/../../testnets/nicaea-exported-state"
+            type: bind
+            read_only: yes
+        entrypoint: ./node --chain ../testnet-state/raw_chain_spec.json --alice --validator --unsafe-ws-external --rpc-cors=all
+        state: started
+
+    - name: execute network tests
+      shell: yarn test >> ../../.tmp/tests.log
+      args:
+        chdir: ../../tests/network-tests/
+
+  always:
+    - name: display tests log
+      shell: cat ../../.tmp/tests.log
+
+    - name: stop docker container
+      docker_container:
+        name: "joystream-node-testing"
+        state: absent

+ 16 - 5
devops/ansible/roles/run_tests_single_node/tasks/main.yml

@@ -1,21 +1,32 @@
 - name: run network
   block:
+    - name: yarn install for joystream types
+      shell: yarn workspace @joystream/types install
+
+    - name: yarn build for joystream types
+      shell: yarn workspace @joystream/types build
+
+    - name: yarn install for network tests
+      shell: yarn workspace joystream-testing install
 
     - name: run docker container
       docker_container:
-        name: "joystream-node-testing"
-        image: "joystream/node-testing"
+        name: "joystream-node"
+        image: "joystream/node"
         ports:
           - "9944:9944"
-        entrypoint: ./node --chain=chainspec.json --alice --validator --ws-external --rpc-cors=all
+        entrypoint: ./node --dev --alice --validator --unsafe-ws-external --rpc-cors=all
         state: started
 
     - name: execute network tests
-      shell: yarn debug >> ../../.tmp/tests.log
+      shell: yarn test >> ../../.tmp/tests.log
       args:
         chdir: ../../tests/network-tests/
-        
+
   always:
+    - name: display tests log
+      shell: cat ../../.tmp/tests.log
+
     - name: stop docker container
       docker_container:
         name: "joystream-node-testing"

+ 0 - 37
devops/dockerfiles/ansible-node/Dockerfile

@@ -1,37 +0,0 @@
-FROM joystream/rust-builder AS builder
-LABEL description="Compiles all workspace artifacts"
-WORKDIR /joystream
-COPY . /joystream
-
-# Build joystream-node and its dependencies - runtime
-RUN WASM_BUILD_TOOLCHAIN=nightly-2020-05-23 cargo build --release -p joystream-node
-RUN /joystream/scripts/create-test-chainspec.sh
-
-FROM debian:stretch
-LABEL description="Joystream node"
-WORKDIR /joystream
-COPY --from=builder /joystream/target/release/joystream-node /joystream/node
-COPY --from=builder /joystream/target/release/wbuild/joystream-node-runtime/joystream_node_runtime.compact.wasm /joystream/runtime.compact.wasm
-COPY --from=builder /joystream/.tmp/chainspec.json /joystream/chainspec.json
-
-# confirm it works
-RUN /joystream/node --version
-
-# https://manpages.debian.org/stretch/coreutils/b2sum.1.en.html
-# RUN apt-get install coreutils
-# print the blake2 256 hash of the wasm blob
-RUN b2sum -l 256 /joystream/runtime.compact.wasm
-# print the blake2 512 hash of the wasm blob
-RUN b2sum -l 512 /joystream/runtime.compact.wasm
-
-EXPOSE 30333 9933 9944
-
-# Use these volumes to persits chain state and keystore, eg.:
-# --base-path /data
-# optionally separate keystore (otherwise it will be stored in the base path)
-# --keystore-path /keystore
-# if base-path isn't specified, chain state is stored inside container in ~/.local/share/joystream-node/
-# which is not ideal
-VOLUME ["/data", "/keystore"]
-
-ENTRYPOINT ["/joystream/node"]

+ 1 - 1
devops/dockerfiles/rust-builder/Dockerfile

@@ -5,4 +5,4 @@ WORKDIR /setup
 COPY setup.sh /setup
 ENV TERM=xterm
 
-RUN ./setup.sh
+RUN ./setup.sh

+ 4 - 0
scripts/alter-block-creation-time.sh

@@ -0,0 +1,4 @@
+#!/bin/bash
+
+perl -i -pe's/pub const MILLISECS_PER_BLOCK: Moment = 6000;/pub const MILLISECS_PER_BLOCK: Moment = 2000;/' runtime/src/constants.rs
+perl -i -pe's/pub const SLOT_DURATION: Moment = 6000;/pub const SLOT_DURATION: Moment = 2000;/' runtime/src/constants.rs

+ 0 - 7
scripts/build-joystream-testing-node-docker-image.sh

@@ -1,7 +0,0 @@
-#!/usr/bin/env bash
-
-# Build the node and runtime image
-docker build --tag joystream/node-testing \
-    --file ./devops/dockerfiles/ansible-node/Dockerfile \
-    .
-

ファイルの差分が大きいため隠しています
+ 21 - 0
testnets/nicaea-exported-state/chain_spec.json


ファイルの差分が大きいため隠しています
+ 0 - 0
testnets/nicaea-exported-state/content.json


ファイルの差分が大きいため隠しています
+ 0 - 0
testnets/nicaea-exported-state/forum.json


ファイルの差分が大きいため隠しています
+ 0 - 0
testnets/nicaea-exported-state/members.json


ファイルの差分が大きいため隠しています
+ 99 - 0
testnets/nicaea-exported-state/raw_chain_spec.json


+ 3 - 1
tests/network-tests/.env

@@ -1,5 +1,7 @@
 # Address of the Joystream node.
 NODE_URL = ws://127.0.0.1:9944
+# Path to the database for shared keys and nonce
+DB_PATH = ../../.tmp/db.json
 # Account which is expected to provide sufficient funds to test accounts.
 SUDO_ACCOUNT_URI = //Alice
 # Amount of members able to buy membership in membership creation test.
@@ -49,4 +51,4 @@ SLASH_AMOUNT = 2
 # Stake decrement amount for manage working group lead testing scenario
 STAKE_DECREMENT = 3
 # Mint capacity increment value for working gorup mint capacity test
-MINT_CAPACITY_INCREMENT = 11
+MINT_CAPACITY_INCREMENT = 1000

+ 9 - 2
tests/network-tests/.eslintrc.js

@@ -1,5 +1,12 @@
 module.exports = {
     env: {
         node: true,
-    }
-}
+    },
+  rules: {
+      'no-async-promise-executor': 'off',
+      'no-useless-return': 'off',
+      'new-cap': 'off',
+      // Disabled because of the false positive bug: https://github.com/eslint/eslint/issues/11899
+      'require-atomic-updates': 'off',
+  }
+}

+ 6 - 4
tests/network-tests/package.json

@@ -4,10 +4,10 @@
   "license": "GPL-3.0-only",
   "scripts": {
     "build": "tsc --build tsconfig.json",
-    "test": "tap --files src/iznik/tests/proposals/*Test.ts --files src/iznik/tests/workingGroup/*Test.ts -T",
+    "test": "rm -f ../../.tmp/db.json && tap --files src/iznik/tests/unknown.unknown src/iznik/tests/councilSetup.ts src/iznik/tests/proposals/*Test.ts src/iznik/tests/leaderSetup.ts src/iznik/tests/workingGroup/*Test.ts -T",
     "test-migration-constantinople": "tap --files src/rome/tests/romeRuntimeUpgradeTest.ts --files src/constantinople/tests/electingCouncilTest.ts -T",
     "test-migration-nicaea": "tap --files src/constantinople/tests/proposals/updateRuntimeTest.ts --files src/nicaea/tests/electingCouncilTest.ts -T",
-    "debug": "tap --files src/iznik/tests/proposals/manageLeaderRoleTest.ts -T",
+    "debug": "tap --files src/iznik/tests/workingGroup/workerPayoutTest.ts -T",
     "lint": "eslint . --quiet --ext .ts",
     "checks": "yarn lint && tsc --noEmit --pretty && prettier ./ --check",
     "format": "prettier ./ --write "
@@ -16,13 +16,15 @@
     "@constantinople/types@npm:@joystream/types": "^0.10.0",
     "@nicaea/types@npm:@joystream/types": "^0.12.0",
     "@alexandria/types": "link:../../types",
-    "@polkadot/api": "^0.96.1",
-    "@polkadot/keyring": "^1.7.0-beta.5",
+    "@polkadot/api": "1.26.1",
+    "@polkadot/keyring": "3.0.1",
     "@rome/types@npm:@joystream/types": "^0.7.0",
     "@types/bn.js": "^4.11.5",
+    "@types/lowdb": "^1.0.9",
     "bn.js": "^4.11.8",
     "dotenv": "^8.2.0",
     "fs": "^0.0.1-security",
+    "lowdb": "^1.0.0",
     "uuid": "^7.0.3"
   },
   "devDependencies": {

+ 106 - 0
tests/network-tests/src/iznik/services/dbService.ts

@@ -0,0 +1,106 @@
+import lowdb from 'lowdb/lib/main'
+import FileSync from 'lowdb/adapters/FileSync'
+import { KeyringPair, KeyringPair$Json } from '@polkadot/keyring/types'
+import Keyring from '@polkadot/keyring'
+import BN from 'bn.js'
+
+export class DbService {
+  private static instance: DbService
+
+  private adapter: any
+  private db: any
+  private keyring: Keyring
+  private dbPath: string
+
+  private static MEMBERS_KEY = 'members'
+  private static COUNCIL_KEY = 'council'
+  private static LEADER_KEY = 'leader'
+  private static NONCE_KEY = 'nonce'
+
+  private constructor() {
+    this.keyring = new Keyring({ type: 'sr25519' })
+    this.dbPath = process.env.DB_PATH!
+    this.adapter = new FileSync(this.dbPath)
+    this.db = lowdb(this.adapter)
+  }
+
+  public static getInstance(): DbService {
+    if (!DbService.instance) {
+      DbService.instance = new DbService()
+    }
+    return DbService.instance
+  }
+
+  public setCouncil(council: KeyringPair[]): void {
+    council.forEach((keyPair, index) => {
+      this.db.set(`${DbService.COUNCIL_KEY}.${index}`, keyPair.toJson()).write()
+    })
+  }
+
+  public getCouncil(): KeyringPair[] {
+    const council: KeyringPair[] = []
+    const jsonKeyringPairs: KeyringPair$Json[] = this.db.get(DbService.COUNCIL_KEY).value()
+    jsonKeyringPairs.forEach((jsonKeyringPair) => {
+      const keyPair: KeyringPair = this.keyring.addFromJson(jsonKeyringPair)
+      keyPair.decodePkcs8()
+      council.push(keyPair)
+    })
+    return council
+  }
+
+  public hasCouncil(): boolean {
+    return this.db.has(DbService.COUNCIL_KEY).value()
+  }
+
+  public setMembers(members: KeyringPair[]): void {
+    members.forEach((keyPair, index) => {
+      this.db.set(`${DbService.MEMBERS_KEY}.${index}`, keyPair.toJson()).write()
+    })
+  }
+
+  public getMembers(): KeyringPair[] {
+    const members: KeyringPair[] = []
+    const jsonKeyringPairs: KeyringPair$Json[] = this.db.get(DbService.MEMBERS_KEY).value()
+    jsonKeyringPairs.forEach((jsonKeyringPair) => {
+      const keyPair: KeyringPair = this.keyring.addFromJson(jsonKeyringPair)
+      keyPair.decodePkcs8()
+      members.push(keyPair)
+    })
+    return members
+  }
+
+  public hasMembers(): boolean {
+    return this.db.has(DbService.MEMBERS_KEY).value()
+  }
+
+  public setLeader(leader: KeyringPair, workingGroup: string): void {
+    this.db.set(`${workingGroup}.${DbService.LEADER_KEY}`, leader.toJson()).write()
+  }
+
+  public getLeader(workingGroup: string): KeyringPair {
+    const jsonKeyringPair: KeyringPair$Json = this.db.get(`${workingGroup}.${DbService.LEADER_KEY}`).value()
+    const keyPair: KeyringPair = this.keyring.addFromJson(jsonKeyringPair)
+    keyPair.decodePkcs8()
+    return keyPair
+  }
+
+  public hasLeader(workingGroup: string): boolean {
+    return this.db.has(`${workingGroup}.${DbService.LEADER_KEY}`).value()
+  }
+
+  public setNonce(address: string, nonce: BN): void {
+    this.db.set(`${DbService.NONCE_KEY}.${address}`, nonce.toString()).write()
+  }
+
+  public getNonce(address: string): BN {
+    return new BN(this.db.get(`${DbService.NONCE_KEY}.${address}`).value() as string)
+  }
+
+  public hasNonce(address: string): boolean {
+    return this.db.has(`${DbService.NONCE_KEY}.${address}`).value()
+  }
+
+  public removeNonce(address: string): void {
+    this.db.unset(`${DbService.NONCE_KEY}.${address}`).write()
+  }
+}

+ 2 - 4
tests/network-tests/src/iznik/tests/council/electingCouncilTest.ts

@@ -4,17 +4,15 @@ import { Keyring, WsProvider } from '@polkadot/api'
 import { setTestTimeout } from '../../utils/setTestTimeout'
 import BN from 'bn.js'
 import tap from 'tap'
-import { registerJoystreamTypes } from '@alexandria/types'
 import { ApiWrapper } from '../../utils/apiWrapper'
 import { closeApi } from '../../utils/closeApi'
 import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule'
 import { ElectCouncilFixture } from '../fixtures/councilElectionModule'
 import { Utils } from '../../utils/utils'
-import { PaidTermId } from '@nicaea/types/members'
+import { PaidTermId } from '@alexandria/types/members'
 
 tap.mocha.describe('Electing council scenario', async () => {
   initConfig()
-  registerJoystreamTypes()
 
   const nodeUrl: string = process.env.NODE_URL!
   const sudoUri: string = process.env.SUDO_ACCOUNT_URI!
@@ -26,7 +24,7 @@ tap.mocha.describe('Electing council scenario', async () => {
   const N: number = +process.env.MEMBERSHIP_CREATION_N!
   const m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
   const m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
-  const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!)
+  const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!))
   const K: number = +process.env.COUNCIL_ELECTION_K!
   const greaterStake: BN = new BN(+process.env.COUNCIL_STAKE_GREATER_AMOUNT!)
   const lesserStake: BN = new BN(+process.env.COUNCIL_STAKE_LESSER_AMOUNT!)

+ 57 - 0
tests/network-tests/src/iznik/tests/councilSetup.ts

@@ -0,0 +1,57 @@
+import { KeyringPair } from '@polkadot/keyring/types'
+import { Keyring, WsProvider } from '@polkadot/api'
+import BN from 'bn.js'
+import tap from 'tap'
+import { PaidTermId } from '@alexandria/types/members'
+import { DbService } from '../services/dbService'
+import { initConfig } from '../utils/config'
+import { ApiWrapper } from '../utils/apiWrapper'
+import { Utils } from '../utils/utils'
+import { setTestTimeout } from '../utils/setTestTimeout'
+import { closeApi } from '../utils/closeApi'
+import { CouncilElectionHappyCaseFixture } from './fixtures/councilElectionHappyCase'
+
+tap.mocha.describe('Electing council scenario', async () => {
+  initConfig()
+
+  const nodeUrl: string = process.env.NODE_URL!
+  const sudoUri: string = process.env.SUDO_ACCOUNT_URI!
+  const keyring = new Keyring({ type: 'sr25519' })
+  const db: DbService = DbService.getInstance()
+  if (db.hasCouncil()) {
+    return
+  }
+
+  const provider = new WsProvider(nodeUrl)
+  const apiWrapper: ApiWrapper = await ApiWrapper.create(provider)
+  const sudo: KeyringPair = keyring.addFromUri(sudoUri)
+
+  const N: number = +process.env.MEMBERSHIP_CREATION_N!
+  const m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  const m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!))
+  const K: number = +process.env.COUNCIL_ELECTION_K!
+  const greaterStake: BN = new BN(+process.env.COUNCIL_STAKE_GREATER_AMOUNT!)
+  const lesserStake: BN = new BN(+process.env.COUNCIL_STAKE_LESSER_AMOUNT!)
+
+  const durationInBlocks = 25
+
+  setTestTimeout(apiWrapper, durationInBlocks)
+
+  const councilElectionHappyCaseFixture = new CouncilElectionHappyCaseFixture(
+    apiWrapper,
+    sudo,
+    m1KeyPairs,
+    m2KeyPairs,
+    paidTerms,
+    K,
+    greaterStake,
+    lesserStake
+  )
+  await councilElectionHappyCaseFixture.runner(false)
+
+  db.setMembers(m1KeyPairs)
+  db.setCouncil(m2KeyPairs)
+
+  closeApi(apiWrapper)
+})

+ 68 - 0
tests/network-tests/src/iznik/tests/fixtures/councilElectionHappyCase.ts

@@ -0,0 +1,68 @@
+import { Fixture } from './interfaces/fixture'
+import { BuyMembershipHappyCaseFixture } from './membershipModule'
+import tap from 'tap'
+import { ElectCouncilFixture } from './councilElectionModule'
+import { ApiWrapper } from '../../utils/apiWrapper'
+import { KeyringPair } from '@polkadot/keyring/types'
+import { PaidTermId } from '@alexandria/types/members'
+import BN from 'bn.js'
+
+export class CouncilElectionHappyCaseFixture implements Fixture {
+  private apiWrapper: ApiWrapper
+  private sudo: KeyringPair
+  private membersKeyPairs: KeyringPair[]
+  private councilKeyPairs: KeyringPair[]
+  private paidTerms: PaidTermId
+  private k: number
+  private greaterStake: BN
+  private lesserStake: BN
+
+  constructor(
+    apiWrapper: ApiWrapper,
+    sudo: KeyringPair,
+    membersKeyPairs: KeyringPair[],
+    councilKeyPairs: KeyringPair[],
+    paidTerms: PaidTermId,
+    k: number,
+    greaterStake: BN,
+    lesserStake: BN
+  ) {
+    this.apiWrapper = apiWrapper
+    this.sudo = sudo
+    this.membersKeyPairs = membersKeyPairs
+    this.councilKeyPairs = councilKeyPairs
+    this.paidTerms = paidTerms
+    this.k = k
+    this.greaterStake = greaterStake
+    this.lesserStake = lesserStake
+  }
+
+  public async runner(expectFailure: boolean): Promise<void> {
+    const firstMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
+      this.apiWrapper,
+      this.sudo,
+      this.membersKeyPairs,
+      this.paidTerms
+    )
+    tap.test('Creating first set of members', async () => firstMemberSetFixture.runner(false))
+
+    const secondMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
+      this.apiWrapper,
+      this.sudo,
+      this.councilKeyPairs,
+      this.paidTerms
+    )
+    tap.test('Creating second set of members', async () => secondMemberSetFixture.runner(false))
+
+    const electCouncilFixture: ElectCouncilFixture = new ElectCouncilFixture(
+      this.apiWrapper,
+      this.membersKeyPairs,
+      this.councilKeyPairs,
+      this.k,
+      this.sudo,
+      this.greaterStake,
+      this.lesserStake
+    )
+    tap.test('Elect council', async () => electCouncilFixture.runner(false))
+  }
+}

+ 25 - 25
tests/network-tests/src/iznik/tests/fixtures/councilElectionModule.ts

@@ -9,8 +9,8 @@ import { Fixture } from './interfaces/fixture'
 
 export class ElectCouncilFixture implements Fixture {
   private apiWrapper: ApiWrapper
-  private m1KeyPairs: KeyringPair[]
-  private m2KeyPairs: KeyringPair[]
+  private membersKeyPairs: KeyringPair[]
+  private councilKeyPairs: KeyringPair[]
   private k: number
   private sudo: KeyringPair
   private greaterStake: BN
@@ -18,16 +18,16 @@ export class ElectCouncilFixture implements Fixture {
 
   public constructor(
     apiWrapper: ApiWrapper,
-    m1KeyPairs: KeyringPair[],
-    m2KeyPairs: KeyringPair[],
+    membersKeyPairs: KeyringPair[],
+    councilKeyPairs: KeyringPair[],
     k: number,
     sudo: KeyringPair,
     greaterStake: BN,
     lesserStake: BN
   ) {
     this.apiWrapper = apiWrapper
-    this.m1KeyPairs = m1KeyPairs
-    this.m2KeyPairs = m2KeyPairs
+    this.membersKeyPairs = membersKeyPairs
+    this.councilKeyPairs = councilKeyPairs
     this.k = k
     this.sudo = sudo
     this.greaterStake = greaterStake
@@ -43,7 +43,7 @@ export class ElectCouncilFixture implements Fixture {
       this.greaterStake
     )
     const salt: string[] = []
-    this.m1KeyPairs.forEach(() => {
+    this.membersKeyPairs.forEach(() => {
       salt.push(''.concat(uuid().replace(/-/g, '')))
     })
     const revealVoteFee: BN = this.apiWrapper.estimateRevealVoteFee(this.sudo.address, salt[0])
@@ -51,19 +51,19 @@ export class ElectCouncilFixture implements Fixture {
     // Topping the balances
     await this.apiWrapper.transferBalanceToAccounts(
       this.sudo,
-      this.m2KeyPairs,
+      this.councilKeyPairs,
       applyForCouncilFee.add(this.greaterStake)
     )
     await this.apiWrapper.transferBalanceToAccounts(
       this.sudo,
-      this.m1KeyPairs,
+      this.membersKeyPairs,
       voteForCouncilFee.add(revealVoteFee).add(this.greaterStake)
     )
 
     // First K members stake more
     await this.apiWrapper.sudoStartAnnouncingPerion(this.sudo, now.addn(100))
-    await this.apiWrapper.batchApplyForCouncilElection(this.m2KeyPairs.slice(0, this.k), this.greaterStake)
-    this.m2KeyPairs.slice(0, this.k).forEach((keyPair) =>
+    await this.apiWrapper.batchApplyForCouncilElection(this.councilKeyPairs.slice(0, this.k), this.greaterStake)
+    this.councilKeyPairs.slice(0, this.k).forEach((keyPair) =>
       this.apiWrapper.getCouncilElectionStake(keyPair.address).then((stake) => {
         assert(
           stake.eq(this.greaterStake),
@@ -73,8 +73,8 @@ export class ElectCouncilFixture implements Fixture {
     )
 
     // Last members stake less
-    await this.apiWrapper.batchApplyForCouncilElection(this.m2KeyPairs.slice(this.k), this.lesserStake)
-    this.m2KeyPairs.slice(this.k).forEach((keyPair) =>
+    await this.apiWrapper.batchApplyForCouncilElection(this.councilKeyPairs.slice(this.k), this.lesserStake)
+    this.councilKeyPairs.slice(this.k).forEach((keyPair) =>
       this.apiWrapper.getCouncilElectionStake(keyPair.address).then((stake) => {
         assert(
           stake.eq(this.lesserStake),
@@ -86,14 +86,14 @@ export class ElectCouncilFixture implements Fixture {
     // Voting
     await this.apiWrapper.sudoStartVotingPerion(this.sudo, now.addn(100))
     await this.apiWrapper.batchVoteForCouncilMember(
-      this.m1KeyPairs.slice(0, this.k),
-      this.m2KeyPairs.slice(0, this.k),
+      this.membersKeyPairs.slice(0, this.k),
+      this.councilKeyPairs.slice(0, this.k),
       salt.slice(0, this.k),
       this.lesserStake
     )
     await this.apiWrapper.batchVoteForCouncilMember(
-      this.m1KeyPairs.slice(this.k),
-      this.m2KeyPairs.slice(this.k),
+      this.membersKeyPairs.slice(this.k),
+      this.councilKeyPairs.slice(this.k),
       salt.slice(this.k),
       this.greaterStake
     )
@@ -101,13 +101,13 @@ export class ElectCouncilFixture implements Fixture {
     // Revealing
     await this.apiWrapper.sudoStartRevealingPerion(this.sudo, now.addn(100))
     await this.apiWrapper.batchRevealVote(
-      this.m1KeyPairs.slice(0, this.k),
-      this.m2KeyPairs.slice(0, this.k),
+      this.membersKeyPairs.slice(0, this.k),
+      this.councilKeyPairs.slice(0, this.k),
       salt.slice(0, this.k)
     )
     await this.apiWrapper.batchRevealVote(
-      this.m1KeyPairs.slice(this.k),
-      this.m2KeyPairs.slice(this.k),
+      this.membersKeyPairs.slice(this.k),
+      this.councilKeyPairs.slice(this.k),
       salt.slice(this.k)
     )
     now = await this.apiWrapper.getBestBlock()
@@ -119,14 +119,14 @@ export class ElectCouncilFixture implements Fixture {
     const seats: Seat[] = await this.apiWrapper.getCouncil()
 
     // Preparing collections to increase assertion readability
-    const m2addresses: string[] = this.m2KeyPairs.map((keyPair) => keyPair.address)
-    const m1addresses: string[] = this.m1KeyPairs.map((keyPair) => keyPair.address)
+    const councilAddresses: string[] = this.councilKeyPairs.map((keyPair) => keyPair.address)
+    const membersAddresses: string[] = this.membersKeyPairs.map((keyPair) => keyPair.address)
     const members: string[] = seats.map((seat) => seat.member.toString())
     const bakers: string[] = seats.map((seat) => seat.backers.map((baker) => baker.member.toString())).flat()
 
     // Assertions
-    m2addresses.forEach((address) => assert(members.includes(address), `Account ${address} is not in the council`))
-    m1addresses.forEach((address) => assert(bakers.includes(address), `Account ${address} is not in the voters`))
+    councilAddresses.forEach((address) => assert(members.includes(address), `Account ${address} is not in the council`))
+    membersAddresses.forEach((address) => assert(bakers.includes(address), `Account ${address} is not in the voters`))
     seats.forEach((seat) =>
       assert(
         Utils.getTotalStake(seat).eq(this.greaterStake.add(this.lesserStake)),

+ 126 - 0
tests/network-tests/src/iznik/tests/fixtures/leaderHiringHappyCase.ts

@@ -0,0 +1,126 @@
+import { Fixture } from './interfaces/fixture'
+import tap from 'tap'
+import {
+  AddLeaderOpeningFixture,
+  ApplyForOpeningFixture,
+  BeginLeaderApplicationReviewFixture,
+  FillLeaderOpeningFixture,
+} from './workingGroupModule'
+import { BuyMembershipHappyCaseFixture } from './membershipModule'
+import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper'
+import { OpeningId } from '@alexandria/types/hiring'
+import { KeyringPair } from '@polkadot/keyring/types'
+import { PaidTermId } from '@alexandria/types/members'
+import BN from 'bn.js'
+
+export class LeaderHiringHappyCaseFixture implements Fixture {
+  private apiWrapper: ApiWrapper
+  private sudo: KeyringPair
+  private nKeyPairs: KeyringPair[]
+  private leadKeyPair: KeyringPair[]
+  private paidTerms: PaidTermId
+  private applicationStake: BN
+  private roleStake: BN
+  private openingActivationDelay: BN
+  private rewardInterval: BN
+  private firstRewardInterval: BN
+  private payoutAmount: BN
+  private workingGroup: WorkingGroups
+
+  constructor(
+    apiWrapper: ApiWrapper,
+    sudo: KeyringPair,
+    nKeyPairs: KeyringPair[],
+    leadKeyPair: KeyringPair[],
+    paidTerms: PaidTermId,
+    applicationStake: BN,
+    roleStake: BN,
+    openingActivationDelay: BN,
+    rewardInterval: BN,
+    firstRewardInterval: BN,
+    payoutAmount: BN,
+    workingGroup: WorkingGroups
+  ) {
+    this.apiWrapper = apiWrapper
+    this.sudo = sudo
+    this.nKeyPairs = nKeyPairs
+    this.leadKeyPair = leadKeyPair
+    this.paidTerms = paidTerms
+    this.applicationStake = applicationStake
+    this.roleStake = roleStake
+    this.openingActivationDelay = openingActivationDelay
+    this.rewardInterval = rewardInterval
+    this.firstRewardInterval = firstRewardInterval
+    this.payoutAmount = payoutAmount
+    this.workingGroup = workingGroup
+  }
+
+  public async runner(expectFailure: boolean): Promise<void> {
+    const happyCaseFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
+      this.apiWrapper,
+      this.sudo,
+      this.nKeyPairs,
+      this.paidTerms
+    )
+    tap.test('Creating a set of members', async () => happyCaseFixture.runner(false))
+
+    const leaderHappyCaseFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
+      this.apiWrapper,
+      this.sudo,
+      this.leadKeyPair,
+      this.paidTerms
+    )
+    tap.test('Buying membership for leader account', async () => leaderHappyCaseFixture.runner(false))
+
+    const addLeaderOpeningFixture: AddLeaderOpeningFixture = new AddLeaderOpeningFixture(
+      this.apiWrapper,
+      this.nKeyPairs,
+      this.sudo,
+      this.applicationStake,
+      this.roleStake,
+      this.openingActivationDelay,
+      this.workingGroup
+    )
+    tap.test('Add lead opening', async () => await addLeaderOpeningFixture.runner(false))
+
+    let applyForLeaderOpeningFixture: ApplyForOpeningFixture
+    tap.test('Apply for lead opening', async () => {
+      applyForLeaderOpeningFixture = new ApplyForOpeningFixture(
+        this.apiWrapper,
+        this.leadKeyPair,
+        this.sudo,
+        this.applicationStake,
+        this.roleStake,
+        addLeaderOpeningFixture.getCreatedOpeningId() as OpeningId,
+        this.workingGroup
+      )
+      await applyForLeaderOpeningFixture.runner(false)
+    })
+
+    let beginLeaderApplicationReviewFixture: BeginLeaderApplicationReviewFixture
+    tap.test('Begin lead application review', async () => {
+      beginLeaderApplicationReviewFixture = new BeginLeaderApplicationReviewFixture(
+        this.apiWrapper,
+        this.sudo,
+        addLeaderOpeningFixture.getCreatedOpeningId() as OpeningId,
+        this.workingGroup
+      )
+      await beginLeaderApplicationReviewFixture.runner(false)
+    })
+
+    let fillLeaderOpeningFixture: FillLeaderOpeningFixture
+    tap.test('Fill lead opening', async () => {
+      fillLeaderOpeningFixture = new FillLeaderOpeningFixture(
+        this.apiWrapper,
+        this.leadKeyPair,
+        this.sudo,
+        addLeaderOpeningFixture.getCreatedOpeningId() as OpeningId,
+        this.firstRewardInterval,
+        this.rewardInterval,
+        this.payoutAmount,
+        this.workingGroup
+      )
+      await fillLeaderOpeningFixture.runner(false)
+    })
+  }
+}

+ 16 - 11
tests/network-tests/src/iznik/tests/fixtures/membershipModule.ts

@@ -3,17 +3,17 @@ import { KeyringPair } from '@polkadot/keyring/types'
 import BN from 'bn.js'
 import { assert } from 'chai'
 import { Fixture } from './interfaces/fixture'
-import { PaidTermId } from '@nicaea/types/members'
+import { PaidTermId } from '@alexandria/types/members'
 
 export class BuyMembershipHappyCaseFixture implements Fixture {
   private apiWrapper: ApiWrapper
-  private sudo: KeyringPair
+  private treasury: KeyringPair
   private keyPairs: KeyringPair[]
   private paidTerms: PaidTermId
 
-  public constructor(apiWrapper: ApiWrapper, sudo: KeyringPair, keyPairs: KeyringPair[], paidTerms: PaidTermId) {
+  public constructor(apiWrapper: ApiWrapper, treasury: KeyringPair, keyPairs: KeyringPair[], paidTerms: PaidTermId) {
     this.apiWrapper = apiWrapper
-    this.sudo = sudo
+    this.treasury = treasury
     this.keyPairs = keyPairs
     this.paidTerms = paidTerms
   }
@@ -22,12 +22,12 @@ export class BuyMembershipHappyCaseFixture implements Fixture {
     // Fee estimation and transfer
     const membershipFee: BN = await this.apiWrapper.getMembershipFee(this.paidTerms)
     const membershipTransactionFee: BN = this.apiWrapper.estimateBuyMembershipFee(
-      this.sudo,
+      this.treasury,
       this.paidTerms,
       'member_name_which_is_longer_than_expected'
     )
     await this.apiWrapper.transferBalanceToAccounts(
-      this.sudo,
+      this.treasury,
       this.keyPairs,
       membershipTransactionFee.add(new BN(membershipFee))
     )
@@ -57,26 +57,31 @@ export class BuyMembershipHappyCaseFixture implements Fixture {
 
 export class BuyMembershipWithInsufficienFundsFixture implements Fixture {
   private apiWrapper: ApiWrapper
-  private sudo: KeyringPair
+  private treasury: KeyringPair
   private aKeyPair: KeyringPair
   private paidTerms: PaidTermId
 
-  public constructor(apiWrapper: ApiWrapper, sudo: KeyringPair, aKeyPair: KeyringPair, paidTerms: PaidTermId) {
+  public constructor(apiWrapper: ApiWrapper, treasury: KeyringPair, aKeyPair: KeyringPair, paidTerms: PaidTermId) {
     this.apiWrapper = apiWrapper
-    this.sudo = sudo
+    this.treasury = treasury
     this.aKeyPair = aKeyPair
     this.paidTerms = paidTerms
   }
 
   public async runner(expectFailure: boolean) {
+    // Assertions
+    this.apiWrapper
+      .getMemberIds(this.aKeyPair.address)
+      .then((membership) => assert(membership.length === 0, 'Account A is a member'))
+
     // Fee estimation and transfer
     const membershipFee: BN = await this.apiWrapper.getMembershipFee(this.paidTerms)
     const membershipTransactionFee: BN = this.apiWrapper.estimateBuyMembershipFee(
-      this.sudo,
+      this.treasury,
       this.paidTerms,
       'member_name_which_is_longer_than_expected'
     )
-    await this.apiWrapper.transferBalance(this.sudo, this.aKeyPair.address, membershipTransactionFee)
+    await this.apiWrapper.transferBalance(this.treasury, this.aKeyPair.address, membershipTransactionFee)
 
     // Balance assertion
     await this.apiWrapper

ファイルの差分が大きいため隠しています
+ 283 - 233
tests/network-tests/src/iznik/tests/fixtures/proposalsModule.ts


+ 137 - 214
tests/network-tests/src/iznik/tests/fixtures/workingGroupModule.ts

@@ -2,35 +2,20 @@ import BN from 'bn.js'
 import { assert } from 'chai'
 import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper'
 import { KeyringPair } from '@polkadot/keyring/types'
-import { Balance, BlockNumber, Event } from '@polkadot/types/interfaces'
+import { Event } from '@polkadot/types/interfaces'
 import { Keyring } from '@polkadot/api'
-import { Option, u32 } from '@polkadot/types'
 import { v4 as uuid } from 'uuid'
 import { RewardRelationship } from '@alexandria/types/recurring-rewards'
-import {
-  Application,
-  ApplicationIdToWorkerIdMap,
-  SlashingTerms,
-  Worker,
-  WorkerId,
-  WorkingGroupOpeningPolicyCommitment,
-} from '@alexandria/types/working-group'
+import { Application, ApplicationIdToWorkerIdMap, Worker, WorkerId } from '@alexandria/types/working-group'
 import { Utils } from '../../utils/utils'
-import {
-  ActivateOpeningAt,
-  ApplicationId,
-  ApplicationRationingPolicy,
-  Opening as HiringOpening,
-  OpeningId,
-  StakingPolicy,
-} from '@alexandria/types/hiring'
+import { ApplicationId, Opening as HiringOpening, OpeningId } from '@alexandria/types/hiring'
 import { Fixture } from './interfaces/fixture'
 
 export class AddWorkerOpeningFixture implements Fixture {
   private apiWrapper: ApiWrapper
   private membersKeyPairs: KeyringPair[]
   private lead: KeyringPair
-  private sudo: KeyringPair
+  private treasury: KeyringPair
   private applicationStake: BN
   private roleStake: BN
   private activationDelay: BN
@@ -39,7 +24,7 @@ export class AddWorkerOpeningFixture implements Fixture {
 
   private result: OpeningId | undefined
 
-  public getResult(): OpeningId | undefined {
+  public getCreatedOpeningId(): OpeningId | undefined {
     return this.result
   }
 
@@ -47,7 +32,7 @@ export class AddWorkerOpeningFixture implements Fixture {
     apiWrapper: ApiWrapper,
     membersKeyPairs: KeyringPair[],
     lead: KeyringPair,
-    sudo: KeyringPair,
+    treasury: KeyringPair,
     applicationStake: BN,
     roleStake: BN,
     activationDelay: BN,
@@ -57,7 +42,7 @@ export class AddWorkerOpeningFixture implements Fixture {
     this.apiWrapper = apiWrapper
     this.membersKeyPairs = membersKeyPairs
     this.lead = lead
-    this.sudo = sudo
+    this.treasury = treasury
     this.applicationStake = applicationStake
     this.roleStake = roleStake
     this.activationDelay = activationDelay
@@ -66,65 +51,37 @@ export class AddWorkerOpeningFixture implements Fixture {
   }
 
   public async runner(expectFailure: boolean): Promise<void> {
-    // Worker opening construction
-    const activateAtBlock: ActivateOpeningAt = new ActivateOpeningAt(
-      this.activationDelay.eqn(0)
-        ? 'CurrentBlock'
-        : { ExactBlock: (await this.apiWrapper.getBestBlock()).add(this.activationDelay) }
-    )
-    const commitment: WorkingGroupOpeningPolicyCommitment = new WorkingGroupOpeningPolicyCommitment({
-      application_rationing_policy: new Option(ApplicationRationingPolicy, {
-        max_active_applicants: new BN(this.membersKeyPairs.length) as u32,
-      }),
-      max_review_period_length: new BN(32) as u32,
-      application_staking_policy: new Option(StakingPolicy, {
-        amount: this.applicationStake,
-        amount_mode: 'AtLeast',
-        crowded_out_unstaking_period_length: new BN(1),
-        review_period_expired_unstaking_period_length: new BN(1),
-      }),
-      role_staking_policy: new Option(StakingPolicy, {
-        amount: this.roleStake,
-        amount_mode: 'AtLeast',
-        crowded_out_unstaking_period_length: new BN(1),
-        review_period_expired_unstaking_period_length: new BN(1),
-      }),
-      role_slashing_terms: new SlashingTerms({
-        Slashable: {
-          max_count: new BN(1),
-          max_percent_pts_per_time: new BN(100),
-        },
-      }),
-      fill_opening_successful_applicant_application_stake_unstaking_period: new Option(
-        u32,
-        this.unstakingPeriod as BlockNumber
-      ),
-      fill_opening_failed_applicant_application_stake_unstaking_period: new Option(
-        u32,
-        this.unstakingPeriod as BlockNumber
-      ),
-      fill_opening_failed_applicant_role_stake_unstaking_period: new Option(u32, this.unstakingPeriod as BlockNumber),
-      terminate_application_stake_unstaking_period: new Option(u32, this.unstakingPeriod as BlockNumber),
-      terminate_role_stake_unstaking_period: new Option(u32, this.unstakingPeriod as BlockNumber),
-      exit_role_application_stake_unstaking_period: new Option(u32, this.unstakingPeriod as BlockNumber),
-      exit_role_stake_unstaking_period: new Option(u32, this.unstakingPeriod as BlockNumber),
-    })
-
     // Fee estimation and transfer
     const addOpeningFee: BN = this.apiWrapper.estimateAddOpeningFee(this.module)
-    await this.apiWrapper.transferBalance(this.sudo, this.lead.address, addOpeningFee)
+    await this.apiWrapper.transferBalance(this.treasury, this.lead.address, addOpeningFee)
 
     // Worker opening creation
     const addOpeningPromise: Promise<Event> = this.apiWrapper.expectEvent('OpeningAdded')
-    await this.apiWrapper.addOpening(
-      this.lead,
-      activateAtBlock,
-      commitment,
-      uuid().substring(0, 8),
-      'Worker',
-      this.module,
-      expectFailure
-    )
+    await this.apiWrapper.addOpening({
+      leader: this.lead,
+      activationDelay: this.activationDelay,
+      maxActiveApplicants: new BN(this.membersKeyPairs.length),
+      maxReviewPeriodLength: new BN(32),
+      applicationStakingPolicyAmount: this.applicationStake,
+      applicationCrowdedOutUnstakingPeriodLength: new BN(1),
+      applicationReviewPeriodExpiredUnstakingPeriodLength: new BN(1),
+      roleStakingPolicyAmount: this.roleStake,
+      roleCrowdedOutUnstakingPeriodLength: new BN(1),
+      roleReviewPeriodExpiredUnstakingPeriodLength: new BN(1),
+      slashableMaxCount: new BN(1),
+      slashableMaxPercentPtsPerTime: new BN(100),
+      fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod: this.unstakingPeriod,
+      fillOpeningFailedApplicantApplicationStakeUnstakingPeriod: this.unstakingPeriod,
+      fillOpeningFailedApplicantRoleStakeUnstakingPeriod: this.unstakingPeriod,
+      terminateApplicationStakeUnstakingPeriod: this.unstakingPeriod,
+      terminateRoleStakeUnstakingPeriod: this.unstakingPeriod,
+      exitRoleApplicationStakeUnstakingPeriod: this.unstakingPeriod,
+      exitRoleStakeUnstakingPeriod: this.unstakingPeriod,
+      text: uuid().substring(0, 8),
+      type: 'Worker',
+      module: this.module,
+      expectFailure: expectFailure,
+    })
     if (!expectFailure) {
       const openingId: OpeningId = (await addOpeningPromise).data[0] as OpeningId
       this.result = openingId
@@ -143,7 +100,7 @@ export class AddLeaderOpeningFixture implements Fixture {
 
   private result: OpeningId | undefined
 
-  public getResult(): OpeningId | undefined {
+  public getCreatedOpeningId(): OpeningId | undefined {
     return this.result
   }
 
@@ -166,53 +123,31 @@ export class AddLeaderOpeningFixture implements Fixture {
   }
 
   public async runner(expectFailure: boolean): Promise<void> {
-    // Leader opening creation
-    const activateAtBlock: ActivateOpeningAt = new ActivateOpeningAt(
-      this.activationDelay.eqn(0)
-        ? 'CurrentBlock'
-        : { ExactBlock: (await this.apiWrapper.getBestBlock()).add(this.activationDelay) }
-    )
-    const commitment: WorkingGroupOpeningPolicyCommitment = new WorkingGroupOpeningPolicyCommitment({
-      application_rationing_policy: new Option(ApplicationRationingPolicy, {
-        max_active_applicants: new BN(this.membersKeyPairs.length) as u32,
-      }),
-      max_review_period_length: new BN(32) as u32,
-      application_staking_policy: new Option(StakingPolicy, {
-        amount: this.applicationStake,
-        amount_mode: 'AtLeast',
-        crowded_out_unstaking_period_length: new BN(1),
-        review_period_expired_unstaking_period_length: new BN(1),
-      }),
-      role_staking_policy: new Option(StakingPolicy, {
-        amount: this.roleStake,
-        amount_mode: 'AtLeast',
-        crowded_out_unstaking_period_length: new BN(1),
-        review_period_expired_unstaking_period_length: new BN(1),
-      }),
-      role_slashing_terms: new SlashingTerms({
-        Slashable: {
-          max_count: new BN(1),
-          max_percent_pts_per_time: new BN(100),
-        },
-      }),
-      fill_opening_successful_applicant_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber),
-      fill_opening_failed_applicant_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber),
-      fill_opening_failed_applicant_role_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber),
-      terminate_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber),
-      terminate_role_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber),
-      exit_role_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber),
-      exit_role_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber),
-    })
-
     const addOpeningPromise: Promise<Event> = this.apiWrapper.expectEvent('OpeningAdded')
-    await this.apiWrapper.sudoAddOpening(
-      this.sudo,
-      activateAtBlock,
-      commitment,
-      uuid().substring(0, 8),
-      'Leader',
-      this.module
-    )
+    await this.apiWrapper.sudoAddOpening({
+      sudo: this.sudo,
+      activationDelay: this.activationDelay,
+      maxActiveApplicants: new BN(this.membersKeyPairs.length),
+      maxReviewPeriodLength: new BN(32),
+      applicationStakingPolicyAmount: this.applicationStake,
+      applicationCrowdedOutUnstakingPeriodLength: new BN(1),
+      applicationReviewPeriodExpiredUnstakingPeriodLength: new BN(1),
+      roleStakingPolicyAmount: this.roleStake,
+      roleCrowdedOutUnstakingPeriodLength: new BN(1),
+      roleReviewPeriodExpiredUnstakingPeriodLength: new BN(1),
+      slashableMaxCount: new BN(1),
+      slashableMaxPercentPtsPerTime: new BN(100),
+      fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod: new BN(1),
+      fillOpeningFailedApplicantApplicationStakeUnstakingPeriod: new BN(1),
+      fillOpeningFailedApplicantRoleStakeUnstakingPeriod: new BN(1),
+      terminateApplicationStakeUnstakingPeriod: new BN(1),
+      terminateRoleStakeUnstakingPeriod: new BN(1),
+      exitRoleApplicationStakeUnstakingPeriod: new BN(1),
+      exitRoleStakeUnstakingPeriod: new BN(1),
+      text: uuid().substring(0, 8),
+      type: 'Leader',
+      module: this.module,
+    })
     this.result = (await addOpeningPromise).data[0] as OpeningId
     if (expectFailure) {
       throw new Error('Successful fixture run while expecting failure')
@@ -223,20 +158,20 @@ export class AddLeaderOpeningFixture implements Fixture {
 export class AcceptApplicationsFixture implements Fixture {
   private apiWrapper: ApiWrapper
   private lead: KeyringPair
-  private sudo: KeyringPair
+  private treasury: KeyringPair
   private openingId: OpeningId
   private module: WorkingGroups
 
   public constructor(
     apiWrapper: ApiWrapper,
     lead: KeyringPair,
-    sudo: KeyringPair,
+    treasury: KeyringPair,
     openingId: OpeningId,
     module: WorkingGroups
   ) {
     this.apiWrapper = apiWrapper
     this.lead = lead
-    this.sudo = sudo
+    this.treasury = treasury
     this.openingId = openingId
     this.module = module
   }
@@ -244,7 +179,7 @@ export class AcceptApplicationsFixture implements Fixture {
   public async runner(expectFailure: boolean): Promise<void> {
     // Fee estimation and transfer
     const acceptApplicationsFee: BN = this.apiWrapper.estimateAcceptApplicationsFee(this.module)
-    await this.apiWrapper.transferBalance(this.sudo, this.lead.address, acceptApplicationsFee)
+    await this.apiWrapper.transferBalance(this.treasury, this.lead.address, acceptApplicationsFee)
 
     // Begin accepting applications
     await this.apiWrapper.acceptApplications(this.lead, this.openingId, this.module)
@@ -260,7 +195,7 @@ export class AcceptApplicationsFixture implements Fixture {
 export class ApplyForOpeningFixture implements Fixture {
   private apiWrapper: ApiWrapper
   private membersKeyPairs: KeyringPair[]
-  private sudo: KeyringPair
+  private treasury: KeyringPair
   private applicationStake: BN
   private roleStake: BN
   private openingId: OpeningId
@@ -269,7 +204,7 @@ export class ApplyForOpeningFixture implements Fixture {
   public constructor(
     apiWrapper: ApiWrapper,
     membersKeyPairs: KeyringPair[],
-    sudo: KeyringPair,
+    treasury: KeyringPair,
     applicationStake: BN,
     roleStake: BN,
     openingId: OpeningId,
@@ -277,7 +212,7 @@ export class ApplyForOpeningFixture implements Fixture {
   ) {
     this.apiWrapper = apiWrapper
     this.membersKeyPairs = membersKeyPairs
-    this.sudo = sudo
+    this.treasury = treasury
     this.applicationStake = applicationStake
     this.roleStake = roleStake
     this.openingId = openingId
@@ -287,10 +222,10 @@ export class ApplyForOpeningFixture implements Fixture {
   public async runner(expectFailure: boolean): Promise<void> {
     // Fee estimation and transfer
     const applyOnOpeningFee: BN = this.apiWrapper
-      .estimateApplyOnOpeningFee(this.sudo, this.module)
+      .estimateApplyOnOpeningFee(this.treasury, this.module)
       .add(this.applicationStake)
       .add(this.roleStake)
-    await this.apiWrapper.transferBalanceToAccounts(this.sudo, this.membersKeyPairs, applyOnOpeningFee)
+    await this.apiWrapper.transferBalanceToAccounts(this.treasury, this.membersKeyPairs, applyOnOpeningFee)
 
     // Applying for created worker opening
     await this.apiWrapper.batchApplyOnOpening(
@@ -308,20 +243,20 @@ export class ApplyForOpeningFixture implements Fixture {
 export class WithdrawApplicationFixture implements Fixture {
   private apiWrapper: ApiWrapper
   private membersKeyPairs: KeyringPair[]
-  private sudo: KeyringPair
+  private treasury: KeyringPair
   private module: WorkingGroups
 
-  constructor(apiWrapper: ApiWrapper, membersKeyPairs: KeyringPair[], sudo: KeyringPair, module: WorkingGroups) {
+  constructor(apiWrapper: ApiWrapper, membersKeyPairs: KeyringPair[], treasury: KeyringPair, module: WorkingGroups) {
     this.apiWrapper = apiWrapper
     this.membersKeyPairs = membersKeyPairs
-    this.sudo = sudo
+    this.treasury = treasury
     this.module = module
   }
 
   public async runner(expectFailure: boolean): Promise<void> {
     // Fee estimation and transfer
     const withdrawApplicaitonFee: BN = this.apiWrapper.estimateWithdrawApplicationFee(this.module)
-    await this.apiWrapper.transferBalanceToAccounts(this.sudo, this.membersKeyPairs, withdrawApplicaitonFee)
+    await this.apiWrapper.transferBalanceToAccounts(this.treasury, this.membersKeyPairs, withdrawApplicaitonFee)
 
     // Application withdrawal
     await this.apiWrapper.batchWithdrawApplication(this.membersKeyPairs, this.module)
@@ -343,20 +278,20 @@ export class WithdrawApplicationFixture implements Fixture {
 export class BeginApplicationReviewFixture implements Fixture {
   private apiWrapper: ApiWrapper
   private lead: KeyringPair
-  private sudo: KeyringPair
+  private treasury: KeyringPair
   private openingId: OpeningId
   private module: WorkingGroups
 
   constructor(
     apiWrapper: ApiWrapper,
     lead: KeyringPair,
-    sudo: KeyringPair,
+    treasury: KeyringPair,
     openingId: OpeningId,
     module: WorkingGroups
   ) {
     this.apiWrapper = apiWrapper
     this.lead = lead
-    this.sudo = sudo
+    this.treasury = treasury
     this.openingId = openingId
     this.module = module
   }
@@ -364,7 +299,7 @@ export class BeginApplicationReviewFixture implements Fixture {
   public async runner(expectFailure: boolean): Promise<void> {
     // Fee estimation and transfer
     const beginReviewFee: BN = this.apiWrapper.estimateBeginApplicantReviewFee(this.module)
-    await this.apiWrapper.transferBalance(this.sudo, this.lead.address, beginReviewFee)
+    await this.apiWrapper.transferBalance(this.treasury, this.lead.address, beginReviewFee)
 
     // Begin application review
     const beginApplicantReviewPromise: Promise<ApplicationId> = this.apiWrapper.expectApplicationReviewBegan()
@@ -402,7 +337,7 @@ export class FillOpeningFixture implements Fixture {
   private apiWrapper: ApiWrapper
   private membersKeyPairs: KeyringPair[]
   private lead: KeyringPair
-  private sudo: KeyringPair
+  private treasury: KeyringPair
   private openingId: OpeningId
   private firstPayoutInterval: BN
   private payoutInterval: BN
@@ -413,7 +348,7 @@ export class FillOpeningFixture implements Fixture {
     apiWrapper: ApiWrapper,
     membersKeyPairs: KeyringPair[],
     lead: KeyringPair,
-    sudo: KeyringPair,
+    treasury: KeyringPair,
     openingId: OpeningId,
     firstPayoutInterval: BN,
     payoutInterval: BN,
@@ -423,7 +358,7 @@ export class FillOpeningFixture implements Fixture {
     this.apiWrapper = apiWrapper
     this.membersKeyPairs = membersKeyPairs
     this.lead = lead
-    this.sudo = sudo
+    this.treasury = treasury
     this.openingId = openingId
     this.firstPayoutInterval = firstPayoutInterval
     this.payoutInterval = payoutInterval
@@ -434,7 +369,7 @@ export class FillOpeningFixture implements Fixture {
   public async runner(expectFailure: boolean): Promise<void> {
     // Fee estimation and transfer
     const beginReviewFee: BN = this.apiWrapper.estimateFillOpeningFee(this.module)
-    await this.apiWrapper.transferBalance(this.sudo, this.lead.address, beginReviewFee)
+    await this.apiWrapper.transferBalance(this.treasury, this.lead.address, beginReviewFee)
     const applicationIds: ApplicationId[] = (
       await Promise.all(
         this.membersKeyPairs.map(async (keypair) =>
@@ -442,6 +377,15 @@ export class FillOpeningFixture implements Fixture {
         )
       )
     ).flat()
+    // Assert max number of workers is not exceeded
+    const activeWorkersCount: BN = await this.apiWrapper.getActiveWorkersCount(this.module)
+    const maxWorkersCount: BN = this.apiWrapper.getMaxWorkersCount(this.module)
+    assert(
+      activeWorkersCount.addn(applicationIds.length).lte(maxWorkersCount),
+      `The number of workers ${activeWorkersCount.addn(
+        applicationIds.length
+      )} will exceed max workers count ${maxWorkersCount}`
+    )
 
     // Fill worker opening
     const now: BN = await this.apiWrapper.getBestBlock()
@@ -557,13 +501,13 @@ export class FillLeaderOpeningFixture implements Fixture {
 export class IncreaseStakeFixture implements Fixture {
   private apiWrapper: ApiWrapper
   private membersKeyPairs: KeyringPair[]
-  private sudo: KeyringPair
+  private treasury: KeyringPair
   private module: WorkingGroups
 
-  constructor(apiWrapper: ApiWrapper, membersKeyPairs: KeyringPair[], sudo: KeyringPair, module: WorkingGroups) {
+  constructor(apiWrapper: ApiWrapper, membersKeyPairs: KeyringPair[], treasury: KeyringPair, module: WorkingGroups) {
     this.apiWrapper = apiWrapper
     this.membersKeyPairs = membersKeyPairs
-    this.sudo = sudo
+    this.treasury = treasury
     this.module = module
   }
 
@@ -572,7 +516,7 @@ export class IncreaseStakeFixture implements Fixture {
     const increaseStakeFee: BN = this.apiWrapper.estimateIncreaseStakeFee(this.module)
     const stakeIncrement: BN = new BN(1)
     await this.apiWrapper.transferBalance(
-      this.sudo,
+      this.treasury,
       this.membersKeyPairs[0].address,
       increaseStakeFee.add(stakeIncrement)
     )
@@ -601,27 +545,30 @@ export class UpdateRewardAccountFixture implements Fixture {
   public apiWrapper: ApiWrapper
   public membersKeyPairs: KeyringPair[]
   public keyring: Keyring
-  public sudo: KeyringPair
+  public treasury: KeyringPair
   public module: WorkingGroups
 
   constructor(
     apiWrapper: ApiWrapper,
     membersKeyPairs: KeyringPair[],
     keyring: Keyring,
-    sudo: KeyringPair,
+    treasury: KeyringPair,
     module: WorkingGroups
   ) {
     this.apiWrapper = apiWrapper
     this.membersKeyPairs = membersKeyPairs
     this.keyring = keyring
-    this.sudo = sudo
+    this.treasury = treasury
     this.module = module
   }
 
   public async runner(expectFailure: boolean): Promise<void> {
     // Fee estimation and transfer
-    const updateRewardAccountFee: BN = this.apiWrapper.estimateUpdateRewardAccountFee(this.sudo.address, this.module)
-    await this.apiWrapper.transferBalance(this.sudo, this.membersKeyPairs[0].address, updateRewardAccountFee)
+    const updateRewardAccountFee: BN = this.apiWrapper.estimateUpdateRewardAccountFee(
+      this.treasury.address,
+      this.module
+    )
+    await this.apiWrapper.transferBalance(this.treasury, this.membersKeyPairs[0].address, updateRewardAccountFee)
     const workerId: WorkerId = await this.apiWrapper.getWorkerIdByRoleAccount(
       this.membersKeyPairs[0].address,
       this.module
@@ -645,27 +592,27 @@ export class UpdateRoleAccountFixture implements Fixture {
   private apiWrapper: ApiWrapper
   private membersKeyPairs: KeyringPair[]
   private keyring: Keyring
-  private sudo: KeyringPair
+  private treasury: KeyringPair
   private module: WorkingGroups
 
   constructor(
     apiWrapper: ApiWrapper,
     membersKeyPairs: KeyringPair[],
     keyring: Keyring,
-    sudo: KeyringPair,
+    treasury: KeyringPair,
     module: WorkingGroups
   ) {
     this.apiWrapper = apiWrapper
     this.membersKeyPairs = membersKeyPairs
     this.keyring = keyring
-    this.sudo = sudo
+    this.treasury = treasury
     this.module = module
   }
 
   public async runner(expectFailure: boolean): Promise<void> {
     // Fee estimation and transfer
-    const updateRoleAccountFee: BN = this.apiWrapper.estimateUpdateRoleAccountFee(this.sudo.address, this.module)
-    await this.apiWrapper.transferBalance(this.sudo, this.membersKeyPairs[0].address, updateRoleAccountFee)
+    const updateRoleAccountFee: BN = this.apiWrapper.estimateUpdateRoleAccountFee(this.treasury.address, this.module)
+    await this.apiWrapper.transferBalance(this.treasury, this.membersKeyPairs[0].address, updateRoleAccountFee)
     const workerId: WorkerId = await this.apiWrapper.getWorkerIdByRoleAccount(
       this.membersKeyPairs[0].address,
       this.module
@@ -693,20 +640,20 @@ export class TerminateApplicationsFixture implements Fixture {
   private apiWrapper: ApiWrapper
   private membersKeyPairs: KeyringPair[]
   private lead: KeyringPair
-  private sudo: KeyringPair
+  private treasury: KeyringPair
   private module: WorkingGroups
 
   constructor(
     apiWrapper: ApiWrapper,
     membersKeyPairs: KeyringPair[],
     lead: KeyringPair,
-    sudo: KeyringPair,
+    treasury: KeyringPair,
     module: WorkingGroups
   ) {
     this.apiWrapper = apiWrapper
     this.membersKeyPairs = membersKeyPairs
     this.lead = lead
-    this.sudo = sudo
+    this.treasury = treasury
     this.module = module
   }
 
@@ -714,7 +661,7 @@ export class TerminateApplicationsFixture implements Fixture {
     // Fee estimation and transfer
     const terminateApplicationFee: BN = this.apiWrapper.estimateTerminateApplicationFee(this.module)
     await this.apiWrapper.transferBalance(
-      this.sudo,
+      this.treasury,
       this.lead.address,
       terminateApplicationFee.muln(this.membersKeyPairs.length)
     )
@@ -738,27 +685,27 @@ export class DecreaseStakeFixture implements Fixture {
   private apiWrapper: ApiWrapper
   private membersKeyPairs: KeyringPair[]
   private lead: KeyringPair
-  private sudo: KeyringPair
+  private treasury: KeyringPair
   private module: WorkingGroups
 
   constructor(
     apiWrapper: ApiWrapper,
     membersKeyPairs: KeyringPair[],
     lead: KeyringPair,
-    sudo: KeyringPair,
+    treasury: KeyringPair,
     module: WorkingGroups
   ) {
     this.apiWrapper = apiWrapper
     this.membersKeyPairs = membersKeyPairs
     this.lead = lead
-    this.sudo = sudo
+    this.treasury = treasury
     this.module = module
   }
 
   public async runner(expectFailure: boolean): Promise<void> {
     // Fee estimation and transfer
     const decreaseStakeFee: BN = this.apiWrapper.estimateDecreaseStakeFee(this.module)
-    await this.apiWrapper.transferBalance(this.sudo, this.lead.address, decreaseStakeFee)
+    await this.apiWrapper.transferBalance(this.treasury, this.lead.address, decreaseStakeFee)
     const workerStakeDecrement: BN = new BN(1)
     const workerId: WorkerId = await this.apiWrapper.getWorkerIdByRoleAccount(
       this.membersKeyPairs[0].address,
@@ -786,27 +733,27 @@ export class SlashFixture implements Fixture {
   private apiWrapper: ApiWrapper
   private membersKeyPairs: KeyringPair[]
   private lead: KeyringPair
-  private sudo: KeyringPair
+  private treasury: KeyringPair
   private module: WorkingGroups
 
   constructor(
     apiWrapper: ApiWrapper,
     membersKeyPairs: KeyringPair[],
     lead: KeyringPair,
-    sudo: KeyringPair,
+    treasury: KeyringPair,
     module: WorkingGroups
   ) {
     this.apiWrapper = apiWrapper
     this.membersKeyPairs = membersKeyPairs
     this.lead = lead
-    this.sudo = sudo
+    this.treasury = treasury
     this.module = module
   }
 
   public async runner(expectFailure: boolean): Promise<void> {
     // Fee estimation and transfer
     const slashStakeFee: BN = this.apiWrapper.estimateSlashStakeFee(this.module)
-    await this.apiWrapper.transferBalance(this.sudo, this.lead.address, slashStakeFee)
+    await this.apiWrapper.transferBalance(this.treasury, this.lead.address, slashStakeFee)
     const slashAmount: BN = new BN(1)
     const workerId: WorkerId = await this.apiWrapper.getWorkerIdByRoleAccount(
       this.membersKeyPairs[0].address,
@@ -827,70 +774,65 @@ export class TerminateRoleFixture implements Fixture {
   private apiWrapper: ApiWrapper
   private membersKeyPairs: KeyringPair[]
   private lead: KeyringPair
-  private sudo: KeyringPair
+  private treasury: KeyringPair
   private module: WorkingGroups
 
   constructor(
     apiWrapper: ApiWrapper,
     membersKeyPairs: KeyringPair[],
     lead: KeyringPair,
-    sudo: KeyringPair,
+    treasury: KeyringPair,
     module: WorkingGroups
   ) {
     this.apiWrapper = apiWrapper
     this.membersKeyPairs = membersKeyPairs
     this.lead = lead
-    this.sudo = sudo
+    this.treasury = treasury
     this.module = module
   }
 
   public async runner(expectFailure: boolean): Promise<void> {
     // Fee estimation and transfer
     const terminateRoleFee: BN = this.apiWrapper.estimateTerminateRoleFee(this.module)
-    await this.apiWrapper.transferBalance(this.sudo, this.lead.address, terminateRoleFee)
+    await this.apiWrapper.transferBalance(this.treasury, this.lead.address, terminateRoleFee)
     const workerId: WorkerId = await this.apiWrapper.getWorkerIdByRoleAccount(
       this.membersKeyPairs[0].address,
       this.module
     )
 
-    // Slash worker
+    // Terminate worker role
     await this.apiWrapper.terminateRole(this.lead, workerId, uuid().substring(0, 8), this.module, expectFailure)
 
     // Assertions
-    this.apiWrapper.getWorkerIdByRoleAccount(this.membersKeyPairs[0].address, this.module)
-    const newWorkerId: WorkerId = await this.apiWrapper.getWorkerIdByRoleAccount(
-      this.membersKeyPairs[0].address,
-      this.module
-    )
-    assert(newWorkerId === undefined, `Worker with account ${this.membersKeyPairs[0].address} is not terminated`)
+    const isWorker: boolean = await this.apiWrapper.isWorker(this.membersKeyPairs[0].address, this.module)
+    assert(!isWorker, `Worker with account ${this.membersKeyPairs[0].address} is not terminated`)
   }
 }
 
 export class LeaveRoleFixture implements Fixture {
   private apiWrapper: ApiWrapper
   private membersKeyPairs: KeyringPair[]
-  private sudo: KeyringPair
+  private treasury: KeyringPair
   private module: WorkingGroups
 
-  constructor(apiWrapper: ApiWrapper, membersKeyPairs: KeyringPair[], sudo: KeyringPair, module: WorkingGroups) {
+  constructor(apiWrapper: ApiWrapper, membersKeyPairs: KeyringPair[], treasury: KeyringPair, module: WorkingGroups) {
     this.apiWrapper = apiWrapper
     this.membersKeyPairs = membersKeyPairs
-    this.sudo = sudo
+    this.treasury = treasury
     this.module = module
   }
 
   public async runner(expectFailure: boolean): Promise<void> {
     // Fee estimation and transfer
     const leaveRoleFee: BN = this.apiWrapper.estimateLeaveRoleFee(this.module)
-    await this.apiWrapper.transferBalanceToAccounts(this.sudo, this.membersKeyPairs, leaveRoleFee)
+    await this.apiWrapper.transferBalanceToAccounts(this.treasury, this.membersKeyPairs, leaveRoleFee)
 
     await this.apiWrapper.batchLeaveRole(this.membersKeyPairs, uuid().substring(0, 8), expectFailure, this.module)
 
     // Assertions
     this.membersKeyPairs.forEach(async (keyPair) => {
-      this.apiWrapper.getWorkerIdByRoleAccount(keyPair.address, this.module)
-      const newWorkerId: WorkerId = await this.apiWrapper.getWorkerIdByRoleAccount(keyPair.address, this.module)
-      assert(newWorkerId === undefined, `Worker with account ${keyPair.address} is not terminated`)
+      const isWorker: boolean = await this.apiWrapper.isWorker(this.membersKeyPairs[0].address, this.module)
+      assert(!isWorker, `Worker with account ${keyPair.address} is not terminated`)
     })
   }
 }
@@ -932,6 +874,7 @@ export class AwaitPayoutFixture implements Fixture {
     )
 
     const secondPayoutWaitingPeriod: BN = payoutInterval.addn(1)
+    console.log('waiting period ' + secondPayoutWaitingPeriod)
     await Utils.wait(this.apiWrapper.getBlockDuration().mul(secondPayoutWaitingPeriod).toNumber())
 
     const balanceAfterSecondPayout: BN = await this.apiWrapper.getBalance(this.membersKeyPairs[0].address)
@@ -956,7 +899,7 @@ export class ExpectLeadOpeningAddedFixture implements Fixture {
     this.apiWrapper = apiWrapper
   }
 
-  public getResult(): OpeningId | undefined {
+  public getCreatedOpeningId(): OpeningId | undefined {
     return this.result
   }
 
@@ -988,7 +931,7 @@ export class ExpectLeaderSetFixture implements Fixture {
     this.module = module
   }
 
-  public getResult(): WorkerId | undefined {
+  public getLeaderWorkerId(): WorkerId | undefined {
     return this.result
   }
 
@@ -1026,7 +969,7 @@ export class ExpectBeganApplicationReviewFixture implements Fixture {
     this.apiWrapper = apiWrapper
   }
 
-  public getResult(): ApplicationId | undefined {
+  public getApplicationId(): ApplicationId | undefined {
     return this.result
   }
 
@@ -1048,7 +991,6 @@ export class ExpectLeaderRoleTerminatedFixture implements Fixture {
   private apiWrapper: ApiWrapper
   private module: WorkingGroups
 
-  private result: BN | undefined
   private events: Event[] = []
 
   constructor(apiWrapper: ApiWrapper, module: WorkingGroups) {
@@ -1056,10 +998,6 @@ export class ExpectLeaderRoleTerminatedFixture implements Fixture {
     this.module = module
   }
 
-  public getResult(): BN | undefined {
-    return this.result
-  }
-
   public getEvents(): Event[] {
     return this.events
   }
@@ -1080,7 +1018,6 @@ export class ExpectLeaderRewardAmountUpdatedFixture implements Fixture {
   private expectedReward: BN
   private module: WorkingGroups
 
-  private result: BN | undefined
   private events: Event[] = []
 
   constructor(apiWrapper: ApiWrapper, expectedReward: BN, module: WorkingGroups) {
@@ -1089,10 +1026,6 @@ export class ExpectLeaderRewardAmountUpdatedFixture implements Fixture {
     this.module = module
   }
 
-  public getResult(): BN | undefined {
-    return this.result
-  }
-
   public getEvents(): Event[] {
     return this.events
   }
@@ -1101,9 +1034,9 @@ export class ExpectLeaderRewardAmountUpdatedFixture implements Fixture {
     const event: Event = await this.apiWrapper.expectEvent('WorkerRewardAmountUpdated')
     this.events.push(event)
     const leadWorkerId: WorkerId = (await this.apiWrapper.getLeadWorkerId(this.module))!
-    const receivedReward: BN = (await this.apiWrapper.getRewardRelationship(leadWorkerId)).getField<Balance>(
-      'amount_per_payout'
-    )
+    const leadWorker: Worker = await this.apiWrapper.getWorkerById(leadWorkerId, this.module)
+    const receivedReward: BN = (await this.apiWrapper.getRewardRelationship(leadWorker.reward_relationship.unwrap()))
+      .amount_per_payout
     assert(
       receivedReward.eq(this.expectedReward),
       `Unexpected reward amount for worker with id ${leadWorkerId}: ${receivedReward}, expected ${this.expectedReward}`
@@ -1119,7 +1052,6 @@ export class ExpectLeaderStakeDecreasedFixture implements Fixture {
   private expectedStake: BN
   private module: WorkingGroups
 
-  private result: BN | undefined
   private events: Event[] = []
 
   constructor(apiWrapper: ApiWrapper, expectedStake: BN, module: WorkingGroups) {
@@ -1128,10 +1060,6 @@ export class ExpectLeaderStakeDecreasedFixture implements Fixture {
     this.module = module
   }
 
-  public getResult(): BN | undefined {
-    return this.result
-  }
-
   public getEvents(): Event[] {
     return this.events
   }
@@ -1156,7 +1084,6 @@ export class ExpectLeaderSlashedFixture implements Fixture {
   private expectedStake: BN
   private module: WorkingGroups
 
-  private result: BN | undefined
   private events: Event[] = []
 
   constructor(apiWrapper: ApiWrapper, expectedStake: BN, module: WorkingGroups) {
@@ -1165,10 +1092,6 @@ export class ExpectLeaderSlashedFixture implements Fixture {
     this.module = module
   }
 
-  public getResult(): BN | undefined {
-    return this.result
-  }
-
   public getEvents(): Event[] {
     return this.events
   }

+ 62 - 0
tests/network-tests/src/iznik/tests/leaderSetup.ts

@@ -0,0 +1,62 @@
+import { initConfig } from '../utils/config'
+import { closeApi } from '../utils/closeApi'
+import { ApiWrapper, WorkingGroups } from '../utils/apiWrapper'
+import { WsProvider, Keyring } from '@polkadot/api'
+import { KeyringPair } from '@polkadot/keyring/types'
+import { setTestTimeout } from '../utils/setTestTimeout'
+import BN from 'bn.js'
+import tap from 'tap'
+import { Utils } from '../utils/utils'
+import { PaidTermId } from '@alexandria/types/members'
+import { DbService } from '../services/dbService'
+import { LeaderHiringHappyCaseFixture } from './fixtures/leaderHiringHappyCase'
+
+tap.mocha.describe('Worker application happy case scenario', async () => {
+  initConfig()
+  const nodeUrl: string = process.env.NODE_URL!
+  const sudoUri: string = process.env.SUDO_ACCOUNT_URI!
+  const keyring = new Keyring({ type: 'sr25519' })
+  const db: DbService = DbService.getInstance()
+  const provider = new WsProvider(nodeUrl)
+  const apiWrapper: ApiWrapper = await ApiWrapper.create(provider)
+  if (db.hasLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))) {
+    return
+  }
+
+  const sudo: KeyringPair = keyring.addFromUri(sudoUri)
+  const N: number = +process.env.WORKING_GROUP_N!
+  const nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  const leadKeyPair: KeyringPair[] = Utils.createKeyPairs(keyring, 1)
+
+  const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!))
+  const applicationStake: BN = new BN(process.env.WORKING_GROUP_APPLICATION_STAKE!)
+  const roleStake: BN = new BN(process.env.WORKING_GROUP_ROLE_STAKE!)
+  const firstRewardInterval: BN = new BN(process.env.LONG_REWARD_INTERVAL!)
+  const rewardInterval: BN = new BN(process.env.LONG_REWARD_INTERVAL!)
+  const payoutAmount: BN = new BN(process.env.PAYOUT_AMOUNT!)
+  const durationInBlocks = 48
+  const openingActivationDelay: BN = new BN(0)
+
+  setTestTimeout(apiWrapper, durationInBlocks)
+
+  const leaderHiringHappyCaseFixture: LeaderHiringHappyCaseFixture = new LeaderHiringHappyCaseFixture(
+    apiWrapper,
+    sudo,
+    nKeyPairs,
+    leadKeyPair,
+    paidTerms,
+    applicationStake,
+    roleStake,
+    openingActivationDelay,
+    rewardInterval,
+    firstRewardInterval,
+    payoutAmount,
+    WorkingGroups.StorageWorkingGroup
+  )
+  await leaderHiringHappyCaseFixture.runner(false)
+
+  db.setMembers(nKeyPairs)
+  db.setLeader(leadKeyPair[0], apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))
+
+  closeApi(apiWrapper)
+})

+ 3 - 4
tests/network-tests/src/iznik/tests/membership/membershipCreationTest.ts

@@ -3,16 +3,15 @@ import { Keyring, WsProvider } from '@polkadot/api'
 import { initConfig } from '../../utils/config'
 import { setTestTimeout } from '../../utils/setTestTimeout'
 import tap from 'tap'
-import { registerJoystreamTypes } from '@alexandria/types'
 import { ApiWrapper } from '../../utils/apiWrapper'
 import { closeApi } from '../../utils/closeApi'
 import { BuyMembershipHappyCaseFixture, BuyMembershipWithInsufficienFundsFixture } from '../fixtures/membershipModule'
 import { Utils } from '../../utils/utils'
-import { PaidTermId } from '@nicaea/types/members'
+import { PaidTermId } from '@alexandria/types/members'
+import BN from 'bn.js'
 
 tap.mocha.describe('Membership creation scenario', async () => {
   initConfig()
-  registerJoystreamTypes()
 
   const nodeUrl: string = process.env.NODE_URL!
   const sudoUri: string = process.env.SUDO_ACCOUNT_URI!
@@ -24,7 +23,7 @@ tap.mocha.describe('Membership creation scenario', async () => {
   const N: number = +process.env.MEMBERSHIP_CREATION_N!
   const nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
   const aKeyPair: KeyringPair[] = Utils.createKeyPairs(keyring, 1)
-  const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!)
+  const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!))
 
   const durationInBlocks = 7
 

+ 26 - 36
tests/network-tests/src/iznik/tests/proposals/contentWorkingGroupMintCapacityProposalTest.ts

@@ -4,18 +4,16 @@ import { Keyring, WsProvider } from '@polkadot/api'
 import BN from 'bn.js'
 import { setTestTimeout } from '../../utils/setTestTimeout'
 import tap from 'tap'
-import { registerJoystreamTypes } from '@alexandria/types'
 import { closeApi } from '../../utils/closeApi'
 import { ApiWrapper } from '../../utils/apiWrapper'
 import { ContentWorkingGroupMintCapacityProposalFixture } from '../fixtures/proposalsModule'
-import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule'
-import { ElectCouncilFixture } from '../fixtures/councilElectionModule'
 import { Utils } from '../../utils/utils'
-import { PaidTermId } from '@nicaea/types/members'
+import { PaidTermId } from '@alexandria/types/members'
+import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase'
+import { DbService } from '../../services/dbService'
 
 tap.mocha.describe('Validator count proposal scenario', async () => {
   initConfig()
-  registerJoystreamTypes()
 
   const nodeUrl: string = process.env.NODE_URL!
   const sudoUri: string = process.env.SUDO_ACCOUNT_URI!
@@ -23,12 +21,13 @@ tap.mocha.describe('Validator count proposal scenario', async () => {
   const provider = new WsProvider(nodeUrl)
   const apiWrapper: ApiWrapper = await ApiWrapper.create(provider)
   const sudo: KeyringPair = keyring.addFromUri(sudoUri)
+  const db: DbService = DbService.getInstance()
 
   const N: number = +process.env.MEMBERSHIP_CREATION_N!
-  const m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
-  const m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
 
-  const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!)
+  const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!))
   const K: number = +process.env.COUNCIL_ELECTION_K!
   const greaterStake: BN = new BN(+process.env.COUNCIL_STAKE_GREATER_AMOUNT!)
   const lesserStake: BN = new BN(+process.env.COUNCIL_STAKE_LESSER_AMOUNT!)
@@ -38,32 +37,22 @@ tap.mocha.describe('Validator count proposal scenario', async () => {
 
   setTestTimeout(apiWrapper, durationInBlocks)
 
-  const firstMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    m1KeyPairs,
-    paidTerms
-  )
-  tap.test('Creating first set of members', async () => firstMemberSetFixture.runner(false))
-
-  const secondMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    m2KeyPairs,
-    paidTerms
-  )
-  tap.test('Creating second set of members', async () => secondMemberSetFixture.runner(false))
-
-  const electCouncilFixture: ElectCouncilFixture = new ElectCouncilFixture(
-    apiWrapper,
-    m1KeyPairs,
-    m2KeyPairs,
-    K,
-    sudo,
-    greaterStake,
-    lesserStake
-  )
-  tap.test('Elect council', async () => electCouncilFixture.runner(false))
+  if (db.hasCouncil()) {
+    m1KeyPairs = db.getMembers()
+    m2KeyPairs = db.getCouncil()
+  } else {
+    const councilElectionHappyCaseFixture = new CouncilElectionHappyCaseFixture(
+      apiWrapper,
+      sudo,
+      m1KeyPairs,
+      m2KeyPairs,
+      paidTerms,
+      K,
+      greaterStake,
+      lesserStake
+    )
+    await councilElectionHappyCaseFixture.runner(false)
+  }
 
   const contentWorkingGroupMintCapacityProposalFixture: ContentWorkingGroupMintCapacityProposalFixture = new ContentWorkingGroupMintCapacityProposalFixture(
     apiWrapper,
@@ -72,8 +61,9 @@ tap.mocha.describe('Validator count proposal scenario', async () => {
     sudo,
     mintingCapacityIncrement
   )
-  tap.test('Content working group mint capacity test', async () =>
-    contentWorkingGroupMintCapacityProposalFixture.runner(false)
+  tap.test(
+    'Content working group mint capacity test',
+    async () => await contentWorkingGroupMintCapacityProposalFixture.runner(false)
   )
 
   closeApi(apiWrapper)

+ 24 - 35
tests/network-tests/src/iznik/tests/proposals/electionParametersProposalTest.ts

@@ -4,18 +4,16 @@ import { Keyring, WsProvider } from '@polkadot/api'
 import BN from 'bn.js'
 import { setTestTimeout } from '../../utils/setTestTimeout'
 import tap from 'tap'
-import { registerJoystreamTypes } from '@alexandria/types'
 import { closeApi } from '../../utils/closeApi'
 import { ApiWrapper } from '../../utils/apiWrapper'
-import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule'
-import { ElectCouncilFixture } from '../fixtures/councilElectionModule'
 import { Utils } from '../../utils/utils'
 import { ElectionParametersProposalFixture } from '../fixtures/proposalsModule'
-import { PaidTermId } from '@nicaea/types/members'
+import { PaidTermId } from '@alexandria/types/members'
+import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase'
+import { DbService } from '../../services/dbService'
 
 tap.mocha.describe('Election parameters proposal scenario', async () => {
   initConfig()
-  registerJoystreamTypes()
 
   const nodeUrl: string = process.env.NODE_URL!
   const sudoUri: string = process.env.SUDO_ACCOUNT_URI!
@@ -23,12 +21,13 @@ tap.mocha.describe('Election parameters proposal scenario', async () => {
   const provider = new WsProvider(nodeUrl)
   const apiWrapper: ApiWrapper = await ApiWrapper.create(provider)
   const sudo: KeyringPair = keyring.addFromUri(sudoUri)
+  const db: DbService = DbService.getInstance()
 
   const N: number = +process.env.MEMBERSHIP_CREATION_N!
-  const m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
-  const m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
 
-  const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!)
+  const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!))
   const K: number = +process.env.COUNCIL_ELECTION_K!
   const greaterStake: BN = new BN(+process.env.COUNCIL_STAKE_GREATER_AMOUNT!)
   const lesserStake: BN = new BN(+process.env.COUNCIL_STAKE_LESSER_AMOUNT!)
@@ -37,32 +36,22 @@ tap.mocha.describe('Election parameters proposal scenario', async () => {
 
   setTestTimeout(apiWrapper, durationInBlocks)
 
-  const firstMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    m1KeyPairs,
-    paidTerms
-  )
-  tap.test('Creating first set of members', async () => firstMemberSetFixture.runner(false))
-
-  const secondMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    m2KeyPairs,
-    paidTerms
-  )
-  tap.test('Creating second set of members', async () => secondMemberSetFixture.runner(false))
-
-  const electCouncilFixture: ElectCouncilFixture = new ElectCouncilFixture(
-    apiWrapper,
-    m1KeyPairs,
-    m2KeyPairs,
-    K,
-    sudo,
-    greaterStake,
-    lesserStake
-  )
-  tap.test('Elect council', async () => electCouncilFixture.runner(false))
+  if (db.hasCouncil()) {
+    m1KeyPairs = db.getMembers()
+    m2KeyPairs = db.getCouncil()
+  } else {
+    const councilElectionHappyCaseFixture = new CouncilElectionHappyCaseFixture(
+      apiWrapper,
+      sudo,
+      m1KeyPairs,
+      m2KeyPairs,
+      paidTerms,
+      K,
+      greaterStake,
+      lesserStake
+    )
+    await councilElectionHappyCaseFixture.runner(false)
+  }
 
   const electionParametersProposalFixture: ElectionParametersProposalFixture = new ElectionParametersProposalFixture(
     apiWrapper,
@@ -70,7 +59,7 @@ tap.mocha.describe('Election parameters proposal scenario', async () => {
     m2KeyPairs,
     sudo
   )
-  tap.test('Election parameters proposal test', async () => electionParametersProposalFixture.runner(false))
+  tap.test('Election parameters proposal test', async () => await electionParametersProposalFixture.runner(false))
 
   closeApi(apiWrapper)
 })

+ 42 - 51
tests/network-tests/src/iznik/tests/proposals/manageLeaderRoleTest.ts

@@ -4,11 +4,9 @@ import { Keyring, WsProvider } from '@polkadot/api'
 import BN from 'bn.js'
 import { setTestTimeout } from '../../utils/setTestTimeout'
 import tap from 'tap'
-import { registerJoystreamTypes } from '@alexandria/types'
 import { closeApi } from '../../utils/closeApi'
 import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper'
 import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule'
-import { ElectCouncilFixture } from '../fixtures/councilElectionModule'
 import {
   BeginWorkingGroupLeaderApplicationReviewFixture,
   CreateWorkingGroupLeaderOpeningFixture,
@@ -30,27 +28,30 @@ import {
   ExpectLeadOpeningAddedFixture,
 } from '../fixtures/workingGroupModule'
 import { Utils } from '../../utils/utils'
-import { PaidTermId } from '@nicaea/types/members'
-import { OpeningId } from '@nicaea/types/hiring'
-import { ProposalId } from '@nicaea/types/proposals'
+import { PaidTermId } from '@alexandria/types/members'
+import { OpeningId } from '@alexandria/types/hiring'
+import { ProposalId } from '@alexandria/types/proposals'
+import { DbService } from '../../services/dbService'
+import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase'
 
 tap.mocha.describe('Set lead proposal scenario', async () => {
   initConfig()
-  registerJoystreamTypes()
 
   const nodeUrl: string = process.env.NODE_URL!
   const sudoUri: string = process.env.SUDO_ACCOUNT_URI!
   const keyring = new Keyring({ type: 'sr25519' })
+  const db: DbService = DbService.getInstance()
+
   const provider = new WsProvider(nodeUrl)
   const apiWrapper: ApiWrapper = await ApiWrapper.create(provider)
   const sudo: KeyringPair = keyring.addFromUri(sudoUri)
 
   const N: number = +process.env.MEMBERSHIP_CREATION_N!
-  const m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
-  const m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
   const leadKeyPair: KeyringPair[] = Utils.createKeyPairs(keyring, 1)
 
-  const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!)
+  const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!))
   const K: number = +process.env.COUNCIL_ELECTION_K!
   const greaterStake: BN = new BN(+process.env.COUNCIL_STAKE_GREATER_AMOUNT!)
   const lesserStake: BN = new BN(+process.env.COUNCIL_STAKE_LESSER_AMOUNT!)
@@ -66,21 +67,22 @@ tap.mocha.describe('Set lead proposal scenario', async () => {
 
   setTestTimeout(apiWrapper, durationInBlocks)
 
-  const firstMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    m1KeyPairs,
-    paidTerms
-  )
-  tap.test('Creating first set of members', async () => firstMemberSetFixture.runner(false))
-
-  const secondMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    m2KeyPairs,
-    paidTerms
-  )
-  tap.test('Creating second set of members', async () => secondMemberSetFixture.runner(false))
+  if (db.hasCouncil()) {
+    m1KeyPairs = db.getMembers()
+    m2KeyPairs = db.getCouncil()
+  } else {
+    const councilElectionHappyCaseFixture = new CouncilElectionHappyCaseFixture(
+      apiWrapper,
+      sudo,
+      m1KeyPairs,
+      m2KeyPairs,
+      paidTerms,
+      K,
+      greaterStake,
+      lesserStake
+    )
+    await councilElectionHappyCaseFixture.runner(false)
+  }
 
   const leaderMembershipFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
     apiWrapper,
@@ -88,18 +90,7 @@ tap.mocha.describe('Set lead proposal scenario', async () => {
     leadKeyPair,
     paidTerms
   )
-  tap.test('Buy membership for lead', async () => leaderMembershipFixture.runner(false))
-
-  const electCouncilFixture: ElectCouncilFixture = new ElectCouncilFixture(
-    apiWrapper,
-    m1KeyPairs,
-    m2KeyPairs,
-    K,
-    sudo,
-    greaterStake,
-    lesserStake
-  )
-  tap.test('Elect council', async () => electCouncilFixture.runner(false))
+  tap.test('Buy membership for lead', async () => await leaderMembershipFixture.runner(false))
 
   const createWorkingGroupLeaderOpeningFixture: CreateWorkingGroupLeaderOpeningFixture = new CreateWorkingGroupLeaderOpeningFixture(
     apiWrapper,
@@ -109,7 +100,7 @@ tap.mocha.describe('Set lead proposal scenario', async () => {
     roleStake,
     'Storage'
   )
-  tap.test('Propose create leader opening', async () => createWorkingGroupLeaderOpeningFixture.runner(false))
+  tap.test('Propose create leader opening', async () => await createWorkingGroupLeaderOpeningFixture.runner(false))
 
   let voteForCreateOpeningProposalFixture: VoteForProposalFixture
   const expectLeadOpeningAddedFixture: ExpectLeadOpeningAddedFixture = new ExpectLeadOpeningAddedFixture(apiWrapper)
@@ -118,7 +109,7 @@ tap.mocha.describe('Set lead proposal scenario', async () => {
       apiWrapper,
       m2KeyPairs,
       sudo,
-      createWorkingGroupLeaderOpeningFixture.getResult() as OpeningId
+      createWorkingGroupLeaderOpeningFixture.getCreatedProposalId() as OpeningId
     )
     voteForCreateOpeningProposalFixture.runner(false)
     await expectLeadOpeningAddedFixture.runner(false)
@@ -132,7 +123,7 @@ tap.mocha.describe('Set lead proposal scenario', async () => {
       sudo,
       applicationStake,
       roleStake,
-      expectLeadOpeningAddedFixture.getResult() as OpeningId,
+      expectLeadOpeningAddedFixture.getCreatedOpeningId() as OpeningId,
       WorkingGroups.StorageWorkingGroup
     )
     await applyForLeaderOpeningFixture.runner(false)
@@ -144,7 +135,7 @@ tap.mocha.describe('Set lead proposal scenario', async () => {
       apiWrapper,
       m1KeyPairs,
       sudo,
-      expectLeadOpeningAddedFixture.getResult() as OpeningId,
+      expectLeadOpeningAddedFixture.getCreatedOpeningId() as OpeningId,
       'Storage'
     )
     await beginWorkingGroupLeaderApplicationReviewFixture.runner(false)
@@ -159,7 +150,7 @@ tap.mocha.describe('Set lead proposal scenario', async () => {
       apiWrapper,
       m2KeyPairs,
       sudo,
-      beginWorkingGroupLeaderApplicationReviewFixture.getResult() as ProposalId
+      beginWorkingGroupLeaderApplicationReviewFixture.getCreatedProposalId() as ProposalId
     )
     voteForBeginReviewProposal.runner(false)
     await expectBeganApplicationReviewFixture.runner(false)
@@ -175,7 +166,7 @@ tap.mocha.describe('Set lead proposal scenario', async () => {
       firstRewardInterval,
       rewardInterval,
       payoutAmount,
-      expectLeadOpeningAddedFixture.getResult() as OpeningId,
+      expectLeadOpeningAddedFixture.getCreatedOpeningId() as OpeningId,
       WorkingGroups.StorageWorkingGroup
     )
     await fillLeaderOpeningProposalFixture.runner(false)
@@ -192,7 +183,7 @@ tap.mocha.describe('Set lead proposal scenario', async () => {
       apiWrapper,
       m2KeyPairs,
       sudo,
-      fillLeaderOpeningProposalFixture.getResult() as ProposalId
+      fillLeaderOpeningProposalFixture.getCreatedProposalId() as ProposalId
     )
     voteForFillLeaderProposalFixture.runner(false)
     await expectLeaderSetFixture.runner(false)
@@ -218,7 +209,7 @@ tap.mocha.describe('Set lead proposal scenario', async () => {
       apiWrapper,
       m2KeyPairs,
       sudo,
-      setLeaderRewardProposalFixture.getResult() as ProposalId
+      setLeaderRewardProposalFixture.getCreatedProposalId() as ProposalId
     )
     voteForeLeaderRewardFixture.runner(false)
     await expectLeaderRewardAmountUpdatedFixture.runner(false)
@@ -238,13 +229,13 @@ tap.mocha.describe('Set lead proposal scenario', async () => {
   let expectLeaderStakeDecreasedFixture: ExpectLeaderStakeDecreasedFixture
   tap.test('Approve decreased leader stake', async () => {
     newStake = applicationStake.sub(stakeDecrement)
-    voteForFillLeaderProposalFixture = new VoteForProposalFixture(
+    voteForDecreaseStakeProposal = new VoteForProposalFixture(
       apiWrapper,
       m2KeyPairs,
       sudo,
-      decreaseLeaderStakeProposalFixture.getResult() as ProposalId
+      decreaseLeaderStakeProposalFixture.getCreatedProposalId() as ProposalId
     )
-    voteForFillLeaderProposalFixture.runner(false)
+    voteForDecreaseStakeProposal.runner(false)
     expectLeaderStakeDecreasedFixture = new ExpectLeaderStakeDecreasedFixture(
       apiWrapper,
       newStake,
@@ -260,7 +251,7 @@ tap.mocha.describe('Set lead proposal scenario', async () => {
     slashAmount,
     WorkingGroups.StorageWorkingGroup
   )
-  tap.test('Propose leader slash', async () => slashLeaderProposalFixture.runner(false))
+  tap.test('Propose leader slash', async () => await slashLeaderProposalFixture.runner(false))
 
   let voteForSlashProposalFixture: VoteForProposalFixture
   let expectLeaderSlashedFixture: ExpectLeaderSlashedFixture
@@ -270,7 +261,7 @@ tap.mocha.describe('Set lead proposal scenario', async () => {
       apiWrapper,
       m2KeyPairs,
       sudo,
-      slashLeaderProposalFixture.getResult() as ProposalId
+      slashLeaderProposalFixture.getCreatedProposalId() as ProposalId
     )
     voteForSlashProposalFixture.runner(false)
     expectLeaderSlashedFixture = new ExpectLeaderSlashedFixture(apiWrapper, newStake, WorkingGroups.StorageWorkingGroup)
@@ -285,7 +276,7 @@ tap.mocha.describe('Set lead proposal scenario', async () => {
     false,
     WorkingGroups.StorageWorkingGroup
   )
-  tap.test('Propose terminate leader role', async () => terminateLeaderRoleProposalFixture.runner(false))
+  tap.test('Propose terminate leader role', async () => await terminateLeaderRoleProposalFixture.runner(false))
 
   let voteForLeaderRoleTerminationFixture: VoteForProposalFixture
   const expectLeaderRoleTerminatedFixture: ExpectLeaderRoleTerminatedFixture = new ExpectLeaderRoleTerminatedFixture(
@@ -297,7 +288,7 @@ tap.mocha.describe('Set lead proposal scenario', async () => {
       apiWrapper,
       m2KeyPairs,
       sudo,
-      terminateLeaderRoleProposalFixture.getResult() as ProposalId
+      terminateLeaderRoleProposalFixture.getCreatedProposalId() as ProposalId
     )
     voteForLeaderRoleTerminationFixture.runner(false)
     await expectLeaderRoleTerminatedFixture.runner(false)

+ 24 - 35
tests/network-tests/src/iznik/tests/proposals/setLeadProposalTest.ts

@@ -4,18 +4,16 @@ import { Keyring, WsProvider } from '@polkadot/api'
 import BN from 'bn.js'
 import { setTestTimeout } from '../../utils/setTestTimeout'
 import tap from 'tap'
-import { registerJoystreamTypes } from '@alexandria/types'
 import { closeApi } from '../../utils/closeApi'
 import { ApiWrapper } from '../../utils/apiWrapper'
 import { Utils } from '../../utils/utils'
-import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule'
-import { ElectCouncilFixture } from '../fixtures/councilElectionModule'
 import { SetLeadProposalFixture } from '../fixtures/proposalsModule'
-import { PaidTermId } from '@nicaea/types/members'
+import { PaidTermId } from '@alexandria/types/members'
+import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase'
+import { DbService } from '../../services/dbService'
 
 tap.mocha.describe('Set lead proposal scenario', async () => {
   initConfig()
-  registerJoystreamTypes()
 
   const nodeUrl: string = process.env.NODE_URL!
   const sudoUri: string = process.env.SUDO_ACCOUNT_URI!
@@ -23,12 +21,13 @@ tap.mocha.describe('Set lead proposal scenario', async () => {
   const provider = new WsProvider(nodeUrl)
   const apiWrapper: ApiWrapper = await ApiWrapper.create(provider)
   const sudo: KeyringPair = keyring.addFromUri(sudoUri)
+  const db: DbService = DbService.getInstance()
 
   const N: number = +process.env.MEMBERSHIP_CREATION_N!
-  const m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
-  const m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
 
-  const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!)
+  const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!))
   const K: number = +process.env.COUNCIL_ELECTION_K!
   const greaterStake: BN = new BN(+process.env.COUNCIL_STAKE_GREATER_AMOUNT!)
   const lesserStake: BN = new BN(+process.env.COUNCIL_STAKE_LESSER_AMOUNT!)
@@ -37,32 +36,22 @@ tap.mocha.describe('Set lead proposal scenario', async () => {
 
   setTestTimeout(apiWrapper, durationInBlocks)
 
-  const firstMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    m1KeyPairs,
-    paidTerms
-  )
-  tap.test('Creating first set of members', async () => firstMemberSetFixture.runner(false))
-
-  const secondMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    m2KeyPairs,
-    paidTerms
-  )
-  tap.test('Creating second set of members', async () => secondMemberSetFixture.runner(false))
-
-  const electCouncilFixture: ElectCouncilFixture = new ElectCouncilFixture(
-    apiWrapper,
-    m1KeyPairs,
-    m2KeyPairs,
-    K,
-    sudo,
-    greaterStake,
-    lesserStake
-  )
-  tap.test('Elect council', async () => electCouncilFixture.runner(false))
+  if (db.hasCouncil()) {
+    m1KeyPairs = db.getMembers()
+    m2KeyPairs = db.getCouncil()
+  } else {
+    const councilElectionHappyCaseFixture = new CouncilElectionHappyCaseFixture(
+      apiWrapper,
+      sudo,
+      m1KeyPairs,
+      m2KeyPairs,
+      paidTerms,
+      K,
+      greaterStake,
+      lesserStake
+    )
+    await councilElectionHappyCaseFixture.runner(false)
+  }
 
   const setLeadProposalFixture: SetLeadProposalFixture = new SetLeadProposalFixture(
     apiWrapper,
@@ -70,7 +59,7 @@ tap.mocha.describe('Set lead proposal scenario', async () => {
     m2KeyPairs,
     sudo
   )
-  tap.test('Set lead proposal test', async () => setLeadProposalFixture.runner(false))
+  tap.test('Set lead proposal test', async () => await setLeadProposalFixture.runner(false))
 
   closeApi(apiWrapper)
 })

+ 24 - 35
tests/network-tests/src/iznik/tests/proposals/spendingProposalTest.ts

@@ -4,18 +4,16 @@ import { Keyring, WsProvider } from '@polkadot/api'
 import BN from 'bn.js'
 import { setTestTimeout } from '../../utils/setTestTimeout'
 import tap from 'tap'
-import { registerJoystreamTypes } from '@alexandria/types'
 import { closeApi } from '../../utils/closeApi'
 import { ApiWrapper } from '../../utils/apiWrapper'
 import { Utils } from '../../utils/utils'
-import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule'
-import { ElectCouncilFixture } from '../fixtures/councilElectionModule'
 import { SpendingProposalFixture } from '../fixtures/proposalsModule'
-import { PaidTermId } from '@nicaea/types/members'
+import { PaidTermId } from '@alexandria/types/members'
+import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase'
+import { DbService } from '../../services/dbService'
 
 tap.mocha.describe('Spending proposal scenario', async () => {
   initConfig()
-  registerJoystreamTypes()
 
   const nodeUrl: string = process.env.NODE_URL!
   const sudoUri: string = process.env.SUDO_ACCOUNT_URI!
@@ -23,12 +21,13 @@ tap.mocha.describe('Spending proposal scenario', async () => {
   const provider = new WsProvider(nodeUrl)
   const apiWrapper: ApiWrapper = await ApiWrapper.create(provider)
   const sudo: KeyringPair = keyring.addFromUri(sudoUri)
+  const db: DbService = DbService.getInstance()
 
   const N: number = +process.env.MEMBERSHIP_CREATION_N!
-  const m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
-  const m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
 
-  const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!)
+  const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!))
   const K: number = +process.env.COUNCIL_ELECTION_K!
   const greaterStake: BN = new BN(+process.env.COUNCIL_STAKE_GREATER_AMOUNT!)
   const lesserStake: BN = new BN(+process.env.COUNCIL_STAKE_LESSER_AMOUNT!)
@@ -38,32 +37,22 @@ tap.mocha.describe('Spending proposal scenario', async () => {
 
   setTestTimeout(apiWrapper, durationInBlocks)
 
-  const firstMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    m1KeyPairs,
-    paidTerms
-  )
-  tap.test('Creating first set of members', async () => firstMemberSetFixture.runner(false))
-
-  const secondMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    m2KeyPairs,
-    paidTerms
-  )
-  tap.test('Creating second set of members', async () => secondMemberSetFixture.runner(false))
-
-  const electCouncilFixture: ElectCouncilFixture = new ElectCouncilFixture(
-    apiWrapper,
-    m1KeyPairs,
-    m2KeyPairs,
-    K,
-    sudo,
-    greaterStake,
-    lesserStake
-  )
-  tap.test('Elect council', async () => electCouncilFixture.runner(false))
+  if (db.hasCouncil()) {
+    m1KeyPairs = db.getMembers()
+    m2KeyPairs = db.getCouncil()
+  } else {
+    const councilElectionHappyCaseFixture = new CouncilElectionHappyCaseFixture(
+      apiWrapper,
+      sudo,
+      m1KeyPairs,
+      m2KeyPairs,
+      paidTerms,
+      K,
+      greaterStake,
+      lesserStake
+    )
+    await councilElectionHappyCaseFixture.runner(false)
+  }
 
   const spendingProposalFixture: SpendingProposalFixture = new SpendingProposalFixture(
     apiWrapper,
@@ -73,7 +62,7 @@ tap.mocha.describe('Spending proposal scenario', async () => {
     spendingBalance,
     mintCapacity
   )
-  tap.test('Spending proposal test', async () => spendingProposalFixture.runner(false))
+  tap.test('Spending proposal test', async () => await spendingProposalFixture.runner(false))
 
   closeApi(apiWrapper)
 })

+ 24 - 35
tests/network-tests/src/iznik/tests/proposals/textProposalTest.ts

@@ -4,18 +4,16 @@ import { Keyring, WsProvider } from '@polkadot/api'
 import BN from 'bn.js'
 import { setTestTimeout } from '../../utils/setTestTimeout'
 import tap from 'tap'
-import { registerJoystreamTypes } from '@alexandria/types'
 import { closeApi } from '../../utils/closeApi'
 import { ApiWrapper } from '../../utils/apiWrapper'
 import { Utils } from '../../utils/utils'
-import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule'
-import { ElectCouncilFixture } from '../fixtures/councilElectionModule'
 import { TextProposalFixture } from '../fixtures/proposalsModule'
-import { PaidTermId } from '@nicaea/types/members'
+import { PaidTermId } from '@alexandria/types/members'
+import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase'
+import { DbService } from '../../services/dbService'
 
 tap.mocha.describe('Text proposal scenario', async () => {
   initConfig()
-  registerJoystreamTypes()
 
   const nodeUrl: string = process.env.NODE_URL!
   const sudoUri: string = process.env.SUDO_ACCOUNT_URI!
@@ -23,12 +21,13 @@ tap.mocha.describe('Text proposal scenario', async () => {
   const provider = new WsProvider(nodeUrl)
   const apiWrapper: ApiWrapper = await ApiWrapper.create(provider)
   const sudo: KeyringPair = keyring.addFromUri(sudoUri)
+  const db: DbService = DbService.getInstance()
 
   const N: number = +process.env.MEMBERSHIP_CREATION_N!
-  const m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
-  const m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
 
-  const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!)
+  const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!))
   const K: number = +process.env.COUNCIL_ELECTION_K!
   const greaterStake: BN = new BN(+process.env.COUNCIL_STAKE_GREATER_AMOUNT!)
   const lesserStake: BN = new BN(+process.env.COUNCIL_STAKE_LESSER_AMOUNT!)
@@ -36,35 +35,25 @@ tap.mocha.describe('Text proposal scenario', async () => {
 
   setTestTimeout(apiWrapper, durationInBlocks)
 
-  const firstMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    m1KeyPairs,
-    paidTerms
-  )
-  tap.test('Creating first set of members', async () => firstMemberSetFixture.runner(false))
-
-  const secondMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    m2KeyPairs,
-    paidTerms
-  )
-  tap.test('Creating second set of members', async () => secondMemberSetFixture.runner(false))
-
-  const electCouncilFixture: ElectCouncilFixture = new ElectCouncilFixture(
-    apiWrapper,
-    m1KeyPairs,
-    m2KeyPairs,
-    K,
-    sudo,
-    greaterStake,
-    lesserStake
-  )
-  tap.test('Elect council', async () => electCouncilFixture.runner(false))
+  if (db.hasCouncil()) {
+    m1KeyPairs = db.getMembers()
+    m2KeyPairs = db.getCouncil()
+  } else {
+    const councilElectionHappyCaseFixture = new CouncilElectionHappyCaseFixture(
+      apiWrapper,
+      sudo,
+      m1KeyPairs,
+      m2KeyPairs,
+      paidTerms,
+      K,
+      greaterStake,
+      lesserStake
+    )
+    await councilElectionHappyCaseFixture.runner(false)
+  }
 
   const textProposalFixture: TextProposalFixture = new TextProposalFixture(apiWrapper, m1KeyPairs, m2KeyPairs, sudo)
-  tap.test('Text proposal test', async () => textProposalFixture.runner(false))
+  tap.test('Text proposal test', async () => await textProposalFixture.runner(false))
 
   closeApi(apiWrapper)
 })

+ 28 - 31
tests/network-tests/src/iznik/tests/proposals/updateRuntime.ts

@@ -4,18 +4,17 @@ import { Keyring, WsProvider } from '@polkadot/api'
 import BN from 'bn.js'
 import { setTestTimeout } from '../../utils/setTestTimeout'
 import tap from 'tap'
-import { registerJoystreamTypes } from '@alexandria/types'
 import { closeApi } from '../../utils/closeApi'
 import { ApiWrapper } from '../../utils/apiWrapper'
 import { Utils } from '../../utils/utils'
 import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule'
-import { ElectCouncilFixture } from '../fixtures/councilElectionModule'
 import { UpdateRuntimeFixture } from '../fixtures/proposalsModule'
-import { PaidTermId } from '@nicaea/types/members'
+import { PaidTermId } from '@alexandria/types/members'
+import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase'
+import { DbService } from '../../services/dbService'
 
 tap.mocha.describe('Update runtime scenario', async () => {
   initConfig()
-  registerJoystreamTypes()
 
   const nodeUrl: string = process.env.NODE_URL!
   const sudoUri: string = process.env.SUDO_ACCOUNT_URI!
@@ -23,48 +22,46 @@ tap.mocha.describe('Update runtime scenario', async () => {
   const provider = new WsProvider(nodeUrl)
   const apiWrapper: ApiWrapper = await ApiWrapper.create(provider)
   const sudo: KeyringPair = keyring.addFromUri(sudoUri)
+  const db: DbService = DbService.getInstance()
 
   const N: number = +process.env.MEMBERSHIP_CREATION_N!
-  const m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
-  const m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
 
-  const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!)
+  const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!))
   const K: number = +process.env.COUNCIL_ELECTION_K!
   const greaterStake: BN = new BN(+process.env.COUNCIL_STAKE_GREATER_AMOUNT!)
   const lesserStake: BN = new BN(+process.env.COUNCIL_STAKE_LESSER_AMOUNT!)
+  const runtimePath: string = process.env.RUNTIME_WASM_PATH!
   const durationInBlocks = 54
 
   setTestTimeout(apiWrapper, durationInBlocks)
 
-  const firstMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    m1KeyPairs,
-    paidTerms
-  )
-  tap.test('Creating first set of members', async () => firstMemberSetFixture.runner(false))
-
-  const secondMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    m2KeyPairs,
-    paidTerms
-  )
-  tap.test('Creating second set of members', async () => secondMemberSetFixture.runner(false))
+  if (db.hasCouncil()) {
+    m1KeyPairs = db.getMembers()
+    m2KeyPairs = db.getCouncil()
+  } else {
+    const councilElectionHappyCaseFixture = new CouncilElectionHappyCaseFixture(
+      apiWrapper,
+      sudo,
+      m1KeyPairs,
+      m2KeyPairs,
+      paidTerms,
+      K,
+      greaterStake,
+      lesserStake
+    )
+    await councilElectionHappyCaseFixture.runner(false)
+  }
 
-  const electCouncilFixture: ElectCouncilFixture = new ElectCouncilFixture(
+  const updateRuntimeFixture: UpdateRuntimeFixture = new UpdateRuntimeFixture(
     apiWrapper,
     m1KeyPairs,
     m2KeyPairs,
-    K,
     sudo,
-    greaterStake,
-    lesserStake
+    runtimePath
   )
-  tap.test('Elect council', async () => electCouncilFixture.runner(false))
-
-  const updateRuntimeFixture: UpdateRuntimeFixture = new UpdateRuntimeFixture(apiWrapper, m1KeyPairs, m2KeyPairs, sudo)
-  tap.test('Upgrade runtime', async () => updateRuntimeFixture.runner(false))
+  tap.test('Upgrade runtime', async () => await updateRuntimeFixture.runner(false))
 
   const thirdMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
     apiWrapper,
@@ -72,7 +69,7 @@ tap.mocha.describe('Update runtime scenario', async () => {
     Utils.createKeyPairs(keyring, N),
     paidTerms
   )
-  tap.test('Creating third set of members', async () => thirdMemberSetFixture.runner(false))
+  tap.test('Creating third set of members', async () => await thirdMemberSetFixture.runner(false))
 
   closeApi(apiWrapper)
 })

+ 24 - 35
tests/network-tests/src/iznik/tests/proposals/validatorCountProposalTest.ts

@@ -4,18 +4,16 @@ import { Keyring, WsProvider } from '@polkadot/api'
 import BN from 'bn.js'
 import { setTestTimeout } from '../../utils/setTestTimeout'
 import tap from 'tap'
-import { registerJoystreamTypes } from '@alexandria/types'
 import { closeApi } from '../../utils/closeApi'
 import { ApiWrapper } from '../../utils/apiWrapper'
 import { Utils } from '../../utils/utils'
-import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule'
-import { ElectCouncilFixture } from '../fixtures/councilElectionModule'
 import { ValidatorCountProposalFixture } from '../fixtures/proposalsModule'
-import { PaidTermId } from '@nicaea/types/members'
+import { PaidTermId } from '@alexandria/types/members'
+import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase'
+import { DbService } from '../../services/dbService'
 
 tap.mocha.describe('Validator count proposal scenario', async () => {
   initConfig()
-  registerJoystreamTypes()
 
   const nodeUrl: string = process.env.NODE_URL!
   const sudoUri: string = process.env.SUDO_ACCOUNT_URI!
@@ -23,12 +21,13 @@ tap.mocha.describe('Validator count proposal scenario', async () => {
   const provider = new WsProvider(nodeUrl)
   const apiWrapper: ApiWrapper = await ApiWrapper.create(provider)
   const sudo: KeyringPair = keyring.addFromUri(sudoUri)
+  const db: DbService = DbService.getInstance()
 
   const N: number = +process.env.MEMBERSHIP_CREATION_N!
-  const m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
-  const m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
 
-  const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!)
+  const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!))
   const K: number = +process.env.COUNCIL_ELECTION_K!
   const greaterStake: BN = new BN(+process.env.COUNCIL_STAKE_GREATER_AMOUNT!)
   const lesserStake: BN = new BN(+process.env.COUNCIL_STAKE_LESSER_AMOUNT!)
@@ -37,32 +36,22 @@ tap.mocha.describe('Validator count proposal scenario', async () => {
 
   setTestTimeout(apiWrapper, durationInBlocks)
 
-  const firstMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    m1KeyPairs,
-    paidTerms
-  )
-  tap.test('Creating first set of members', async () => firstMemberSetFixture.runner(false))
-
-  const secondMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    m2KeyPairs,
-    paidTerms
-  )
-  tap.test('Creating second set of members', async () => secondMemberSetFixture.runner(false))
-
-  const electCouncilFixture: ElectCouncilFixture = new ElectCouncilFixture(
-    apiWrapper,
-    m1KeyPairs,
-    m2KeyPairs,
-    K,
-    sudo,
-    greaterStake,
-    lesserStake
-  )
-  tap.test('Elect council', async () => electCouncilFixture.runner(false))
+  if (db.hasCouncil()) {
+    m1KeyPairs = db.getMembers()
+    m2KeyPairs = db.getCouncil()
+  } else {
+    const councilElectionHappyCaseFixture = new CouncilElectionHappyCaseFixture(
+      apiWrapper,
+      sudo,
+      m1KeyPairs,
+      m2KeyPairs,
+      paidTerms,
+      K,
+      greaterStake,
+      lesserStake
+    )
+    await councilElectionHappyCaseFixture.runner(false)
+  }
 
   const validatorCountProposalFixture: ValidatorCountProposalFixture = new ValidatorCountProposalFixture(
     apiWrapper,
@@ -71,7 +60,7 @@ tap.mocha.describe('Validator count proposal scenario', async () => {
     sudo,
     validatorCountIncrement
   )
-  tap.test('Validator count proposal', async () => validatorCountProposalFixture.runner(false))
+  tap.test('Validator count proposal', async () => await validatorCountProposalFixture.runner(false))
 
   closeApi(apiWrapper)
 })

+ 26 - 37
tests/network-tests/src/iznik/tests/proposals/workingGroupMintCapacityProposalTest.ts

@@ -4,20 +4,18 @@ import { Keyring, WsProvider } from '@polkadot/api'
 import BN from 'bn.js'
 import { setTestTimeout } from '../../utils/setTestTimeout'
 import tap from 'tap'
-import { registerJoystreamTypes } from '@alexandria/types'
 import { closeApi } from '../../utils/closeApi'
 import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper'
 import { Utils } from '../../utils/utils'
-import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule'
-import { ElectCouncilFixture } from '../fixtures/councilElectionModule'
 import { VoteForProposalFixture, WorkingGroupMintCapacityProposalFixture } from '../fixtures/proposalsModule'
 import { ExpectMintCapacityChangedFixture } from '../fixtures/workingGroupModule'
-import { PaidTermId } from '@nicaea/types/members'
-import { ProposalId } from '@nicaea/types/proposals'
+import { PaidTermId } from '@alexandria/types/members'
+import { ProposalId } from '@alexandria/types/proposals'
+import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase'
+import { DbService } from '../../services/dbService'
 
 tap.mocha.describe('Set storage working group mint capacity scenario', async () => {
   initConfig()
-  registerJoystreamTypes()
 
   const nodeUrl: string = process.env.NODE_URL!
   const sudoUri: string = process.env.SUDO_ACCOUNT_URI!
@@ -25,12 +23,13 @@ tap.mocha.describe('Set storage working group mint capacity scenario', async ()
   const provider = new WsProvider(nodeUrl)
   const apiWrapper: ApiWrapper = await ApiWrapper.create(provider)
   const sudo: KeyringPair = keyring.addFromUri(sudoUri)
+  const db: DbService = DbService.getInstance()
 
   const N: number = +process.env.MEMBERSHIP_CREATION_N!
-  const m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
-  const m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  let m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
 
-  const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!)
+  const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!))
   const K: number = +process.env.COUNCIL_ELECTION_K!
   const greaterStake: BN = new BN(+process.env.COUNCIL_STAKE_GREATER_AMOUNT!)
   const lesserStake: BN = new BN(+process.env.COUNCIL_STAKE_LESSER_AMOUNT!)
@@ -39,32 +38,22 @@ tap.mocha.describe('Set storage working group mint capacity scenario', async ()
 
   setTestTimeout(apiWrapper, durationInBlocks)
 
-  const firstMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    m1KeyPairs,
-    paidTerms
-  )
-  tap.test('Creating first set of members', async () => firstMemberSetFixture.runner(false))
-
-  const secondMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    m2KeyPairs,
-    paidTerms
-  )
-  tap.test('Creating second set of members', async () => secondMemberSetFixture.runner(false))
-
-  const electCouncilFixture: ElectCouncilFixture = new ElectCouncilFixture(
-    apiWrapper,
-    m1KeyPairs,
-    m2KeyPairs,
-    K,
-    sudo,
-    greaterStake,
-    lesserStake
-  )
-  tap.test('Elect council', async () => electCouncilFixture.runner(false))
+  if (db.hasCouncil()) {
+    m1KeyPairs = db.getMembers()
+    m2KeyPairs = db.getCouncil()
+  } else {
+    const councilElectionHappyCaseFixture = new CouncilElectionHappyCaseFixture(
+      apiWrapper,
+      sudo,
+      m1KeyPairs,
+      m2KeyPairs,
+      paidTerms,
+      K,
+      greaterStake,
+      lesserStake
+    )
+    await councilElectionHappyCaseFixture.runner(false)
+  }
 
   const newMintCapacity: BN = (await apiWrapper.getWorkingGroupMintCapacity(WorkingGroups.StorageWorkingGroup)).add(
     mintCapacityIncrement
@@ -76,7 +65,7 @@ tap.mocha.describe('Set storage working group mint capacity scenario', async ()
     newMintCapacity,
     WorkingGroups.StorageWorkingGroup
   )
-  tap.test('Propose mint capacity', async () => workingGroupMintCapacityProposalFixture.runner(false))
+  tap.test('Propose mint capacity', async () => await workingGroupMintCapacityProposalFixture.runner(false))
 
   let voteForProposalFixture: VoteForProposalFixture
   const expectMintCapacityChanged: ExpectMintCapacityChangedFixture = new ExpectMintCapacityChangedFixture(
@@ -88,7 +77,7 @@ tap.mocha.describe('Set storage working group mint capacity scenario', async ()
       apiWrapper,
       m2KeyPairs,
       sudo,
-      workingGroupMintCapacityProposalFixture.getResult() as ProposalId
+      workingGroupMintCapacityProposalFixture.getCreatedProposalId() as ProposalId
     )
     voteForProposalFixture.runner(false)
     await expectMintCapacityChanged.runner(false)

+ 36 - 85
tests/network-tests/src/iznik/tests/workingGroup/atLeastValueBugTest.ts

@@ -1,41 +1,34 @@
 import { initConfig } from '../../utils/config'
-import { registerJoystreamTypes } from '@alexandria/types'
 import { closeApi } from '../../utils/closeApi'
 import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper'
 import { WsProvider, Keyring } from '@polkadot/api'
 import { KeyringPair } from '@polkadot/keyring/types'
 import { setTestTimeout } from '../../utils/setTestTimeout'
-import {
-  AddLeaderOpeningFixture,
-  AddWorkerOpeningFixture,
-  ApplyForOpeningFixture,
-  BeginLeaderApplicationReviewFixture,
-  FillLeaderOpeningFixture,
-  LeaveRoleFixture,
-} from '../fixtures/workingGroupModule'
+import { AddWorkerOpeningFixture, LeaveRoleFixture } from '../fixtures/workingGroupModule'
 import BN from 'bn.js'
 import tap from 'tap'
-import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule'
 import { Utils } from '../../utils/utils'
-import { PaidTermId } from '@nicaea/types/members'
-import { OpeningId } from '@nicaea/types/hiring'
+import { PaidTermId } from '@alexandria/types/members'
+import { DbService } from '../../services/dbService'
+import { LeaderHiringHappyCaseFixture } from '../fixtures/leaderHiringHappyCase'
 
-tap.mocha.describe('Worker application happy case scenario', async () => {
+tap.mocha.describe('Zero at least value bug scenario', async () => {
   initConfig()
-  registerJoystreamTypes()
 
   const nodeUrl: string = process.env.NODE_URL!
   const sudoUri: string = process.env.SUDO_ACCOUNT_URI!
   const keyring = new Keyring({ type: 'sr25519' })
+  const db: DbService = DbService.getInstance()
+
   const provider = new WsProvider(nodeUrl)
   const apiWrapper: ApiWrapper = await ApiWrapper.create(provider)
   const sudo: KeyringPair = keyring.addFromUri(sudoUri)
 
   const N: number = +process.env.WORKING_GROUP_N!
-  const nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  let nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
   const leadKeyPair: KeyringPair[] = Utils.createKeyPairs(keyring, 1)
 
-  const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!)
+  const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!))
   const applicationStake: BN = new BN(process.env.WORKING_GROUP_APPLICATION_STAKE!)
   const roleStake: BN = new BN(process.env.WORKING_GROUP_ROLE_STAKE!)
   const firstRewardInterval: BN = new BN(process.env.LONG_REWARD_INTERVAL!)
@@ -47,72 +40,26 @@ tap.mocha.describe('Worker application happy case scenario', async () => {
 
   setTestTimeout(apiWrapper, durationInBlocks)
 
-  const happyCaseFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    nKeyPairs,
-    paidTerms
-  )
-  tap.test('Creating a set of members', async () => happyCaseFixture.runner(false))
-
-  const leaderHappyCaseFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    leadKeyPair,
-    paidTerms
-  )
-  tap.test('Buying membership for leader account', async () => leaderHappyCaseFixture.runner(false))
-
-  const addLeaderOpeningFixture: AddLeaderOpeningFixture = new AddLeaderOpeningFixture(
-    apiWrapper,
-    nKeyPairs,
-    sudo,
-    applicationStake,
-    roleStake,
-    openingActivationDelay,
-    WorkingGroups.StorageWorkingGroup
-  )
-  tap.test('Add lead opening', async () => await addLeaderOpeningFixture.runner(false))
-
-  let applyForLeaderOpeningFixture: ApplyForOpeningFixture
-  tap.test('Apply for lead opening', async () => {
-    applyForLeaderOpeningFixture = new ApplyForOpeningFixture(
+  if (db.hasLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))) {
+    nKeyPairs = db.getMembers()
+    leadKeyPair[0] = db.getLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))
+  } else {
+    const leaderHiringHappyCaseFixture: LeaderHiringHappyCaseFixture = new LeaderHiringHappyCaseFixture(
       apiWrapper,
-      leadKeyPair,
       sudo,
+      nKeyPairs,
+      leadKeyPair,
+      paidTerms,
       applicationStake,
       roleStake,
-      addLeaderOpeningFixture.getResult() as OpeningId,
-      WorkingGroups.StorageWorkingGroup
-    )
-    await applyForLeaderOpeningFixture.runner(false)
-  })
-
-  let beginLeaderApplicationReviewFixture: BeginLeaderApplicationReviewFixture
-  tap.test('Begin lead application review', async () => {
-    beginLeaderApplicationReviewFixture = new BeginLeaderApplicationReviewFixture(
-      apiWrapper,
-      sudo,
-      addLeaderOpeningFixture.getResult() as OpeningId,
-      WorkingGroups.StorageWorkingGroup
-    )
-    await beginLeaderApplicationReviewFixture.runner(false)
-  })
-
-  let fillLeaderOpeningFixture: FillLeaderOpeningFixture
-  tap.test('Fill lead opening', async () => {
-    fillLeaderOpeningFixture = new FillLeaderOpeningFixture(
-      apiWrapper,
-      leadKeyPair,
-      sudo,
-      addLeaderOpeningFixture.getResult() as OpeningId,
-      firstRewardInterval,
+      openingActivationDelay,
       rewardInterval,
+      firstRewardInterval,
       payoutAmount,
       WorkingGroups.StorageWorkingGroup
     )
-    await fillLeaderOpeningFixture.runner(false)
-  })
+    await leaderHiringHappyCaseFixture.runner(false)
+  }
 
   const addWorkerOpeningWithoutStakeFixture: AddWorkerOpeningFixture = new AddWorkerOpeningFixture(
     apiWrapper,
@@ -125,8 +72,9 @@ tap.mocha.describe('Worker application happy case scenario', async () => {
     unstakingPeriod,
     WorkingGroups.StorageWorkingGroup
   )
-  tap.test('Add worker opening with 0 stake, expect failure', async () =>
-    addWorkerOpeningWithoutStakeFixture.runner(true)
+  tap.test(
+    'Add worker opening with 0 stake, expect failure',
+    async () => await addWorkerOpeningWithoutStakeFixture.runner(true)
   )
 
   const addWorkerOpeningWithoutUnstakingPeriodFixture: AddWorkerOpeningFixture = new AddWorkerOpeningFixture(
@@ -140,17 +88,20 @@ tap.mocha.describe('Worker application happy case scenario', async () => {
     new BN(0),
     WorkingGroups.StorageWorkingGroup
   )
-  tap.test('Add worker opening with 0 unstaking period, expect failure', async () =>
-    addWorkerOpeningWithoutUnstakingPeriodFixture.runner(true)
+  tap.test(
+    'Add worker opening with 0 unstaking period, expect failure',
+    async () => await addWorkerOpeningWithoutUnstakingPeriodFixture.runner(true)
   )
 
-  const leaveRoleFixture: LeaveRoleFixture = new LeaveRoleFixture(
-    apiWrapper,
-    leadKeyPair,
-    sudo,
-    WorkingGroups.StorageWorkingGroup
-  )
-  tap.test('Leaving lead role', async () => leaveRoleFixture.runner(false))
+  if (!db.hasLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))) {
+    const leaveRoleFixture: LeaveRoleFixture = new LeaveRoleFixture(
+      apiWrapper,
+      leadKeyPair,
+      sudo,
+      WorkingGroups.StorageWorkingGroup
+    )
+    tap.test('Leaving lead role', async () => await leaveRoleFixture.runner(false))
+  }
 
   closeApi(apiWrapper)
 })

+ 42 - 85
tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsLeadTest.ts

@@ -1,5 +1,4 @@
 import { initConfig } from '../../utils/config'
-import { registerJoystreamTypes } from '@alexandria/types'
 import { closeApi } from '../../utils/closeApi'
 import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper'
 import { WsProvider, Keyring } from '@polkadot/api'
@@ -18,29 +17,31 @@ import {
   SlashFixture,
   TerminateRoleFixture,
 } from '../fixtures/workingGroupModule'
-import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule'
 import { Utils } from '../../utils/utils'
 import BN from 'bn.js'
 import tap from 'tap'
-import { PaidTermId } from '@nicaea/types/members'
-import { OpeningId } from '@nicaea/types/hiring'
+import { PaidTermId } from '@alexandria/types/members'
+import { OpeningId } from '@alexandria/types/hiring'
+import { DbService } from '../../services/dbService'
+import { LeaderHiringHappyCaseFixture } from '../fixtures/leaderHiringHappyCase'
 
-tap.mocha.describe('Manage worker as worker scenario', async () => {
+tap.mocha.describe('Manage worker as lead scenario', async () => {
   initConfig()
-  registerJoystreamTypes()
 
   const nodeUrl: string = process.env.NODE_URL!
   const sudoUri: string = process.env.SUDO_ACCOUNT_URI!
   const keyring = new Keyring({ type: 'sr25519' })
+  const db: DbService = DbService.getInstance()
+
   const provider = new WsProvider(nodeUrl)
   const apiWrapper: ApiWrapper = await ApiWrapper.create(provider)
   const sudo: KeyringPair = keyring.addFromUri(sudoUri)
 
   const N: number = +process.env.WORKING_GROUP_N!
-  const nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  let nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
   const leadKeyPair: KeyringPair[] = Utils.createKeyPairs(keyring, 1)
 
-  const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!)
+  const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!))
   const applicationStake: BN = new BN(process.env.WORKING_GROUP_APPLICATION_STAKE!)
   const roleStake: BN = new BN(process.env.WORKING_GROUP_ROLE_STAKE!)
   const firstRewardInterval: BN = new BN(process.env.LONG_REWARD_INTERVAL!)
@@ -52,72 +53,26 @@ tap.mocha.describe('Manage worker as worker scenario', async () => {
 
   setTestTimeout(apiWrapper, durationInBlocks)
 
-  const happyCaseFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    nKeyPairs,
-    paidTerms
-  )
-  tap.test('Creating a set of members', async () => happyCaseFixture.runner(false))
-
-  const leaderHappyCaseFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    leadKeyPair,
-    paidTerms
-  )
-  tap.test('Buying membership for leader account', async () => leaderHappyCaseFixture.runner(false))
-
-  const addLeaderOpeningFixture: AddLeaderOpeningFixture = new AddLeaderOpeningFixture(
-    apiWrapper,
-    nKeyPairs,
-    sudo,
-    applicationStake,
-    roleStake,
-    openingActivationDelay,
-    WorkingGroups.StorageWorkingGroup
-  )
-  tap.test('Add lead opening', async () => await addLeaderOpeningFixture.runner(false))
-
-  let applyForLeaderOpeningFixture: ApplyForOpeningFixture
-  tap.test('Apply for lead opening', async () => {
-    applyForLeaderOpeningFixture = new ApplyForOpeningFixture(
+  if (db.hasLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))) {
+    nKeyPairs = db.getMembers()
+    leadKeyPair[0] = db.getLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))
+  } else {
+    const leaderHiringHappyCaseFixture: LeaderHiringHappyCaseFixture = new LeaderHiringHappyCaseFixture(
       apiWrapper,
-      leadKeyPair,
       sudo,
+      nKeyPairs,
+      leadKeyPair,
+      paidTerms,
       applicationStake,
       roleStake,
-      addLeaderOpeningFixture.getResult() as OpeningId,
-      WorkingGroups.StorageWorkingGroup
-    )
-    await applyForLeaderOpeningFixture.runner(false)
-  })
-
-  let beginLeaderApplicationReviewFixture: BeginLeaderApplicationReviewFixture
-  tap.test('Begin lead application review', async () => {
-    beginLeaderApplicationReviewFixture = new BeginLeaderApplicationReviewFixture(
-      apiWrapper,
-      sudo,
-      addLeaderOpeningFixture.getResult() as OpeningId,
-      WorkingGroups.StorageWorkingGroup
-    )
-    await beginLeaderApplicationReviewFixture.runner(false)
-  })
-
-  let fillLeaderOpeningFixture: FillLeaderOpeningFixture
-  tap.test('Fill lead opening', async () => {
-    fillLeaderOpeningFixture = new FillLeaderOpeningFixture(
-      apiWrapper,
-      leadKeyPair,
-      sudo,
-      addLeaderOpeningFixture.getResult() as OpeningId,
-      firstRewardInterval,
+      openingActivationDelay,
       rewardInterval,
+      firstRewardInterval,
       payoutAmount,
       WorkingGroups.StorageWorkingGroup
     )
-    await fillLeaderOpeningFixture.runner(false)
-  })
+    await leaderHiringHappyCaseFixture.runner(false)
+  }
 
   const addWorkerOpeningFixture: AddWorkerOpeningFixture = new AddWorkerOpeningFixture(
     apiWrapper,
@@ -130,7 +85,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => {
     unstakingPeriod,
     WorkingGroups.StorageWorkingGroup
   )
-  tap.test('Add worker opening', async () => addWorkerOpeningFixture.runner(false))
+  tap.test('Add worker opening', async () => await addWorkerOpeningFixture.runner(false))
 
   let applyForWorkerOpeningFixture: ApplyForOpeningFixture
   tap.test('First apply for worker opening', async () => {
@@ -140,7 +95,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => {
       sudo,
       applicationStake,
       roleStake,
-      addWorkerOpeningFixture.getResult() as OpeningId,
+      addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId,
       WorkingGroups.StorageWorkingGroup
     )
     await applyForWorkerOpeningFixture.runner(false)
@@ -152,7 +107,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => {
       apiWrapper,
       leadKeyPair[0],
       sudo,
-      addWorkerOpeningFixture.getResult() as OpeningId,
+      addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId,
       WorkingGroups.StorageWorkingGroup
     )
     await beginApplicationReviewFixture.runner(false)
@@ -165,7 +120,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => {
       nKeyPairs,
       leadKeyPair[0],
       sudo,
-      addWorkerOpeningFixture.getResult() as OpeningId,
+      addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId,
       firstRewardInterval,
       rewardInterval,
       payoutAmount,
@@ -180,7 +135,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => {
     sudo,
     WorkingGroups.StorageWorkingGroup
   )
-  tap.test('Leaving lead role', async () => leaveRoleFixture.runner(false))
+  tap.test('Leaving lead role', async () => await leaveRoleFixture.runner(false))
 
   const decreaseStakeFailureFixture: DecreaseStakeFixture = new DecreaseStakeFixture(
     apiWrapper,
@@ -189,7 +144,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => {
     sudo,
     WorkingGroups.StorageWorkingGroup
   )
-  tap.test('Decrease worker stake, expect failure', async () => decreaseStakeFailureFixture.runner(true))
+  tap.test('Decrease worker stake, expect failure', async () => await decreaseStakeFailureFixture.runner(true))
 
   const addNewLeaderOpeningFixture: AddLeaderOpeningFixture = new AddLeaderOpeningFixture(
     apiWrapper,
@@ -210,7 +165,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => {
       sudo,
       applicationStake,
       roleStake,
-      addNewLeaderOpeningFixture.getResult() as OpeningId,
+      addNewLeaderOpeningFixture.getCreatedOpeningId() as OpeningId,
       WorkingGroups.StorageWorkingGroup
     )
     await applyForNewLeaderOpeningFixture.runner(false)
@@ -221,7 +176,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => {
     beginNewLeaderApplicationReviewFixture = new BeginLeaderApplicationReviewFixture(
       apiWrapper,
       sudo,
-      addNewLeaderOpeningFixture.getResult() as OpeningId,
+      addNewLeaderOpeningFixture.getCreatedOpeningId() as OpeningId,
       WorkingGroups.StorageWorkingGroup
     )
     await beginNewLeaderApplicationReviewFixture.runner(false)
@@ -233,7 +188,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => {
       apiWrapper,
       leadKeyPair,
       sudo,
-      addNewLeaderOpeningFixture.getResult() as OpeningId,
+      addNewLeaderOpeningFixture.getCreatedOpeningId() as OpeningId,
       firstRewardInterval,
       rewardInterval,
       payoutAmount,
@@ -249,7 +204,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => {
     sudo,
     WorkingGroups.StorageWorkingGroup
   )
-  tap.test('Decrease worker stake', async () => decreaseStakeFixture.runner(false))
+  tap.test('Decrease worker stake', async () => await decreaseStakeFixture.runner(false))
 
   const slashFixture: SlashFixture = new SlashFixture(
     apiWrapper,
@@ -258,7 +213,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => {
     sudo,
     WorkingGroups.StorageWorkingGroup
   )
-  tap.test('Slash worker', async () => slashFixture.runner(false))
+  tap.test('Slash worker', async () => await slashFixture.runner(false))
 
   const terminateRoleFixture: TerminateRoleFixture = new TerminateRoleFixture(
     apiWrapper,
@@ -267,15 +222,17 @@ tap.mocha.describe('Manage worker as worker scenario', async () => {
     sudo,
     WorkingGroups.StorageWorkingGroup
   )
-  tap.test('Terminate worker role', async () => terminateRoleFixture.runner(false))
+  tap.test('Terminate worker role', async () => await terminateRoleFixture.runner(false))
 
-  const newLeaveRoleFixture: LeaveRoleFixture = new LeaveRoleFixture(
-    apiWrapper,
-    leadKeyPair,
-    sudo,
-    WorkingGroups.StorageWorkingGroup
-  )
-  tap.test('Leaving lead role', async () => newLeaveRoleFixture.runner(false))
+  if (!db.hasLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))) {
+    const leaveRoleFixture: LeaveRoleFixture = new LeaveRoleFixture(
+      apiWrapper,
+      leadKeyPair,
+      sudo,
+      WorkingGroups.StorageWorkingGroup
+    )
+    tap.test('Leaving lead role', async () => await leaveRoleFixture.runner(false))
+  }
 
   closeApi(apiWrapper)
 })

+ 36 - 82
tests/network-tests/src/iznik/tests/workingGroup/manageWorkerAsWorkerTest.ts

@@ -1,45 +1,43 @@
 import { initConfig } from '../../utils/config'
-import { registerJoystreamTypes } from '@alexandria/types'
 import { closeApi } from '../../utils/closeApi'
 import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper'
 import { WsProvider, Keyring } from '@polkadot/api'
 import { KeyringPair } from '@polkadot/keyring/types'
 import { setTestTimeout } from '../../utils/setTestTimeout'
 import {
-  AddLeaderOpeningFixture,
   AddWorkerOpeningFixture,
   ApplyForOpeningFixture,
   BeginApplicationReviewFixture,
-  BeginLeaderApplicationReviewFixture,
-  FillLeaderOpeningFixture,
   FillOpeningFixture,
   IncreaseStakeFixture,
   LeaveRoleFixture,
   UpdateRewardAccountFixture,
 } from '../fixtures/workingGroupModule'
-import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule'
 import { Utils } from '../../utils/utils'
 import BN from 'bn.js'
 import tap from 'tap'
-import { PaidTermId } from '@nicaea/types/members'
-import { OpeningId } from '@nicaea/types/hiring'
+import { PaidTermId } from '@alexandria/types/members'
+import { OpeningId } from '@alexandria/types/hiring'
+import { DbService } from '../../services/dbService'
+import { LeaderHiringHappyCaseFixture } from '../fixtures/leaderHiringHappyCase'
 
 tap.mocha.describe('Manage worker as worker scenario', async () => {
   initConfig()
-  registerJoystreamTypes()
 
   const nodeUrl: string = process.env.NODE_URL!
   const sudoUri: string = process.env.SUDO_ACCOUNT_URI!
   const keyring = new Keyring({ type: 'sr25519' })
+  const db: DbService = DbService.getInstance()
+
   const provider = new WsProvider(nodeUrl)
   const apiWrapper: ApiWrapper = await ApiWrapper.create(provider)
   const sudo: KeyringPair = keyring.addFromUri(sudoUri)
 
   const N: number = +process.env.WORKING_GROUP_N!
-  const nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  let nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
   const leadKeyPair: KeyringPair[] = Utils.createKeyPairs(keyring, 1)
 
-  const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!)
+  const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!))
   const applicationStake: BN = new BN(process.env.WORKING_GROUP_APPLICATION_STAKE!)
   const roleStake: BN = new BN(process.env.WORKING_GROUP_ROLE_STAKE!)
   const firstRewardInterval: BN = new BN(process.env.LONG_REWARD_INTERVAL!)
@@ -51,72 +49,26 @@ tap.mocha.describe('Manage worker as worker scenario', async () => {
 
   setTestTimeout(apiWrapper, durationInBlocks)
 
-  const happyCaseFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    nKeyPairs,
-    paidTerms
-  )
-  tap.test('Creating a set of members', async () => happyCaseFixture.runner(false))
-
-  const leaderHappyCaseFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    leadKeyPair,
-    paidTerms
-  )
-  tap.test('Buying membership for leader account', async () => leaderHappyCaseFixture.runner(false))
-
-  const addLeaderOpeningFixture: AddLeaderOpeningFixture = new AddLeaderOpeningFixture(
-    apiWrapper,
-    nKeyPairs,
-    sudo,
-    applicationStake,
-    roleStake,
-    openingActivationDelay,
-    WorkingGroups.StorageWorkingGroup
-  )
-  tap.test('Add lead opening', async () => await addLeaderOpeningFixture.runner(false))
-
-  let applyForLeaderOpeningFixture: ApplyForOpeningFixture
-  tap.test('Apply for lead opening', async () => {
-    applyForLeaderOpeningFixture = new ApplyForOpeningFixture(
+  if (db.hasLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))) {
+    nKeyPairs = db.getMembers()
+    leadKeyPair[0] = db.getLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))
+  } else {
+    const leaderHiringHappyCaseFixture: LeaderHiringHappyCaseFixture = new LeaderHiringHappyCaseFixture(
       apiWrapper,
-      leadKeyPair,
       sudo,
+      nKeyPairs,
+      leadKeyPair,
+      paidTerms,
       applicationStake,
       roleStake,
-      addLeaderOpeningFixture.getResult() as OpeningId,
-      WorkingGroups.StorageWorkingGroup
-    )
-    await applyForLeaderOpeningFixture.runner(false)
-  })
-
-  let beginLeaderApplicationReviewFixture: BeginLeaderApplicationReviewFixture
-  tap.test('Begin lead application review', async () => {
-    beginLeaderApplicationReviewFixture = new BeginLeaderApplicationReviewFixture(
-      apiWrapper,
-      sudo,
-      addLeaderOpeningFixture.getResult() as OpeningId,
-      WorkingGroups.StorageWorkingGroup
-    )
-    await beginLeaderApplicationReviewFixture.runner(false)
-  })
-
-  let fillLeaderOpeningFixture: FillLeaderOpeningFixture
-  tap.test('Fill lead opening', async () => {
-    fillLeaderOpeningFixture = new FillLeaderOpeningFixture(
-      apiWrapper,
-      leadKeyPair,
-      sudo,
-      addLeaderOpeningFixture.getResult() as OpeningId,
-      firstRewardInterval,
+      openingActivationDelay,
       rewardInterval,
+      firstRewardInterval,
       payoutAmount,
       WorkingGroups.StorageWorkingGroup
     )
-    await fillLeaderOpeningFixture.runner(false)
-  })
+    await leaderHiringHappyCaseFixture.runner(false)
+  }
 
   const addWorkerOpeningFixture: AddWorkerOpeningFixture = new AddWorkerOpeningFixture(
     apiWrapper,
@@ -129,7 +81,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => {
     unstakingPeriod,
     WorkingGroups.StorageWorkingGroup
   )
-  tap.test('Add worker opening', async () => addWorkerOpeningFixture.runner(false))
+  tap.test('Add worker opening', async () => await addWorkerOpeningFixture.runner(false))
 
   let applyForWorkerOpeningFixture: ApplyForOpeningFixture
   tap.test('First apply for worker opening', async () => {
@@ -139,7 +91,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => {
       sudo,
       applicationStake,
       roleStake,
-      addWorkerOpeningFixture.getResult() as OpeningId,
+      addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId,
       WorkingGroups.StorageWorkingGroup
     )
     await applyForWorkerOpeningFixture.runner(false)
@@ -151,7 +103,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => {
       apiWrapper,
       leadKeyPair[0],
       sudo,
-      addWorkerOpeningFixture.getResult() as OpeningId,
+      addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId,
       WorkingGroups.StorageWorkingGroup
     )
     await beginApplicationReviewFixture.runner(false)
@@ -164,7 +116,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => {
       nKeyPairs,
       leadKeyPair[0],
       sudo,
-      addWorkerOpeningFixture.getResult() as OpeningId,
+      addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId,
       firstRewardInterval,
       rewardInterval,
       payoutAmount,
@@ -179,7 +131,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => {
     sudo,
     WorkingGroups.StorageWorkingGroup
   )
-  tap.test('Increase worker stake', async () => increaseStakeFixture.runner(false))
+  tap.test('Increase worker stake', async () => await increaseStakeFixture.runner(false))
 
   const updateRewardAccountFixture: UpdateRewardAccountFixture = new UpdateRewardAccountFixture(
     apiWrapper,
@@ -188,7 +140,7 @@ tap.mocha.describe('Manage worker as worker scenario', async () => {
     sudo,
     WorkingGroups.StorageWorkingGroup
   )
-  tap.test('Update reward account', async () => updateRewardAccountFixture.runner(false))
+  tap.test('Update reward account', async () => await updateRewardAccountFixture.runner(false))
 
   const updateRoleAccountFixture: UpdateRewardAccountFixture = new UpdateRewardAccountFixture(
     apiWrapper,
@@ -197,15 +149,17 @@ tap.mocha.describe('Manage worker as worker scenario', async () => {
     sudo,
     WorkingGroups.StorageWorkingGroup
   )
-  tap.test('Update role account', async () => updateRoleAccountFixture.runner(false))
+  tap.test('Update role account', async () => await updateRoleAccountFixture.runner(false))
 
-  const newLeaveRoleFixture: LeaveRoleFixture = new LeaveRoleFixture(
-    apiWrapper,
-    leadKeyPair,
-    sudo,
-    WorkingGroups.StorageWorkingGroup
-  )
-  tap.test('Leaving lead role', async () => newLeaveRoleFixture.runner(false))
+  if (!db.hasLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))) {
+    const leaveRoleFixture: LeaveRoleFixture = new LeaveRoleFixture(
+      apiWrapper,
+      leadKeyPair,
+      sudo,
+      WorkingGroups.StorageWorkingGroup
+    )
+    tap.test('Leaving lead role', async () => await leaveRoleFixture.runner(false))
+  }
 
   closeApi(apiWrapper)
 })

+ 35 - 81
tests/network-tests/src/iznik/tests/workingGroup/workerApplicationHappyCaseTest.ts

@@ -1,5 +1,4 @@
 import { initConfig } from '../../utils/config'
-import { registerJoystreamTypes } from '@alexandria/types'
 import { closeApi } from '../../utils/closeApi'
 import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper'
 import { WsProvider, Keyring } from '@polkadot/api'
@@ -7,38 +6,37 @@ import { KeyringPair } from '@polkadot/keyring/types'
 import { setTestTimeout } from '../../utils/setTestTimeout'
 import BN from 'bn.js'
 import tap from 'tap'
-import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule'
 import { Utils } from '../../utils/utils'
 import {
-  AddLeaderOpeningFixture,
   AddWorkerOpeningFixture,
   ApplyForOpeningFixture,
   BeginApplicationReviewFixture,
-  BeginLeaderApplicationReviewFixture,
-  FillLeaderOpeningFixture,
   FillOpeningFixture,
   LeaveRoleFixture,
   WithdrawApplicationFixture,
 } from '../fixtures/workingGroupModule'
-import { PaidTermId } from '@nicaea/types/members'
-import { OpeningId } from '@nicaea/types/hiring'
+import { PaidTermId } from '@alexandria/types/members'
+import { OpeningId } from '@alexandria/types/hiring'
+import { DbService } from '../../services/dbService'
+import { LeaderHiringHappyCaseFixture } from '../fixtures/leaderHiringHappyCase'
 
 tap.mocha.describe('Worker application happy case scenario', async () => {
   initConfig()
-  registerJoystreamTypes()
 
   const nodeUrl: string = process.env.NODE_URL!
   const sudoUri: string = process.env.SUDO_ACCOUNT_URI!
   const keyring = new Keyring({ type: 'sr25519' })
+  const db: DbService = DbService.getInstance()
+
   const provider = new WsProvider(nodeUrl)
   const apiWrapper: ApiWrapper = await ApiWrapper.create(provider)
   const sudo: KeyringPair = keyring.addFromUri(sudoUri)
 
   const N: number = +process.env.WORKING_GROUP_N!
-  const nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  let nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
   const leadKeyPair: KeyringPair[] = Utils.createKeyPairs(keyring, 1)
 
-  const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!)
+  const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!))
   const applicationStake: BN = new BN(process.env.WORKING_GROUP_APPLICATION_STAKE!)
   const roleStake: BN = new BN(process.env.WORKING_GROUP_ROLE_STAKE!)
   const firstRewardInterval: BN = new BN(process.env.LONG_REWARD_INTERVAL!)
@@ -50,72 +48,26 @@ tap.mocha.describe('Worker application happy case scenario', async () => {
 
   setTestTimeout(apiWrapper, durationInBlocks)
 
-  const happyCaseFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    nKeyPairs,
-    paidTerms
-  )
-  tap.test('Creating a set of members', async () => happyCaseFixture.runner(false))
-
-  const leaderHappyCaseFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    leadKeyPair,
-    paidTerms
-  )
-  tap.test('Buying membership for leader account', async () => leaderHappyCaseFixture.runner(false))
-
-  const addLeaderOpeningFixture: AddLeaderOpeningFixture = new AddLeaderOpeningFixture(
-    apiWrapper,
-    nKeyPairs,
-    sudo,
-    applicationStake,
-    roleStake,
-    openingActivationDelay,
-    WorkingGroups.StorageWorkingGroup
-  )
-  tap.test('Add lead opening', async () => await addLeaderOpeningFixture.runner(false))
-
-  let applyForLeaderOpeningFixture: ApplyForOpeningFixture
-  tap.test('Apply for lead opening', async () => {
-    applyForLeaderOpeningFixture = new ApplyForOpeningFixture(
+  if (db.hasLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))) {
+    nKeyPairs = db.getMembers()
+    leadKeyPair[0] = db.getLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))
+  } else {
+    const leaderHiringHappyCaseFixture: LeaderHiringHappyCaseFixture = new LeaderHiringHappyCaseFixture(
       apiWrapper,
-      leadKeyPair,
       sudo,
+      nKeyPairs,
+      leadKeyPair,
+      paidTerms,
       applicationStake,
       roleStake,
-      addLeaderOpeningFixture.getResult() as OpeningId,
-      WorkingGroups.StorageWorkingGroup
-    )
-    await applyForLeaderOpeningFixture.runner(false)
-  })
-
-  let beginLeaderApplicationReviewFixture: BeginLeaderApplicationReviewFixture
-  tap.test('Begin lead application review', async () => {
-    beginLeaderApplicationReviewFixture = new BeginLeaderApplicationReviewFixture(
-      apiWrapper,
-      sudo,
-      addLeaderOpeningFixture.getResult() as OpeningId,
-      WorkingGroups.StorageWorkingGroup
-    )
-    await beginLeaderApplicationReviewFixture.runner(false)
-  })
-
-  let fillLeaderOpeningFixture: FillLeaderOpeningFixture
-  tap.test('Fill lead opening', async () => {
-    fillLeaderOpeningFixture = new FillLeaderOpeningFixture(
-      apiWrapper,
-      leadKeyPair,
-      sudo,
-      addLeaderOpeningFixture.getResult() as OpeningId,
-      firstRewardInterval,
+      openingActivationDelay,
       rewardInterval,
+      firstRewardInterval,
       payoutAmount,
       WorkingGroups.StorageWorkingGroup
     )
-    await fillLeaderOpeningFixture.runner(false)
-  })
+    await leaderHiringHappyCaseFixture.runner(false)
+  }
 
   const addWorkerOpeningFixture: AddWorkerOpeningFixture = new AddWorkerOpeningFixture(
     apiWrapper,
@@ -128,7 +80,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => {
     unstakingPeriod,
     WorkingGroups.StorageWorkingGroup
   )
-  tap.test('Add worker opening', async () => addWorkerOpeningFixture.runner(false))
+  tap.test('Add worker opening', async () => await addWorkerOpeningFixture.runner(false))
 
   let firstApplyForWorkerOpeningFixture: ApplyForOpeningFixture
   tap.test('First apply for worker opening', async () => {
@@ -138,7 +90,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => {
       sudo,
       applicationStake,
       roleStake,
-      addWorkerOpeningFixture.getResult() as OpeningId,
+      addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId,
       WorkingGroups.StorageWorkingGroup
     )
     await firstApplyForWorkerOpeningFixture.runner(false)
@@ -150,7 +102,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => {
     sudo,
     WorkingGroups.StorageWorkingGroup
   )
-  tap.test('Withdraw worker application', async () => withdrawApplicationFixture.runner(false))
+  tap.test('Withdraw worker application', async () => await withdrawApplicationFixture.runner(false))
 
   let secondApplyForWorkerOpeningFixture: ApplyForOpeningFixture
   tap.test('Second apply for worker opening', async () => {
@@ -160,7 +112,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => {
       sudo,
       applicationStake,
       roleStake,
-      addWorkerOpeningFixture.getResult() as OpeningId,
+      addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId,
       WorkingGroups.StorageWorkingGroup
     )
     await secondApplyForWorkerOpeningFixture.runner(false)
@@ -172,7 +124,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => {
       apiWrapper,
       leadKeyPair[0],
       sudo,
-      addWorkerOpeningFixture.getResult() as OpeningId,
+      addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId,
       WorkingGroups.StorageWorkingGroup
     )
     await beginApplicationReviewFixture.runner(false)
@@ -185,7 +137,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => {
       nKeyPairs,
       leadKeyPair[0],
       sudo,
-      addWorkerOpeningFixture.getResult() as OpeningId,
+      addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId,
       firstRewardInterval,
       rewardInterval,
       payoutAmount,
@@ -194,13 +146,15 @@ tap.mocha.describe('Worker application happy case scenario', async () => {
     await fillOpeningFixture.runner(false)
   })
 
-  const leaveRoleFixture: LeaveRoleFixture = new LeaveRoleFixture(
-    apiWrapper,
-    leadKeyPair,
-    sudo,
-    WorkingGroups.StorageWorkingGroup
-  )
-  tap.test('Leaving lead role', async () => leaveRoleFixture.runner(false))
+  if (!db.hasLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))) {
+    const leaveRoleFixture: LeaveRoleFixture = new LeaveRoleFixture(
+      apiWrapper,
+      leadKeyPair,
+      sudo,
+      WorkingGroups.StorageWorkingGroup
+    )
+    tap.test('Leaving lead role', async () => await leaveRoleFixture.runner(false))
+  }
 
   closeApi(apiWrapper)
 })

+ 37 - 83
tests/network-tests/src/iznik/tests/workingGroup/workerApplicationRejectionCaseTest.ts

@@ -1,5 +1,4 @@
 import { initConfig } from '../../utils/config'
-import { registerJoystreamTypes } from '@alexandria/types'
 import { closeApi } from '../../utils/closeApi'
 import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper'
 import { WsProvider, Keyring } from '@polkadot/api'
@@ -7,38 +6,37 @@ import { KeyringPair } from '@polkadot/keyring/types'
 import { setTestTimeout } from '../../utils/setTestTimeout'
 import BN from 'bn.js'
 import tap from 'tap'
-import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule'
 import { Utils } from '../../utils/utils'
 import {
   AcceptApplicationsFixture,
-  AddLeaderOpeningFixture,
   AddWorkerOpeningFixture,
   ApplyForOpeningFixture,
-  BeginLeaderApplicationReviewFixture,
-  FillLeaderOpeningFixture,
   LeaveRoleFixture,
   TerminateApplicationsFixture,
 } from '../fixtures/workingGroupModule'
-import { PaidTermId } from '@nicaea/types/members'
-import { OpeningId } from '@nicaea/types/hiring'
+import { PaidTermId } from '@alexandria/types/members'
+import { OpeningId } from '@alexandria/types/hiring'
+import { DbService } from '../../services/dbService'
+import { LeaderHiringHappyCaseFixture } from '../fixtures/leaderHiringHappyCase'
 
-tap.mocha.describe('Worker application happy case scenario', async () => {
+tap.mocha.describe('Worker application rejection case scenario', async () => {
   initConfig()
-  registerJoystreamTypes()
 
   const nodeUrl: string = process.env.NODE_URL!
   const sudoUri: string = process.env.SUDO_ACCOUNT_URI!
   const keyring = new Keyring({ type: 'sr25519' })
+  const db: DbService = DbService.getInstance()
+
   const provider = new WsProvider(nodeUrl)
   const apiWrapper: ApiWrapper = await ApiWrapper.create(provider)
   const sudo: KeyringPair = keyring.addFromUri(sudoUri)
 
   const N: number = +process.env.WORKING_GROUP_N!
-  const nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  let nKeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
   const leadKeyPair: KeyringPair[] = Utils.createKeyPairs(keyring, 1)
   const nonMemberKeyPairs = Utils.createKeyPairs(keyring, N)
 
-  const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!)
+  const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!))
   const applicationStake: BN = new BN(process.env.WORKING_GROUP_APPLICATION_STAKE!)
   const roleStake: BN = new BN(process.env.WORKING_GROUP_ROLE_STAKE!)
   const firstRewardInterval: BN = new BN(process.env.LONG_REWARD_INTERVAL!)
@@ -51,72 +49,26 @@ tap.mocha.describe('Worker application happy case scenario', async () => {
 
   setTestTimeout(apiWrapper, durationInBlocks)
 
-  const happyCaseFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    nKeyPairs,
-    paidTerms
-  )
-  tap.test('Creating a set of members', async () => happyCaseFixture.runner(false))
-
-  const leaderHappyCaseFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    leadKeyPair,
-    paidTerms
-  )
-  tap.test('Buying membership for leader account', async () => leaderHappyCaseFixture.runner(false))
-
-  const addLeaderOpeningFixture: AddLeaderOpeningFixture = new AddLeaderOpeningFixture(
-    apiWrapper,
-    nKeyPairs,
-    sudo,
-    applicationStake,
-    roleStake,
-    leadOpeningActivationDelay,
-    WorkingGroups.StorageWorkingGroup
-  )
-  tap.test('Add lead opening', async () => await addLeaderOpeningFixture.runner(false))
-
-  let applyForLeaderOpeningFixture: ApplyForOpeningFixture
-  tap.test('Apply for lead opening', async () => {
-    applyForLeaderOpeningFixture = new ApplyForOpeningFixture(
+  if (db.hasLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))) {
+    nKeyPairs = db.getMembers()
+    leadKeyPair[0] = db.getLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))
+  } else {
+    const leaderHiringHappyCaseFixture: LeaderHiringHappyCaseFixture = new LeaderHiringHappyCaseFixture(
       apiWrapper,
-      leadKeyPair,
       sudo,
+      nKeyPairs,
+      leadKeyPair,
+      paidTerms,
       applicationStake,
       roleStake,
-      addLeaderOpeningFixture.getResult() as OpeningId,
-      WorkingGroups.StorageWorkingGroup
-    )
-    await applyForLeaderOpeningFixture.runner(false)
-  })
-
-  let beginLeaderApplicationReviewFixture: BeginLeaderApplicationReviewFixture
-  tap.test('Begin lead application review', async () => {
-    beginLeaderApplicationReviewFixture = new BeginLeaderApplicationReviewFixture(
-      apiWrapper,
-      sudo,
-      addLeaderOpeningFixture.getResult() as OpeningId,
-      WorkingGroups.StorageWorkingGroup
-    )
-    await beginLeaderApplicationReviewFixture.runner(false)
-  })
-
-  let fillLeaderOpeningFixture: FillLeaderOpeningFixture
-  tap.test('Fill lead opening', async () => {
-    fillLeaderOpeningFixture = new FillLeaderOpeningFixture(
-      apiWrapper,
-      leadKeyPair,
-      sudo,
-      addLeaderOpeningFixture.getResult() as OpeningId,
-      firstRewardInterval,
+      leadOpeningActivationDelay,
       rewardInterval,
+      firstRewardInterval,
       payoutAmount,
       WorkingGroups.StorageWorkingGroup
     )
-    await fillLeaderOpeningFixture.runner(false)
-  })
+    await leaderHiringHappyCaseFixture.runner(false)
+  }
 
   const addWorkerOpeningFixture: AddWorkerOpeningFixture = new AddWorkerOpeningFixture(
     apiWrapper,
@@ -129,7 +81,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => {
     unstakingPeriod,
     WorkingGroups.StorageWorkingGroup
   )
-  tap.test('Add worker opening', async () => addWorkerOpeningFixture.runner(false))
+  tap.test('Add worker opening', async () => await addWorkerOpeningFixture.runner(false))
 
   let applyForWorkerOpeningBeforeAcceptanceFixture: ApplyForOpeningFixture
   tap.test('Apply for worker opening, expect failure', async () => {
@@ -139,7 +91,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => {
       sudo,
       applicationStake,
       roleStake,
-      addWorkerOpeningFixture.getResult() as OpeningId,
+      addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId,
       WorkingGroups.StorageWorkingGroup
     )
     await applyForWorkerOpeningBeforeAcceptanceFixture.runner(true)
@@ -151,10 +103,10 @@ tap.mocha.describe('Worker application happy case scenario', async () => {
       apiWrapper,
       leadKeyPair[0],
       sudo,
-      addWorkerOpeningFixture.getResult() as OpeningId,
+      addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId,
       WorkingGroups.StorageWorkingGroup
     )
-    acceptApplicationsFixture.runner(false)
+    await acceptApplicationsFixture.runner(false)
   })
 
   let applyForWorkerOpeningAsNonMemberFixture: ApplyForOpeningFixture
@@ -165,7 +117,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => {
       sudo,
       applicationStake,
       roleStake,
-      addWorkerOpeningFixture.getResult() as OpeningId,
+      addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId,
       WorkingGroups.StorageWorkingGroup
     )
     await applyForWorkerOpeningAsNonMemberFixture.runner(true)
@@ -179,7 +131,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => {
       sudo,
       applicationStake,
       roleStake,
-      addWorkerOpeningFixture.getResult() as OpeningId,
+      addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId,
       WorkingGroups.StorageWorkingGroup
     )
     await applyForWorkerOpeningFixture.runner(false)
@@ -192,15 +144,17 @@ tap.mocha.describe('Worker application happy case scenario', async () => {
     sudo,
     WorkingGroups.StorageWorkingGroup
   )
-  tap.test('Terminate worker applicaitons', async () => terminateApplicationsFixture.runner(false))
+  tap.test('Terminate worker applicaitons', async () => await terminateApplicationsFixture.runner(false))
 
-  const leaveRoleFixture: LeaveRoleFixture = new LeaveRoleFixture(
-    apiWrapper,
-    leadKeyPair,
-    sudo,
-    WorkingGroups.StorageWorkingGroup
-  )
-  tap.test('Leaving lead role', async () => leaveRoleFixture.runner(false))
+  if (!db.hasLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))) {
+    const leaveRoleFixture: LeaveRoleFixture = new LeaveRoleFixture(
+      apiWrapper,
+      leadKeyPair,
+      sudo,
+      WorkingGroups.StorageWorkingGroup
+    )
+    tap.test('Leaving lead role', async () => await leaveRoleFixture.runner(false))
+  }
 
   closeApi(apiWrapper)
 })

+ 59 - 100
tests/network-tests/src/iznik/tests/workingGroup/workerPayoutTest.ts

@@ -1,49 +1,49 @@
 import { initConfig } from '../../utils/config'
-import { registerJoystreamTypes } from '@alexandria/types'
 import { closeApi } from '../../utils/closeApi'
 import { ApiWrapper, WorkingGroups } from '../../utils/apiWrapper'
 import { WsProvider, Keyring } from '@polkadot/api'
 import { KeyringPair } from '@polkadot/keyring/types'
 import { setTestTimeout } from '../../utils/setTestTimeout'
 import {
-  AddLeaderOpeningFixture,
   AddWorkerOpeningFixture,
   ApplyForOpeningFixture,
   AwaitPayoutFixture,
   BeginApplicationReviewFixture,
-  BeginLeaderApplicationReviewFixture,
   ExpectMintCapacityChangedFixture,
-  FillLeaderOpeningFixture,
   FillOpeningFixture,
   LeaveRoleFixture,
 } from '../fixtures/workingGroupModule'
 import BN from 'bn.js'
 import tap from 'tap'
-import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule'
 import { Utils } from '../../utils/utils'
-import { ElectCouncilFixture } from '../fixtures/councilElectionModule'
 import { VoteForProposalFixture, WorkingGroupMintCapacityProposalFixture } from '../fixtures/proposalsModule'
-import { PaidTermId } from '@nicaea/types/members'
-import { OpeningId } from '@nicaea/types/hiring'
-import { ProposalId } from '@nicaea/types/proposals'
+import { PaidTermId } from '@alexandria/types/members'
+import { OpeningId } from '@alexandria/types/hiring'
+import { ProposalId } from '@alexandria/types/proposals'
+import { DbService } from '../../services/dbService'
+import { CouncilElectionHappyCaseFixture } from '../fixtures/councilElectionHappyCase'
+import { LeaderHiringHappyCaseFixture } from '../fixtures/leaderHiringHappyCase'
+import { BuyMembershipHappyCaseFixture } from '../fixtures/membershipModule'
 
-tap.mocha.describe('Worker application happy case scenario', async () => {
+tap.mocha.describe('Worker payout scenario', async () => {
   initConfig()
-  registerJoystreamTypes()
 
   const nodeUrl: string = process.env.NODE_URL!
   const sudoUri: string = process.env.SUDO_ACCOUNT_URI!
   const keyring = new Keyring({ type: 'sr25519' })
+  const db: DbService = DbService.getInstance()
+
   const provider = new WsProvider(nodeUrl)
   const apiWrapper: ApiWrapper = await ApiWrapper.create(provider)
   const sudo: KeyringPair = keyring.addFromUri(sudoUri)
 
   const N: number = +process.env.WORKING_GROUP_N!
   const m1KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
-  const m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  let m2KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
+  const m3KeyPairs: KeyringPair[] = Utils.createKeyPairs(keyring, N)
   const leadKeyPair: KeyringPair[] = Utils.createKeyPairs(keyring, 1)
 
-  const paidTerms: PaidTermId = new PaidTermId(+process.env.MEMBERSHIP_PAID_TERMS!)
+  const paidTerms: PaidTermId = apiWrapper.createPaidTermId(new BN(+process.env.MEMBERSHIP_PAID_TERMS!))
   const K: number = +process.env.COUNCIL_ELECTION_K!
   const greaterStake: BN = new BN(+process.env.COUNCIL_STAKE_GREATER_AMOUNT!)
   const lesserStake: BN = new BN(+process.env.COUNCIL_STAKE_LESSER_AMOUNT!)
@@ -56,96 +56,53 @@ tap.mocha.describe('Worker application happy case scenario', async () => {
   const payoutAmount: BN = new BN(process.env.PAYOUT_AMOUNT!)
   const unstakingPeriod: BN = new BN(process.env.STORAGE_WORKING_GROUP_UNSTAKING_PERIOD!)
   const mintCapacity: BN = new BN(process.env.STORAGE_WORKING_GROUP_MINTING_CAPACITY!)
-  const durationInBlocks = 48
+  const durationInBlocks = 58
   const openingActivationDelay: BN = new BN(0)
 
   setTestTimeout(apiWrapper, durationInBlocks)
 
-  const firstMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    m1KeyPairs,
-    paidTerms
-  )
-  tap.test('Creating first set of members', async () => firstMemberSetFixture.runner(false))
-
-  const secondMemberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    m2KeyPairs,
-    paidTerms
-  )
-  tap.test('Creating second set of members', async () => secondMemberSetFixture.runner(false))
-
-  const electCouncilFixture: ElectCouncilFixture = new ElectCouncilFixture(
-    apiWrapper,
-    m1KeyPairs,
-    m2KeyPairs,
-    K,
-    sudo,
-    greaterStake,
-    lesserStake
-  )
-  tap.test('Elect council', async () => electCouncilFixture.runner(false))
-
-  const leaderHappyCaseFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
-    apiWrapper,
-    sudo,
-    leadKeyPair,
-    paidTerms
-  )
-  tap.test('Buying membership for leader account', async () => leaderHappyCaseFixture.runner(false))
-
-  const addLeaderOpeningFixture: AddLeaderOpeningFixture = new AddLeaderOpeningFixture(
-    apiWrapper,
-    m1KeyPairs,
-    sudo,
-    applicationStake,
-    roleStake,
-    openingActivationDelay,
-    WorkingGroups.StorageWorkingGroup
-  )
-  tap.test('Add lead opening', async () => await addLeaderOpeningFixture.runner(false))
-
-  let applyForLeaderOpeningFixture: ApplyForOpeningFixture
-  tap.test('Apply for lead opening', async () => {
-    applyForLeaderOpeningFixture = new ApplyForOpeningFixture(
+  if (db.hasCouncil()) {
+    const memberSetFixture: BuyMembershipHappyCaseFixture = new BuyMembershipHappyCaseFixture(
       apiWrapper,
-      leadKeyPair,
       sudo,
-      applicationStake,
-      roleStake,
-      addLeaderOpeningFixture.getResult() as OpeningId,
-      WorkingGroups.StorageWorkingGroup
+      m1KeyPairs,
+      paidTerms
     )
-    await applyForLeaderOpeningFixture.runner(false)
-  })
-
-  let beginLeaderApplicationReviewFixture: BeginLeaderApplicationReviewFixture
-  tap.test('Begin lead application review', async () => {
-    beginLeaderApplicationReviewFixture = new BeginLeaderApplicationReviewFixture(
+    tap.test('Recreating set of members', async () => await memberSetFixture.runner(false))
+    m2KeyPairs = db.getCouncil()
+  } else {
+    const councilElectionHappyCaseFixture = new CouncilElectionHappyCaseFixture(
       apiWrapper,
       sudo,
-      addLeaderOpeningFixture.getResult() as OpeningId,
-      WorkingGroups.StorageWorkingGroup
+      m1KeyPairs,
+      m2KeyPairs,
+      paidTerms,
+      K,
+      greaterStake,
+      lesserStake
     )
-    await beginLeaderApplicationReviewFixture.runner(false)
-  })
+    await councilElectionHappyCaseFixture.runner(false)
+  }
 
-  let fillLeaderOpeningFixture: FillLeaderOpeningFixture
-  tap.test('Fill lead opening', async () => {
-    fillLeaderOpeningFixture = new FillLeaderOpeningFixture(
+  if (db.hasLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))) {
+    leadKeyPair[0] = db.getLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))
+  } else {
+    const leaderHiringHappyCaseFixture: LeaderHiringHappyCaseFixture = new LeaderHiringHappyCaseFixture(
       apiWrapper,
-      leadKeyPair,
       sudo,
-      addLeaderOpeningFixture.getResult() as OpeningId,
-      leaderFirstRewardInterval,
+      m3KeyPairs,
+      leadKeyPair,
+      paidTerms,
+      applicationStake,
+      roleStake,
+      openingActivationDelay,
       leaderRewardInterval,
+      leaderFirstRewardInterval,
       payoutAmount,
       WorkingGroups.StorageWorkingGroup
     )
-    await fillLeaderOpeningFixture.runner(false)
-  })
+    await leaderHiringHappyCaseFixture.runner(false)
+  }
 
   const workingGroupMintCapacityProposalFixture: WorkingGroupMintCapacityProposalFixture = new WorkingGroupMintCapacityProposalFixture(
     apiWrapper,
@@ -154,7 +111,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => {
     mintCapacity,
     WorkingGroups.StorageWorkingGroup
   )
-  tap.test('Propose mint capacity', async () => workingGroupMintCapacityProposalFixture.runner(false))
+  tap.test('Propose mint capacity', async () => await workingGroupMintCapacityProposalFixture.runner(false))
 
   let voteForProposalFixture: VoteForProposalFixture
   const expectMintCapacityChanged: ExpectMintCapacityChangedFixture = new ExpectMintCapacityChangedFixture(
@@ -166,7 +123,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => {
       apiWrapper,
       m2KeyPairs,
       sudo,
-      workingGroupMintCapacityProposalFixture.getResult() as ProposalId
+      workingGroupMintCapacityProposalFixture.getCreatedProposalId() as ProposalId
     )
     voteForProposalFixture.runner(false)
     await expectMintCapacityChanged.runner(false)
@@ -183,7 +140,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => {
     unstakingPeriod,
     WorkingGroups.StorageWorkingGroup
   )
-  tap.test('Add worker opening', async () => addWorkerOpeningFixture.runner(false))
+  tap.test('Add worker opening', async () => await addWorkerOpeningFixture.runner(false))
 
   let applyForWorkerOpeningFixture: ApplyForOpeningFixture
   tap.test('First apply for worker opening', async () => {
@@ -193,7 +150,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => {
       sudo,
       applicationStake,
       roleStake,
-      addWorkerOpeningFixture.getResult() as OpeningId,
+      addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId,
       WorkingGroups.StorageWorkingGroup
     )
     await applyForWorkerOpeningFixture.runner(false)
@@ -205,7 +162,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => {
       apiWrapper,
       leadKeyPair[0],
       sudo,
-      addWorkerOpeningFixture.getResult() as OpeningId,
+      addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId,
       WorkingGroups.StorageWorkingGroup
     )
     await beginApplicationReviewFixture.runner(false)
@@ -218,7 +175,7 @@ tap.mocha.describe('Worker application happy case scenario', async () => {
       m1KeyPairs,
       leadKeyPair[0],
       sudo,
-      addWorkerOpeningFixture.getResult() as OpeningId,
+      addWorkerOpeningFixture.getCreatedOpeningId() as OpeningId,
       firstRewardInterval,
       rewardInterval,
       payoutAmount,
@@ -232,15 +189,17 @@ tap.mocha.describe('Worker application happy case scenario', async () => {
     m1KeyPairs,
     WorkingGroups.StorageWorkingGroup
   )
-  tap.test('Await worker payout', async () => awaitPayoutFixture.runner(false))
+  tap.test('Await worker payout', async () => await awaitPayoutFixture.runner(false))
 
-  const leaveRoleFixture: LeaveRoleFixture = new LeaveRoleFixture(
-    apiWrapper,
-    leadKeyPair,
-    sudo,
-    WorkingGroups.StorageWorkingGroup
-  )
-  tap.test('Leaving lead role', async () => leaveRoleFixture.runner(false))
+  if (!db.hasLeader(apiWrapper.getWorkingGroupString(WorkingGroups.StorageWorkingGroup))) {
+    const leaveRoleFixture: LeaveRoleFixture = new LeaveRoleFixture(
+      apiWrapper,
+      leadKeyPair,
+      sudo,
+      WorkingGroups.StorageWorkingGroup
+    )
+    tap.test('Leaving lead role', async () => await leaveRoleFixture.runner(false))
+  }
 
   closeApi(apiWrapper)
 })

+ 472 - 166
tests/network-tests/src/iznik/utils/apiWrapper.ts

@@ -1,38 +1,34 @@
 import { ApiPromise, WsProvider } from '@polkadot/api'
-import { Bytes, Option, u32, Vec } from '@polkadot/types'
+import { Bytes, Option, u32, Vec, StorageKey } from '@polkadot/types'
 import { Codec } from '@polkadot/types/types'
 import { KeyringPair } from '@polkadot/keyring/types'
-import { MemberId, PaidMembershipTerms, PaidTermId, UserInfo } from '@alexandria/types/members'
+import { MemberId, PaidMembershipTerms, PaidTermId } from '@alexandria/types/members'
 import { Mint, MintId } from '@alexandria/types/mint'
 import { Lead, LeadId } from '@alexandria/types/content-working-group'
 import {
   Application,
   ApplicationIdToWorkerIdMap,
-  RewardPolicy,
-  SlashingTerms,
   Worker,
   WorkerId,
   WorkingGroupOpeningPolicyCommitment,
 } from '@alexandria/types/working-group'
 import { ElectionStake, Seat } from '@alexandria/types/council'
-import { AccountId, Balance, BalanceOf, BlockNumber, Event, EventRecord } from '@polkadot/types/interfaces'
+import { AccountId, AccountInfo, Balance, BalanceOf, BlockNumber, Event, EventRecord } from '@polkadot/types/interfaces'
 import BN from 'bn.js'
 import { SubmittableExtrinsic } from '@polkadot/api/types'
 import { Sender } from './sender'
 import { Utils } from './utils'
 import { Stake, StakedState, StakeId } from '@alexandria/types/stake'
 import { RewardRelationship, RewardRelationshipId } from '@alexandria/types/recurring-rewards'
+import { types } from '@alexandria/types'
 import {
   ActivateOpeningAt,
   Application as HiringApplication,
   ApplicationId,
-  ApplicationRationingPolicy,
   Opening as HiringOpening,
   OpeningId,
-  StakingPolicy,
 } from '@alexandria/types/hiring'
 import { FillOpeningParameters, ProposalId } from '@alexandria/types/proposals'
-import { WorkingGroup } from '@alexandria/types/common'
 
 export enum WorkingGroups {
   StorageWorkingGroup = 'storageWorkingGroup',
@@ -43,7 +39,7 @@ export class ApiWrapper {
   private readonly sender: Sender
 
   public static async create(provider: WsProvider): Promise<ApiWrapper> {
-    const api = await ApiPromise.create({ provider })
+    const api = await ApiPromise.create({ provider, types })
     return new ApiWrapper(api)
   }
 
@@ -65,6 +61,10 @@ export class ApiWrapper {
     }
   }
 
+  public createPaidTermId(value: BN): PaidTermId {
+    return this.api.createType('PaidTermId', value)
+  }
+
   public async buyMembership(
     account: KeyringPair,
     paidTermsId: PaidTermId,
@@ -87,20 +87,22 @@ export class ApiWrapper {
     return this.api.query.members.memberIdsByControllerAccountId<Vec<MemberId>>(address)
   }
 
-  public getBalance(address: string): Promise<Balance> {
-    return this.api.query.balances.freeBalance<Balance>(address)
+  public async getBalance(address: string): Promise<Balance> {
+    const accountData: AccountInfo = await this.api.query.system.account<AccountInfo>(address)
+    return (await this.api.query.system.account<AccountInfo>(address)).data.free
   }
 
   public async transferBalance(from: KeyringPair, to: string, amount: BN): Promise<void> {
     return this.sender.signAndSend(this.api.tx.balances.transfer(to, amount), from)
   }
 
-  public getPaidMembershipTerms(paidTermsId: PaidTermId): Promise<Option<PaidMembershipTerms>> {
-    return this.api.query.members.paidMembershipTermsById<Option<PaidMembershipTerms>>(paidTermsId)
+  public getPaidMembershipTerms(paidTermsId: PaidTermId): Promise<PaidMembershipTerms> {
+    return this.api.query.members.paidMembershipTermsById<PaidMembershipTerms>(paidTermsId)
   }
 
-  public getMembershipFee(paidTermsId: PaidTermId): Promise<BN> {
-    return this.getPaidMembershipTerms(paidTermsId).then((terms) => terms.unwrap().fee)
+  public async getMembershipFee(paidTermsId: PaidTermId): Promise<BN> {
+    const terms: PaidMembershipTerms = await this.getPaidMembershipTerms(paidTermsId)
+    return terms.fee
   }
 
   public async transferBalanceToAccounts(from: KeyringPair, to: KeyringPair[], amount: BN): Promise<void[]> {
@@ -264,44 +266,50 @@ export class ApiWrapper {
   public estimateVoteForProposalFee(): BN {
     return this.estimateTxFee(
       (this.api.tx.proposalsEngine.vote(
-        new MemberId(0),
-        new ProposalId(0),
+        this.api.createType('MemberId', 0),
+        this.api.createType('ProposalId', 0),
         'Approve'
       ) as unknown) as SubmittableExtrinsic<'promise'>
     )
   }
 
   public estimateAddOpeningFee(module: WorkingGroups): BN {
-    const commitment: WorkingGroupOpeningPolicyCommitment = new WorkingGroupOpeningPolicyCommitment({
-      application_rationing_policy: new Option(ApplicationRationingPolicy, {
+    const commitment: WorkingGroupOpeningPolicyCommitment = this.api.createType('WorkingGroupOpeningPolicyCommitment', {
+      application_rationing_policy: this.api.createType('Option<ApplicationRationingPolicy>', {
         max_active_applicants: new BN(32) as u32,
       }),
       max_review_period_length: new BN(32) as u32,
-      application_staking_policy: new Option(StakingPolicy, {
+      application_staking_policy: this.api.createType('Option<StakingPolicy>', {
         amount: new BN(1),
         amount_mode: 'AtLeast',
         crowded_out_unstaking_period_length: new BN(1),
         review_period_expired_unstaking_period_length: new BN(1),
       }),
-      role_staking_policy: new Option(StakingPolicy, {
+      role_staking_policy: this.api.createType('Option<StakingPolicy>', {
         amount: new BN(1),
         amount_mode: 'AtLeast',
         crowded_out_unstaking_period_length: new BN(1),
         review_period_expired_unstaking_period_length: new BN(1),
       }),
-      role_slashing_terms: new SlashingTerms({
+      role_slashing_terms: this.api.createType('SlashingTerms', {
         Slashable: {
           max_count: new BN(0),
           max_percent_pts_per_time: new BN(0),
         },
       }),
-      fill_opening_successful_applicant_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber),
-      fill_opening_failed_applicant_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber),
-      fill_opening_failed_applicant_role_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber),
-      terminate_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber),
-      terminate_role_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber),
-      exit_role_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber),
-      exit_role_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber),
+      fill_opening_successful_applicant_application_stake_unstaking_period: this.api.createType(
+        'Option<BlockNumber>',
+        new BN(1)
+      ),
+      fill_opening_failed_applicant_application_stake_unstaking_period: this.api.createType(
+        'Option<BlockNumber>',
+        new BN(1)
+      ),
+      fill_opening_failed_applicant_role_stake_unstaking_period: this.api.createType('Option<BlockNumber>', new BN(1)),
+      terminate_application_stake_unstaking_period: this.api.createType('Option<BlockNumber>', new BN(1)),
+      terminate_role_stake_unstaking_period: this.api.createType('Option<BlockNumber>', new BN(1)),
+      exit_role_application_stake_unstaking_period: this.api.createType('Option<BlockNumber>', new BN(1)),
+      exit_role_stake_unstaking_period: this.api.createType('Option<BlockNumber>', new BN(1)),
     })
 
     return this.estimateTxFee(
@@ -316,15 +324,17 @@ export class ApiWrapper {
 
   public estimateAcceptApplicationsFee(module: WorkingGroups): BN {
     return this.estimateTxFee(
-      (this.api.tx[module].acceptApplications(new OpeningId(0)) as unknown) as SubmittableExtrinsic<'promise'>
+      (this.api.tx[module].acceptApplications(this.api.createType('OpeningId', 0)) as unknown) as SubmittableExtrinsic<
+        'promise'
+      >
     )
   }
 
   public estimateApplyOnOpeningFee(account: KeyringPair, module: WorkingGroups): BN {
     return this.estimateTxFee(
       (this.api.tx[module].applyOnOpening(
-        new MemberId(0),
-        new OpeningId(0),
+        this.api.createType('MemberId', 0),
+        this.api.createType('OpeningId', 0),
         account.address,
         0,
         0,
@@ -335,13 +345,15 @@ export class ApiWrapper {
 
   public estimateBeginApplicantReviewFee(module: WorkingGroups): BN {
     return this.estimateTxFee(
-      (this.api.tx[module].beginApplicantReview(new OpeningId(0)) as unknown) as SubmittableExtrinsic<'promise'>
+      (this.api.tx[module].beginApplicantReview(
+        this.api.createType('OpeningId', 0)
+      ) as unknown) as SubmittableExtrinsic<'promise'>
     )
   }
 
   public estimateFillOpeningFee(module: WorkingGroups): BN {
     return this.estimateTxFee(
-      (this.api.tx[module].fillOpening(new OpeningId(0), [new ApplicationId(0)], {
+      (this.api.tx[module].fillOpening(this.api.createType('OpeningId', 0), [this.api.createType('ApplicationId', 0)], {
         'amount_per_payout': 0,
         'next_payment_at_block': 0,
         'payout_interval': 0,
@@ -351,58 +363,75 @@ export class ApiWrapper {
 
   public estimateIncreaseStakeFee(module: WorkingGroups): BN {
     return this.estimateTxFee(
-      (this.api.tx[module].increaseStake(new WorkerId(0), 0) as unknown) as SubmittableExtrinsic<'promise'>
+      (this.api.tx[module].increaseStake(this.api.createType('WorkerId', 0), 0) as unknown) as SubmittableExtrinsic<
+        'promise'
+      >
     )
   }
 
   public estimateDecreaseStakeFee(module: WorkingGroups): BN {
     return this.estimateTxFee(
-      (this.api.tx[module].decreaseStake(new WorkerId(0), 0) as unknown) as SubmittableExtrinsic<'promise'>
+      (this.api.tx[module].decreaseStake(this.api.createType('WorkerId', 0), 0) as unknown) as SubmittableExtrinsic<
+        'promise'
+      >
     )
   }
 
   public estimateUpdateRoleAccountFee(address: string, module: WorkingGroups): BN {
     return this.estimateTxFee(
-      (this.api.tx[module].updateRoleAccount(new WorkerId(0), address) as unknown) as SubmittableExtrinsic<'promise'>
+      (this.api.tx[module].updateRoleAccount(
+        this.api.createType('WorkerId', 0),
+        address
+      ) as unknown) as SubmittableExtrinsic<'promise'>
     )
   }
 
   public estimateUpdateRewardAccountFee(address: string, module: WorkingGroups): BN {
     return this.estimateTxFee(
-      (this.api.tx[module].updateRewardAccount(new WorkerId(0), address) as unknown) as SubmittableExtrinsic<'promise'>
+      (this.api.tx[module].updateRewardAccount(
+        this.api.createType('WorkerId', 0),
+        address
+      ) as unknown) as SubmittableExtrinsic<'promise'>
     )
   }
 
   public estimateLeaveRoleFee(module: WorkingGroups): BN {
     return this.estimateTxFee(
-      (this.api.tx[module].leaveRole(new WorkerId(0), 'Long justification text') as unknown) as SubmittableExtrinsic<
-        'promise'
-      >
+      (this.api.tx[module].leaveRole(
+        this.api.createType('WorkerId', 0),
+        'Long justification text'
+      ) as unknown) as SubmittableExtrinsic<'promise'>
     )
   }
 
   public estimateWithdrawApplicationFee(module: WorkingGroups): BN {
     return this.estimateTxFee(
-      (this.api.tx[module].withdrawApplication(new ApplicationId(0)) as unknown) as SubmittableExtrinsic<'promise'>
+      (this.api.tx[module].withdrawApplication(
+        this.api.createType('ApplicationId', 0)
+      ) as unknown) as SubmittableExtrinsic<'promise'>
     )
   }
 
   public estimateTerminateApplicationFee(module: WorkingGroups): BN {
     return this.estimateTxFee(
-      (this.api.tx[module].terminateApplication(new ApplicationId(0)) as unknown) as SubmittableExtrinsic<'promise'>
+      (this.api.tx[module].terminateApplication(
+        this.api.createType('ApplicationId', 0)
+      ) as unknown) as SubmittableExtrinsic<'promise'>
     )
   }
 
   public estimateSlashStakeFee(module: WorkingGroups): BN {
     return this.estimateTxFee(
-      (this.api.tx[module].slashStake(new WorkerId(0), 0) as unknown) as SubmittableExtrinsic<'promise'>
+      (this.api.tx[module].slashStake(this.api.createType('WorkerId', 0), 0) as unknown) as SubmittableExtrinsic<
+        'promise'
+      >
     )
   }
 
   public estimateTerminateRoleFee(module: WorkingGroups): BN {
     return this.estimateTxFee(
       (this.api.tx[module].terminateRole(
-        new WorkerId(0),
+        this.api.createType('WorkerId', 0),
         'Long justification text explaining why the worker role will be terminated',
         false
       ) as unknown) as SubmittableExtrinsic<'promise'>
@@ -410,41 +439,47 @@ export class ApiWrapper {
   }
 
   public estimateProposeCreateWorkingGroupLeaderOpeningFee(): BN {
-    const commitment: WorkingGroupOpeningPolicyCommitment = new WorkingGroupOpeningPolicyCommitment({
-      application_rationing_policy: new Option(ApplicationRationingPolicy, {
+    const commitment: WorkingGroupOpeningPolicyCommitment = this.api.createType('WorkingGroupOpeningPolicyCommitment', {
+      application_rationing_policy: this.api.createType('Option<ApplicationRationingPolicy>', {
         max_active_applicants: new BN(32) as u32,
       }),
       max_review_period_length: new BN(32) as u32,
-      application_staking_policy: new Option(StakingPolicy, {
+      application_staking_policy: this.api.createType('Option<StakingPolicy>', {
         amount: new BN(1),
         amount_mode: 'AtLeast',
         crowded_out_unstaking_period_length: new BN(1),
         review_period_expired_unstaking_period_length: new BN(1),
       }),
-      role_staking_policy: new Option(StakingPolicy, {
+      role_staking_policy: this.api.createType('Option<StakingPolicy>', {
         amount: new BN(1),
         amount_mode: 'AtLeast',
         crowded_out_unstaking_period_length: new BN(1),
         review_period_expired_unstaking_period_length: new BN(1),
       }),
-      role_slashing_terms: new SlashingTerms({
+      role_slashing_terms: this.api.createType('SlashingTerms', {
         Slashable: {
           max_count: new BN(0),
           max_percent_pts_per_time: new BN(0),
         },
       }),
-      fill_opening_successful_applicant_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber),
-      fill_opening_failed_applicant_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber),
-      fill_opening_failed_applicant_role_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber),
-      terminate_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber),
-      terminate_role_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber),
-      exit_role_application_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber),
-      exit_role_stake_unstaking_period: new Option(u32, new BN(1) as BlockNumber),
+      fill_opening_successful_applicant_application_stake_unstaking_period: this.api.createType(
+        'Option<BlockNumber>',
+        new BN(1)
+      ),
+      fill_opening_failed_applicant_application_stake_unstaking_period: this.api.createType(
+        'Option<BlockNumber>',
+        new BN(1)
+      ),
+      fill_opening_failed_applicant_role_stake_unstaking_period: this.api.createType('Option<BlockNumber>', new BN(1)),
+      terminate_application_stake_unstaking_period: this.api.createType('Option<BlockNumber>', new BN(1)),
+      terminate_role_stake_unstaking_period: this.api.createType('Option<BlockNumber>', new BN(1)),
+      exit_role_application_stake_unstaking_period: this.api.createType('Option<BlockNumber>', new BN(1)),
+      exit_role_stake_unstaking_period: this.api.createType('Option<BlockNumber>', new BN(1)),
     })
 
     return this.estimateTxFee(
       (this.api.tx.proposalsCodex.createAddWorkingGroupLeaderOpeningProposal(
-        new MemberId(0),
+        this.api.createType('MemberId', 0),
         'some long title for the purpose of testing',
         'some long description for the purpose of testing',
         0,
@@ -461,34 +496,31 @@ export class ApiWrapper {
   public estimateProposeBeginWorkingGroupLeaderApplicationReviewFee(): BN {
     return this.estimateTxFee(
       (this.api.tx.proposalsCodex.createBeginReviewWorkingGroupLeaderApplicationsProposal(
-        new MemberId(0),
+        this.api.createType('MemberId', 0),
         'Some testing text used for estimation purposes which is longer than text expected during the test',
         'Some testing text used for estimation purposes which is longer than text expected during the test',
         0,
-        new OpeningId(0),
+        this.api.createType('OpeningId', 0),
         'Storage'
       ) as unknown) as SubmittableExtrinsic<'promise'>
     )
   }
 
   public estimateProposeFillLeaderOpeningFee(): BN {
-    const fillOpeningParameters: FillOpeningParameters = new FillOpeningParameters({
-      opening_id: new OpeningId(0),
-      successful_application_id: new ApplicationId(0),
-      reward_policy: new Option(
-        RewardPolicy,
-        new RewardPolicy({
-          amount_per_payout: new BN(1) as Balance,
-          next_payment_at_block: new BN(99999) as BlockNumber,
-          payout_interval: new Option(u32, new u32(99999)),
-        })
-      ),
-      working_group: new WorkingGroup('Storage'),
+    const fillOpeningParameters: FillOpeningParameters = this.api.createType('FillOpeningParameters', {
+      opening_id: this.api.createType('OpeningId', 0),
+      successful_application_id: this.api.createType('ApplicationId', 0),
+      reward_policy: this.api.createType('Option<RewardPolicy>', {
+        amount_per_payout: new BN(1) as Balance,
+        next_payment_at_block: new BN(99999) as BlockNumber,
+        payout_interval: this.api.createType('Option<u32>', new BN(99999)),
+      }),
+      working_group: this.api.createType('WorkingGroup', 'Storage'),
     })
 
     return this.estimateTxFee(
       (this.api.tx.proposalsCodex.createFillWorkingGroupLeaderOpeningProposal(
-        new MemberId(0),
+        this.api.createType('MemberId', 0),
         'Some testing text used for estimation purposes which is longer than text expected during the test',
         'Some testing text used for estimation purposes which is longer than text expected during the test',
         0,
@@ -500,12 +532,12 @@ export class ApiWrapper {
   public estimateProposeTerminateLeaderRoleFee(): BN {
     return this.estimateTxFee(
       (this.api.tx.proposalsCodex.createTerminateWorkingGroupLeaderRoleProposal(
-        new MemberId(0),
+        this.api.createType('MemberId', 0),
         'Some testing text used for estimation purposes which is longer than text expected during the test',
         'Some testing text used for estimation purposes which is longer than text expected during the test',
         0,
         {
-          'worker_id': new WorkerId(0),
+          'worker_id': this.api.createType('WorkerId', 0),
           'rationale': 'Exceptionaly long and extraordinary descriptive rationale',
           'slash': true,
           'working_group': 'Storage',
@@ -517,11 +549,11 @@ export class ApiWrapper {
   public estimateProposeLeaderRewardFee(): BN {
     return this.estimateTxFee(
       (this.api.tx.proposalsCodex.createSetWorkingGroupLeaderRewardProposal(
-        new MemberId(0),
+        this.api.createType('MemberId', 0),
         'Some testing text used for estimation purposes which is longer than text expected during the test',
         'Some testing text used for estimation purposes which is longer than text expected during the test',
         0,
-        new WorkerId(0),
+        this.api.createType('WorkerId', 0),
         0,
         'Storage'
       ) as unknown) as SubmittableExtrinsic<'promise'>
@@ -531,11 +563,11 @@ export class ApiWrapper {
   public estimateProposeDecreaseLeaderStakeFee(): BN {
     return this.estimateTxFee(
       (this.api.tx.proposalsCodex.createDecreaseWorkingGroupLeaderStakeProposal(
-        new MemberId(0),
+        this.api.createType('MemberId', 0),
         'Some testing text used for estimation purposes which is longer than text expected during the test',
         'Some testing text used for estimation purposes which is longer than text expected during the test',
         0,
-        new WorkerId(0),
+        this.api.createType('WorkerId', 0),
         0,
         'Storage'
       ) as unknown) as SubmittableExtrinsic<'promise'>
@@ -545,11 +577,11 @@ export class ApiWrapper {
   public estimateProposeSlashLeaderStakeFee(): BN {
     return this.estimateTxFee(
       (this.api.tx.proposalsCodex.createSlashWorkingGroupLeaderStakeProposal(
-        new MemberId(0),
+        this.api.createType('MemberId', 0),
         'Some testing text used for estimation purposes which is longer than text expected during the test',
         'Some testing text used for estimation purposes which is longer than text expected during the test',
         0,
-        new WorkerId(0),
+        this.api.createType('WorkerId', 0),
         0,
         'Storage'
       ) as unknown) as SubmittableExtrinsic<'promise'>
@@ -559,7 +591,7 @@ export class ApiWrapper {
   public estimateProposeWorkingGroupMintCapacityFee(): BN {
     return this.estimateTxFee(
       (this.api.tx.proposalsCodex.createSetWorkingGroupMintCapacityProposal(
-        new MemberId(0),
+        this.api.createType('MemberId', 0),
         'Some testing text used for estimation purposes which is longer than text expected during the test',
         'Some testing text used for estimation purposes which is longer than text expected during the test',
         0,
@@ -949,16 +981,14 @@ export class ApiWrapper {
 
   public async getContentWorkingGroupMintCapacity(): Promise<BN> {
     const mintId: MintId = await this.api.query.contentWorkingGroup.mint<MintId>()
-    const mintCodec = await this.api.query.minting.mints<Codec[]>(mintId)
-    const mint: Mint = (mintCodec[0] as unknown) as Mint
-    return mint.getField<Balance>('capacity')
+    const mint: Mint = await this.api.query.minting.mints<Mint>(mintId)
+    return mint.capacity
   }
 
   public async getWorkingGroupMintCapacity(module: WorkingGroups): Promise<BN> {
     const mintId: MintId = await this.api.query[module].mint<MintId>()
-    const mintCodec = await this.api.query.minting.mints<Codec[]>(mintId)
-    const mint: Mint = (mintCodec[0] as unknown) as Mint
-    return mint.getField<Balance>('capacity')
+    const mint: Mint = await this.api.query.minting.mints<Mint>(mintId)
+    return mint.capacity
   }
 
   public getValidatorCount(): Promise<BN> {
@@ -967,8 +997,7 @@ export class ApiWrapper {
 
   public async getCurrentLeadAddress(): Promise<string> {
     const leadId: Option<LeadId> = await this.api.query.contentWorkingGroup.currentLeadId<Option<LeadId>>()
-    const leadCodec = await this.api.query.contentWorkingGroup.leadById<Codec[]>(leadId.unwrap())
-    const lead = (leadCodec[0] as unknown) as Lead
+    const lead = await this.api.query.contentWorkingGroup.leadById<Lead>(leadId.unwrap())
     return lead.role_account.toString()
   }
 
@@ -980,84 +1009,338 @@ export class ApiWrapper {
     return accountWorkers !== undefined
   }
 
-  public async addOpening(
-    leader: KeyringPair,
-    actiavteAt: ActivateOpeningAt,
-    commitment: WorkingGroupOpeningPolicyCommitment,
-    text: string,
-    type: string,
-    module: WorkingGroups,
+  public async addOpening(openingParameters: {
+    leader: KeyringPair
+    activationDelay: BN
+    maxActiveApplicants: BN
+    maxReviewPeriodLength: BN
+    applicationStakingPolicyAmount: BN
+    applicationCrowdedOutUnstakingPeriodLength: BN
+    applicationReviewPeriodExpiredUnstakingPeriodLength: BN
+    roleStakingPolicyAmount: BN
+    roleCrowdedOutUnstakingPeriodLength: BN
+    roleReviewPeriodExpiredUnstakingPeriodLength: BN
+    slashableMaxCount: BN
+    slashableMaxPercentPtsPerTime: BN
+    fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod: BN
+    fillOpeningFailedApplicantApplicationStakeUnstakingPeriod: BN
+    fillOpeningFailedApplicantRoleStakeUnstakingPeriod: BN
+    terminateApplicationStakeUnstakingPeriod: BN
+    terminateRoleStakeUnstakingPeriod: BN
+    exitRoleApplicationStakeUnstakingPeriod: BN
+    exitRoleStakeUnstakingPeriod: BN
+    text: string
+    type: string
+    module: WorkingGroups
     expectFailure: boolean
-  ): Promise<void> {
-    return this.sender.signAndSend(
-      this.createAddOpeningTransaction(actiavteAt, commitment, text, type, module),
-      leader,
-      expectFailure
+  }): Promise<void> {
+    const activateAt: ActivateOpeningAt = this.api.createType(
+      'ActivateOpeningAt',
+      openingParameters.activationDelay.eqn(0)
+        ? 'CurrentBlock'
+        : { ExactBlock: (await this.getBestBlock()).add(openingParameters.activationDelay) }
     )
-  }
 
-  public async sudoAddOpening(
-    sudo: KeyringPair,
-    actiavteAt: ActivateOpeningAt,
-    commitment: WorkingGroupOpeningPolicyCommitment,
-    text: string,
-    type: string,
+    const commitment: WorkingGroupOpeningPolicyCommitment = this.api.createType('WorkingGroupOpeningPolicyCommitment', {
+      application_rationing_policy: this.api.createType('Option<ApplicationRationingPolicy>', {
+        max_active_applicants: openingParameters.maxActiveApplicants as u32,
+      }),
+      max_review_period_length: openingParameters.maxReviewPeriodLength as u32,
+      application_staking_policy: this.api.createType('Option<StakingPolicy>', {
+        amount: openingParameters.applicationStakingPolicyAmount,
+        amount_mode: 'AtLeast',
+        crowded_out_unstaking_period_length: openingParameters.applicationCrowdedOutUnstakingPeriodLength,
+        review_period_expired_unstaking_period_length:
+          openingParameters.applicationReviewPeriodExpiredUnstakingPeriodLength,
+      }),
+      role_staking_policy: this.api.createType('Option<StakingPolicy>', {
+        amount: openingParameters.roleStakingPolicyAmount,
+        amount_mode: 'AtLeast',
+        crowded_out_unstaking_period_length: openingParameters.roleCrowdedOutUnstakingPeriodLength,
+        review_period_expired_unstaking_period_length: openingParameters.roleReviewPeriodExpiredUnstakingPeriodLength,
+      }),
+      role_slashing_terms: this.api.createType('SlashingTerms', {
+        Slashable: {
+          max_count: openingParameters.slashableMaxCount,
+          max_percent_pts_per_time: openingParameters.slashableMaxPercentPtsPerTime,
+        },
+      }),
+      fill_opening_successful_applicant_application_stake_unstaking_period: this.api.createType(
+        'Option<BlockNumber>',
+        openingParameters.fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod
+      ),
+      fill_opening_failed_applicant_application_stake_unstaking_period: this.api.createType(
+        'Option<BlockNumber>',
+        openingParameters.fillOpeningFailedApplicantApplicationStakeUnstakingPeriod
+      ),
+      fill_opening_failed_applicant_role_stake_unstaking_period: this.api.createType(
+        'Option<BlockNumber>',
+        openingParameters.fillOpeningFailedApplicantRoleStakeUnstakingPeriod
+      ),
+      terminate_application_stake_unstaking_period: this.api.createType(
+        'Option<BlockNumber>',
+        openingParameters.terminateApplicationStakeUnstakingPeriod
+      ),
+      terminate_role_stake_unstaking_period: this.api.createType(
+        'Option<BlockNumber>',
+        openingParameters.terminateRoleStakeUnstakingPeriod
+      ),
+      exit_role_application_stake_unstaking_period: this.api.createType(
+        'Option<BlockNumber>',
+        openingParameters.exitRoleApplicationStakeUnstakingPeriod
+      ),
+      exit_role_stake_unstaking_period: this.api.createType(
+        'Option<BlockNumber>',
+        openingParameters.exitRoleStakeUnstakingPeriod
+      ),
+    })
+
+    return this.sender.signAndSend(
+      this.createAddOpeningTransaction(
+        activateAt,
+        commitment,
+        openingParameters.text,
+        openingParameters.type,
+        openingParameters.module
+      ),
+      openingParameters.leader,
+      openingParameters.expectFailure
+    )
+  }
+
+  public async sudoAddOpening(openingParameters: {
+    sudo: KeyringPair
+    activationDelay: BN
+    maxActiveApplicants: BN
+    maxReviewPeriodLength: BN
+    applicationStakingPolicyAmount: BN
+    applicationCrowdedOutUnstakingPeriodLength: BN
+    applicationReviewPeriodExpiredUnstakingPeriodLength: BN
+    roleStakingPolicyAmount: BN
+    roleCrowdedOutUnstakingPeriodLength: BN
+    roleReviewPeriodExpiredUnstakingPeriodLength: BN
+    slashableMaxCount: BN
+    slashableMaxPercentPtsPerTime: BN
+    fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod: BN
+    fillOpeningFailedApplicantApplicationStakeUnstakingPeriod: BN
+    fillOpeningFailedApplicantRoleStakeUnstakingPeriod: BN
+    terminateApplicationStakeUnstakingPeriod: BN
+    terminateRoleStakeUnstakingPeriod: BN
+    exitRoleApplicationStakeUnstakingPeriod: BN
+    exitRoleStakeUnstakingPeriod: BN
+    text: string
+    type: string
     module: WorkingGroups
-  ): Promise<void> {
+  }): Promise<void> {
+    const activateAt: ActivateOpeningAt = this.api.createType(
+      'ActivateOpeningAt',
+      openingParameters.activationDelay.eqn(0)
+        ? 'CurrentBlock'
+        : { ExactBlock: (await this.getBestBlock()).add(openingParameters.activationDelay) }
+    )
+
+    const commitment: WorkingGroupOpeningPolicyCommitment = this.api.createType('WorkingGroupOpeningPolicyCommitment', {
+      application_rationing_policy: this.api.createType('Option<ApplicationRationingPolicy>', {
+        max_active_applicants: openingParameters.maxActiveApplicants as u32,
+      }),
+      max_review_period_length: openingParameters.maxReviewPeriodLength as u32,
+      application_staking_policy: this.api.createType('Option<StakingPolicy>', {
+        amount: openingParameters.applicationStakingPolicyAmount,
+        amount_mode: 'AtLeast',
+        crowded_out_unstaking_period_length: openingParameters.applicationCrowdedOutUnstakingPeriodLength,
+        review_period_expired_unstaking_period_length:
+          openingParameters.applicationReviewPeriodExpiredUnstakingPeriodLength,
+      }),
+      role_staking_policy: this.api.createType('Option<StakingPolicy>', {
+        amount: openingParameters.roleStakingPolicyAmount,
+        amount_mode: 'AtLeast',
+        crowded_out_unstaking_period_length: openingParameters.roleCrowdedOutUnstakingPeriodLength,
+        review_period_expired_unstaking_period_length: openingParameters.roleReviewPeriodExpiredUnstakingPeriodLength,
+      }),
+      role_slashing_terms: this.api.createType('SlashingTerms', {
+        Slashable: {
+          max_count: openingParameters.slashableMaxCount,
+          max_percent_pts_per_time: openingParameters.slashableMaxPercentPtsPerTime,
+        },
+      }),
+      fill_opening_successful_applicant_application_stake_unstaking_period: this.api.createType(
+        'Option<BlockNumber>',
+        openingParameters.fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod
+      ),
+      fill_opening_failed_applicant_application_stake_unstaking_period: this.api.createType(
+        'Option<BlockNumber>',
+        openingParameters.fillOpeningFailedApplicantApplicationStakeUnstakingPeriod
+      ),
+      fill_opening_failed_applicant_role_stake_unstaking_period: this.api.createType(
+        'Option<BlockNumber>',
+        openingParameters.fillOpeningFailedApplicantRoleStakeUnstakingPeriod
+      ),
+      terminate_application_stake_unstaking_period: this.api.createType(
+        'Option<BlockNumber>',
+        openingParameters.terminateApplicationStakeUnstakingPeriod
+      ),
+      terminate_role_stake_unstaking_period: this.api.createType(
+        'Option<BlockNumber>',
+        openingParameters.terminateRoleStakeUnstakingPeriod
+      ),
+      exit_role_application_stake_unstaking_period: this.api.createType(
+        'Option<BlockNumber>',
+        openingParameters.exitRoleApplicationStakeUnstakingPeriod
+      ),
+      exit_role_stake_unstaking_period: this.api.createType(
+        'Option<BlockNumber>',
+        openingParameters.exitRoleStakeUnstakingPeriod
+      ),
+    })
+
     return this.sender.signAndSend(
-      this.api.tx.sudo.sudo(this.createAddOpeningTransaction(actiavteAt, commitment, text, type, module)),
-      sudo,
+      this.api.tx.sudo.sudo(
+        this.createAddOpeningTransaction(
+          activateAt,
+          commitment,
+          openingParameters.text,
+          openingParameters.type,
+          openingParameters.module
+        )
+      ),
+      openingParameters.sudo,
       false
     )
   }
 
-  public async proposeCreateWorkingGroupLeaderOpening(
-    account: KeyringPair,
-    title: string,
-    description: string,
-    proposalStake: BN,
-    actiavteAt: ActivateOpeningAt,
-    commitment: WorkingGroupOpeningPolicyCommitment,
-    text: string,
+  public async proposeCreateWorkingGroupLeaderOpening(leaderOpening: {
+    account: KeyringPair
+    title: string
+    description: string
+    proposalStake: BN
+    actiavteAt: string
+    maxActiveApplicants: BN
+    maxReviewPeriodLength: BN
+    applicationStakingPolicyAmount: BN
+    applicationCrowdedOutUnstakingPeriodLength: BN
+    applicationReviewPeriodExpiredUnstakingPeriodLength: BN
+    roleStakingPolicyAmount: BN
+    roleCrowdedOutUnstakingPeriodLength: BN
+    roleReviewPeriodExpiredUnstakingPeriodLength: BN
+    slashableMaxCount: BN
+    slashableMaxPercentPtsPerTime: BN
+    fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod: BN
+    fillOpeningFailedApplicantApplicationStakeUnstakingPeriod: BN
+    fillOpeningFailedApplicantRoleStakeUnstakingPeriod: BN
+    terminateApplicationStakeUnstakingPeriod: BN
+    terminateRoleStakeUnstakingPeriod: BN
+    exitRoleApplicationStakeUnstakingPeriod: BN
+    exitRoleStakeUnstakingPeriod: BN
+    text: string
     workingGroup: string
-  ): Promise<void> {
-    const memberId: MemberId = (await this.getMemberIds(account.address))[0]
+  }): Promise<void> {
+    const commitment: WorkingGroupOpeningPolicyCommitment = this.api.createType('WorkingGroupOpeningPolicyCommitment', {
+      application_rationing_policy: this.api.createType('Option<ApplicationRationingPolicy>', {
+        max_active_applicants: leaderOpening.maxActiveApplicants as u32,
+      }),
+      max_review_period_length: leaderOpening.maxReviewPeriodLength as u32,
+      application_staking_policy: this.api.createType('Option<StakingPolicy>', {
+        amount: leaderOpening.applicationStakingPolicyAmount,
+        amount_mode: 'AtLeast',
+        crowded_out_unstaking_period_length: leaderOpening.applicationCrowdedOutUnstakingPeriodLength,
+        review_period_expired_unstaking_period_length:
+          leaderOpening.applicationReviewPeriodExpiredUnstakingPeriodLength,
+      }),
+      role_staking_policy: this.api.createType('Option<StakingPolicy>', {
+        amount: leaderOpening.roleStakingPolicyAmount,
+        amount_mode: 'AtLeast',
+        crowded_out_unstaking_period_length: leaderOpening.roleCrowdedOutUnstakingPeriodLength,
+        review_period_expired_unstaking_period_length: leaderOpening.roleReviewPeriodExpiredUnstakingPeriodLength,
+      }),
+      role_slashing_terms: this.api.createType('SlashingTerms', {
+        Slashable: {
+          max_count: leaderOpening.slashableMaxCount,
+          max_percent_pts_per_time: leaderOpening.slashableMaxPercentPtsPerTime,
+        },
+      }),
+      fill_opening_successful_applicant_application_stake_unstaking_period: this.api.createType(
+        'Option<BlockNumber>',
+        leaderOpening.fillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriod
+      ),
+      fill_opening_failed_applicant_application_stake_unstaking_period: this.api.createType(
+        'Option<BlockNumber>',
+        leaderOpening.fillOpeningFailedApplicantApplicationStakeUnstakingPeriod
+      ),
+      fill_opening_failed_applicant_role_stake_unstaking_period: this.api.createType(
+        'Option<BlockNumber>',
+        leaderOpening.fillOpeningFailedApplicantRoleStakeUnstakingPeriod
+      ),
+      terminate_application_stake_unstaking_period: this.api.createType(
+        'Option<BlockNumber>',
+        leaderOpening.terminateApplicationStakeUnstakingPeriod
+      ),
+      terminate_role_stake_unstaking_period: this.api.createType(
+        'Option<BlockNumber>',
+        leaderOpening.terminateRoleStakeUnstakingPeriod
+      ),
+      exit_role_application_stake_unstaking_period: this.api.createType(
+        'Option<BlockNumber>',
+        leaderOpening.exitRoleApplicationStakeUnstakingPeriod
+      ),
+      exit_role_stake_unstaking_period: this.api.createType(
+        'Option<BlockNumber>',
+        leaderOpening.exitRoleStakeUnstakingPeriod
+      ),
+    })
+
+    const memberId: MemberId = (await this.getMemberIds(leaderOpening.account.address))[0]
     return this.sender.signAndSend(
       (this.api.tx.proposalsCodex.createAddWorkingGroupLeaderOpeningProposal(
         memberId,
-        title,
-        description,
-        proposalStake,
+        leaderOpening.title,
+        leaderOpening.description,
+        leaderOpening.proposalStake,
         {
-          activate_at: actiavteAt,
+          activate_at: leaderOpening.actiavteAt,
           commitment: commitment,
-          human_readable_text: text,
-          working_group: workingGroup,
+          human_readable_text: leaderOpening.text,
+          working_group: leaderOpening.workingGroup,
         }
       ) as unknown) as SubmittableExtrinsic<'promise'>,
-      account,
+      leaderOpening.account,
       false
     )
   }
 
-  public async proposeFillLeaderOpening(
-    account: KeyringPair,
-    title: string,
-    description: string,
-    proposalStake: BN,
-    fillOpeningParameters: FillOpeningParameters
-  ): Promise<void> {
-    const memberId: MemberId = (await this.getMemberIds(account.address))[0]
+  public async proposeFillLeaderOpening(fillOpening: {
+    account: KeyringPair
+    title: string
+    description: string
+    proposalStake: BN
+    openingId: OpeningId
+    successfulApplicationId: ApplicationId
+    amountPerPayout: BN
+    nextPaymentAtBlock: BN
+    payoutInterval: BN
+    workingGroup: string
+  }): Promise<void> {
+    const memberId: MemberId = (await this.getMemberIds(fillOpening.account.address))[0]
+
+    const fillOpeningParameters: FillOpeningParameters = this.api.createType('FillOpeningParameters', {
+      opening_id: fillOpening.openingId,
+      successful_application_id: fillOpening.successfulApplicationId,
+      reward_policy: this.api.createType('Option<RewardPolicy>', {
+        amount_per_payout: fillOpening.amountPerPayout as Balance,
+        next_payment_at_block: fillOpening.nextPaymentAtBlock as BlockNumber,
+        payout_interval: this.api.createType('Option<u32>', fillOpening.payoutInterval),
+      }),
+      working_group: this.api.createType('WorkingGroup', fillOpening.workingGroup),
+    })
 
     return this.sender.signAndSend(
       (this.api.tx.proposalsCodex.createFillWorkingGroupLeaderOpeningProposal(
         memberId,
-        title,
-        description,
-        proposalStake,
+        fillOpening.title,
+        fillOpening.description,
+        fillOpening.proposalStake,
         fillOpeningParameters
       ) as unknown) as SubmittableExtrinsic<'promise'>,
-      account,
+      fillOpening.account,
       false
     )
   }
@@ -1398,7 +1681,10 @@ export class ApiWrapper {
   public async batchWithdrawApplication(accounts: KeyringPair[], module: WorkingGroups): Promise<void[]> {
     return Promise.all(
       accounts.map(async (keyPair) => {
-        const applicationIds: ApplicationId[] = await this.getApplicationsIdsByRoleAccount(keyPair.address, module)
+        const applicationIds: ApplicationId[] = await this.getActiveApplicationsIdsByRoleAccount(
+          keyPair.address,
+          module
+        )
         await this.withdrawApplication(keyPair, applicationIds[0], module)
       })
     )
@@ -1506,54 +1792,68 @@ export class ApiWrapper {
   }
 
   public async getHiringOpening(id: OpeningId): Promise<HiringOpening> {
-    return ((await this.api.query.hiring.openingById<Codec[]>(id))[0] as unknown) as HiringOpening
+    return await this.api.query.hiring.openingById<HiringOpening>(id)
   }
 
   public async getWorkers(module: WorkingGroups): Promise<Worker[]> {
-    return ((await this.api.query[module].workerById<Codec[]>())[1] as unknown) as Worker[]
+    return (await this.api.query[module].workerById.entries<Worker>()).map((workerWithId) => workerWithId[1])
   }
 
   public async getWorkerById(id: WorkerId, module: WorkingGroups): Promise<Worker> {
-    return ((await this.api.query[module].workerById<Codec[]>(id))[0] as unknown) as Worker
+    return await this.api.query[module].workerById<Worker>(id)
   }
 
   public async getWorkerIdByRoleAccount(address: string, module: WorkingGroups): Promise<WorkerId> {
-    const workersAndIds = await this.api.query[module].workerById<Codec[]>()
-    const workers: Worker[] = (workersAndIds[1] as unknown) as Worker[]
-    const ids: WorkerId[] = (workersAndIds[0] as unknown) as WorkerId[]
-    const index: number = workers.findIndex((worker) => worker.role_account_id.toString() === address)
-    return ids[index]
+    const workersAndIds: [StorageKey, Worker][] = await this.api.query[module].workerById.entries<Worker>()
+    const index: number = workersAndIds.findIndex(
+      (workersAndId) => workersAndId[1].role_account_id.toString() === address
+    )
+    return workersAndIds[index][0].args[0] as WorkerId
+  }
+
+  public async isWorker(address: string, module: WorkingGroups): Promise<boolean> {
+    const workersAndIds: [StorageKey, Worker][] = await this.api.query[module].workerById.entries<Worker>()
+    const index: number = workersAndIds.findIndex(
+      (workersAndId) => workersAndId[1].role_account_id.toString() === address
+    )
+    return index !== -1
   }
 
   public async getApplicationsIdsByRoleAccount(address: string, module: WorkingGroups): Promise<ApplicationId[]> {
-    const applicationsAndIds = await this.api.query[module].applicationById<Codec[]>()
-    const applications: Application[] = (applicationsAndIds[1] as unknown) as Application[]
-    const ids: ApplicationId[] = (applicationsAndIds[0] as unknown) as ApplicationId[]
-    return applications
-      .map((application, index) => (application.role_account_id.toString() === address ? ids[index] : undefined))
+    const applicationsAndIds: [StorageKey, Application][] = await this.api.query[module].applicationById.entries<
+      Application
+    >()
+    return applicationsAndIds
+      .map((applicationWithId) => {
+        const application: Application = applicationWithId[1]
+        return application.role_account_id.toString() === address
+          ? (applicationWithId[0].args[0] as ApplicationId)
+          : undefined
+      })
       .filter((id) => id !== undefined) as ApplicationId[]
   }
 
   public async getHiringApplicationById(id: ApplicationId): Promise<HiringApplication> {
-    return ((await this.api.query.hiring.applicationById<Codec[]>(id))[0] as unknown) as HiringApplication
+    return this.api.query.hiring.applicationById<HiringApplication>(id)
   }
 
   public async getApplicationById(id: ApplicationId, module: WorkingGroups): Promise<Application> {
-    return ((await this.api.query[module].applicationById<Codec[]>(id))[0] as unknown) as Application
+    return this.api.query[module].applicationById<Application>(id)
   }
 
   public async getActiveApplicationsIdsByRoleAccount(address: string, module: WorkingGroups): Promise<ApplicationId[]> {
-    const applicationsAndIds = await this.api.query[module].applicationById<Codec[]>()
-    const applications: Application[] = (applicationsAndIds[1] as unknown) as Application[]
-    const ids: ApplicationId[] = (applicationsAndIds[0] as unknown) as ApplicationId[]
+    const applicationsAndIds: [StorageKey, Application][] = await this.api.query[module].applicationById.entries<
+      Application
+    >()
     return (
       await Promise.all(
-        applications.map(async (application, index) => {
+        applicationsAndIds.map(async (applicationWithId) => {
+          const application: Application = applicationWithId[1]
           if (
             application.role_account_id.toString() === address &&
             (await this.getHiringApplicationById(application.application_id)).stage.type === 'Active'
           ) {
-            return ids[index]
+            return applicationWithId[0].args[0] as ApplicationId
           } else {
             return undefined
           }
@@ -1563,7 +1863,7 @@ export class ApiWrapper {
   }
 
   public async getStake(id: StakeId): Promise<Stake> {
-    return ((await this.api.query.stake.stakes<Codec[]>(id))[0] as unknown) as Stake
+    return this.api.query.stake.stakes<Stake>(id)
   }
 
   public async getWorkerStakeAmount(workerId: WorkerId, module: WorkingGroups): Promise<BN> {
@@ -1572,9 +1872,7 @@ export class ApiWrapper {
   }
 
   public async getRewardRelationship(id: RewardRelationshipId): Promise<RewardRelationship> {
-    return ((
-      await this.api.query.recurringRewards.rewardRelationships<Codec[]>(id)
-    )[0] as unknown) as RewardRelationship
+    return this.api.query.recurringRewards.rewardRelationships<RewardRelationship>(id)
   }
 
   public async getWorkerRewardAccount(workerId: WorkerId, module: WorkingGroups): Promise<string> {
@@ -1587,4 +1885,12 @@ export class ApiWrapper {
   public async getLeadWorkerId(module: WorkingGroups): Promise<WorkerId | undefined> {
     return (await this.api.query[module].currentLead<Option<WorkerId>>()).unwrapOr(undefined)
   }
+
+  public async getActiveWorkersCount(module: WorkingGroups): Promise<BN> {
+    return this.api.query[module].activeWorkerCount<u32>()
+  }
+
+  public getMaxWorkersCount(module: WorkingGroups): BN {
+    return this.api.createType('u32', this.api.consts[module].maxWorkerNumberLimit)
+  }
 }

+ 13 - 10
tests/network-tests/src/iznik/utils/sender.ts

@@ -1,33 +1,36 @@
 import BN from 'bn.js'
 import { ApiPromise } from '@polkadot/api'
-import { Index } from '@polkadot/types/interfaces'
 import { SubmittableExtrinsic } from '@polkadot/api/types'
+import { AccountInfo } from '@polkadot/types/interfaces'
 import { KeyringPair } from '@polkadot/keyring/types'
+import { DbService } from '../services/dbService'
 
 export class Sender {
   private readonly api: ApiPromise
-  private static nonceMap: Map<string, BN> = new Map()
+  private db: DbService = DbService.getInstance()
 
   constructor(api: ApiPromise) {
     this.api = api
   }
 
   private async getNonce(address: string): Promise<BN> {
-    let oncahinNonce: BN = new BN(0)
-    if (!Sender.nonceMap.get(address)) {
-      oncahinNonce = await this.api.query.system.accountNonce<Index>(address)
+    const oncahinNonce: BN = (await this.api.query.system.account<AccountInfo>(address)).nonce
+    let nonce: BN
+    if (!this.db.hasNonce(address)) {
+      nonce = oncahinNonce
+    } else {
+      nonce = this.db.getNonce(address)
     }
-    let nonce: BN | undefined = Sender.nonceMap.get(address)
-    if (!nonce) {
+    if (oncahinNonce.gt(nonce)) {
       nonce = oncahinNonce
     }
     const nextNonce: BN = nonce.addn(1)
-    Sender.nonceMap.set(address, nextNonce)
+    this.db.setNonce(address, nextNonce)
     return nonce
   }
 
   private clearNonce(address: string): void {
-    Sender.nonceMap.delete(address)
+    this.db.removeNonce(address)
   }
 
   public async signAndSend(
@@ -40,7 +43,7 @@ export class Sender {
       const signedTx = tx.sign(account, { nonce })
       await signedTx
         .send(async (result) => {
-          if (result.status.isFinalized === true && result.events !== undefined) {
+          if (result.status.isInBlock && result.events !== undefined) {
             result.events.forEach((event) => {
               if (event.event.method === 'ExtrinsicFailed') {
                 if (expectFailure) {

+ 0 - 2
tests/network-tests/src/nicaea/tests/workingGroup/impl/workingGroupModule.ts

@@ -358,8 +358,6 @@ export async function updateRoleAccount(
     newRoleAccount === createdAccount.address,
     `Unexpected role account ${newRoleAccount}, expected ${createdAccount.address}`
   )
-
-  membersKeyPairs[0] = createdAccount
 }
 
 export async function terminateApplications(

+ 6 - 1
tests/network-tests/tsconfig.json

@@ -7,6 +7,11 @@
     "strict": true,
     "esModuleInterop": true,
     "forceConsistentCasingInFileNames": true,
-    "skipLibCheck": true
+    "skipLibCheck": true,
+    "baseUrl": ".",
+    "resolveJsonModule": true,
+    "paths": {
+      "@polkadot/types/augment": ["../../types/augment-codec/augment-types.ts"]
+    }
   }
 }

+ 32 - 2
yarn.lock

@@ -3464,7 +3464,7 @@
   dependencies:
     "@babel/runtime" "^7.10.5"
 
-"@polkadot/keyring@^1.7.0-beta.5", "@polkadot/keyring@^3.0.1":
+"@polkadot/keyring@3.0.1", "@polkadot/keyring@^1.7.0-beta.5", "@polkadot/keyring@^3.0.1":
   version "3.0.1"
   resolved "https://registry.yarnpkg.com/@polkadot/keyring/-/keyring-3.0.1.tgz#3944079697c15b2af81e1f57b1c4aeab703a4fef"
   integrity sha512-vAHSBnisiDYHsBbEzAgIpuwQp3vIDN2uWQ/1wAE2BrKzXCBQM7RrF3LRcLFySk0xzQoDs7AP1TlPoakxJ/C/Qw==
@@ -4564,6 +4564,13 @@
   resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.157.tgz#fdac1c52448861dfde1a2e1515dbc46e54926dc8"
   integrity sha512-Ft5BNFmv2pHDgxV5JDsndOWTRJ+56zte0ZpYLowp03tW+K+t8u8YMOzAnpuqPgzX6WO1XpDIUm7u04M8vdDiVQ==
 
+"@types/lowdb@^1.0.9":
+  version "1.0.9"
+  resolved "https://registry.yarnpkg.com/@types/lowdb/-/lowdb-1.0.9.tgz#1f6c27df72dd1c64522cc9a4566796d2dd058d38"
+  integrity sha512-LBRG5EPXFOJDoJc9jACstMhtMP+u+UkPYllBeGQXXKiaHc+uzJs9+/Aynb/5KkX33DtrIiKyzNVTPQc/4RcD6A==
+  dependencies:
+    "@types/lodash" "*"
+
 "@types/marked@^0.7.0":
   version "0.7.4"
   resolved "https://registry.yarnpkg.com/@types/marked/-/marked-0.7.4.tgz#607685669bb1bbde2300bc58ba43486cbbee1f0a"
@@ -12976,7 +12983,7 @@ graceful-fs@^4.0.0, graceful-fs@^4.1.11, graceful-fs@^4.1.15, graceful-fs@^4.1.2
   resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.3.tgz#4a12ff1b60376ef09862c2093edd908328be8423"
   integrity sha512-a30VEBm4PEdx1dRB7MFK7BejejvCvBronbLjht+sHuGYj8PHs7M/5Z+rt5lw551vZ7yfTCj4Vuyy3mSJytDWRQ==
 
-graceful-fs@^4.2.2, graceful-fs@^4.2.4:
+graceful-fs@^4.1.3, graceful-fs@^4.2.2, graceful-fs@^4.2.4:
   version "4.2.4"
   resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.4.tgz#2256bde14d3632958c465ebc96dc467ca07a29fb"
   integrity sha512-WjKPNJF79dtJAVniUlGGWHYGz2jWxT6VhN/4m1NdkbZ2nOsEF+cI1Edgql5zCRhs/VsQYRvrXctxktVXZUkixw==
@@ -17029,6 +17036,11 @@ lodash.zip@^4.2.0:
   resolved "https://registry.yarnpkg.com/lodash.zip/-/lodash.zip-4.2.0.tgz#ec6662e4896408ed4ab6c542a3990b72cc080020"
   integrity sha1-7GZi5IlkCO1KtsVCo5kLcswIACA=
 
+lodash@4:
+  version "4.17.20"
+  resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.20.tgz#b44a9b6297bcb698f1c51a3545a2b3b368d59c52"
+  integrity sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA==
+
 lodash@^4.0.0, lodash@^4.0.1, lodash@^4.17.10, lodash@^4.17.19, lodash@^4.17.3, lodash@^4.17.5, lodash@^4.2.1, lodash@~4.17.10:
   version "4.17.19"
   resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.19.tgz#e48ddedbe30b3321783c5b4301fbd353bc1e4a4b"
@@ -17126,6 +17138,17 @@ loud-rejection@^1.0.0:
     currently-unhandled "^0.4.1"
     signal-exit "^3.0.0"
 
+lowdb@^1.0.0:
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/lowdb/-/lowdb-1.0.0.tgz#5243be6b22786ccce30e50c9a33eac36b20c8064"
+  integrity sha512-2+x8esE/Wb9SQ1F9IHaYWfsC9FIecLOPrK4g17FGEayjUWH172H6nwicRovGvSE2CPZouc2MCIqCI7h9d+GftQ==
+  dependencies:
+    graceful-fs "^4.1.3"
+    is-promise "^2.1.0"
+    lodash "4"
+    pify "^3.0.0"
+    steno "^0.4.1"
+
 lower-case@^1.1.1:
   version "1.1.4"
   resolved "https://registry.yarnpkg.com/lower-case/-/lower-case-1.1.4.tgz#9a2cabd1b9e8e0ae993a4bf7d5875c39c42e8eac"
@@ -23678,6 +23701,13 @@ stealthy-require@^1.1.1:
   resolved "https://registry.yarnpkg.com/stealthy-require/-/stealthy-require-1.1.1.tgz#35b09875b4ff49f26a777e509b3090a3226bf24b"
   integrity sha1-NbCYdbT/SfJqd35QmzCQoyJr8ks=
 
+steno@^0.4.1:
+  version "0.4.4"
+  resolved "https://registry.yarnpkg.com/steno/-/steno-0.4.4.tgz#071105bdfc286e6615c0403c27e9d7b5dcb855cb"
+  integrity sha1-BxEFvfwobmYVwEA8J+nXtdy4Vcs=
+  dependencies:
+    graceful-fs "^4.1.3"
+
 store2@^2.7.1:
   version "2.11.2"
   resolved "https://registry.yarnpkg.com/store2/-/store2-2.11.2.tgz#a298e5e97b21b3ce7419b732540bc7c79cb007db"

この差分においてかなりの量のファイルが変更されているため、一部のファイルを表示していません