Эх сурвалжийг харах

Merge pull request #1069 from Joystream/nicaea

Update Iznik with latest from Nicaea
Martin 4 жил өмнө
parent
commit
32d6859221
100 өөрчлөгдсөн 3585 нэмэгдсэн , 1230 устгасан
  1. 0 2
      .github/workflows/joystream-cli.yml
  2. 49 0
      .github/workflows/joystream-types.yml
  3. 37 0
      .github/workflows/network-tests.yml
  4. 0 4
      .github/workflows/pioneer.yml
  5. 37 0
      .github/workflows/storage-node.yml
  6. 12 0
      .travis.yml
  7. 9 9
      Cargo.lock
  8. 675 0
      LICENSE
  9. 70 98
      README.md
  10. 3 2
      cli/package.json
  11. 3 3
      cli/src/base/ApiCommandBase.ts
  12. 31 7
      devops/eslint-config/index.js
  13. 1 0
      devops/prettier-config/index.js
  14. 10 0
      devops/vscode/settings.json
  15. 1 1
      node/Cargo.toml
  16. 98 0
      node/README.md
  17. 4 3
      node/src/chain_spec.rs
  18. 1 0
      node/src/lib.rs
  19. 17 0
      node/src/proposals_config.rs
  20. 4 0
      package.json
  21. 3 3
      pioneer/package.json
  22. 8 1
      pioneer/packages/app-js/src/Playground.tsx
  23. 2 2
      pioneer/packages/joy-election/src/Applicant.tsx
  24. 2 2
      pioneer/packages/joy-election/src/ApplyForm.tsx
  25. 206 89
      pioneer/packages/joy-proposals/src/Proposal/Body.tsx
  26. 2 12
      pioneer/packages/joy-proposals/src/Proposal/ChooseProposalType.tsx
  27. 5 3
      pioneer/packages/joy-proposals/src/Proposal/Details.tsx
  28. 2 1
      pioneer/packages/joy-proposals/src/Proposal/ProposalFromId.tsx
  29. 1 2
      pioneer/packages/joy-proposals/src/Proposal/ProposalTypePreview.tsx
  30. 10 5
      pioneer/packages/joy-proposals/src/forms/AddWorkingGroupOpeningForm.tsx
  31. 118 0
      pioneer/packages/joy-proposals/src/forms/BeginReviewLeaderApplicationsForm.tsx
  32. 102 0
      pioneer/packages/joy-proposals/src/forms/DecreaseWorkingGroupLeadStakeForm.tsx
  33. 0 88
      pioneer/packages/joy-proposals/src/forms/EvictStorageProviderForm.tsx
  34. 232 0
      pioneer/packages/joy-proposals/src/forms/FillWorkingGroupLeaderOpeningForm.tsx
  35. 82 11
      pioneer/packages/joy-proposals/src/forms/FormFields.tsx
  36. 5 6
      pioneer/packages/joy-proposals/src/forms/GenericProposalForm.tsx
  37. 47 14
      pioneer/packages/joy-proposals/src/forms/GenericWorkingGroupProposalForm.tsx
  38. 2 2
      pioneer/packages/joy-proposals/src/forms/MintCapacityForm.tsx
  39. 2 2
      pioneer/packages/joy-proposals/src/forms/RuntimeUpgradeForm.tsx
  40. 4 3
      pioneer/packages/joy-proposals/src/forms/SetContentWorkingGroupLeadForm.tsx
  41. 2 9
      pioneer/packages/joy-proposals/src/forms/SetCouncilParamsForm.tsx
  42. 3 3
      pioneer/packages/joy-proposals/src/forms/SetMaxValidatorCountForm.tsx
  43. 0 256
      pioneer/packages/joy-proposals/src/forms/SetStorageRoleParamsForm.tsx
  44. 93 0
      pioneer/packages/joy-proposals/src/forms/SetWorkingGroupLeadRewardForm.tsx
  45. 86 0
      pioneer/packages/joy-proposals/src/forms/SetWorkingGroupMintCapacityForm.tsx
  46. 2 2
      pioneer/packages/joy-proposals/src/forms/SignalForm.tsx
  47. 101 0
      pioneer/packages/joy-proposals/src/forms/SlashWorkingGroupLeadStakeForm.tsx
  48. 2 3
      pioneer/packages/joy-proposals/src/forms/SpendingProposalForm.tsx
  49. 125 0
      pioneer/packages/joy-proposals/src/forms/TerminateWorkingGroupLeaderForm.tsx
  50. 4 4
      pioneer/packages/joy-proposals/src/forms/errorHandling.ts
  51. 7 2
      pioneer/packages/joy-proposals/src/forms/index.ts
  52. 25 5
      pioneer/packages/joy-proposals/src/index.tsx
  53. 0 6
      pioneer/packages/joy-proposals/src/stories/ProposalForms.stories.tsx
  54. 3 3
      pioneer/packages/joy-proposals/src/stories/data/ProposalTypesInfo.mock.ts
  55. 163 185
      pioneer/packages/joy-proposals/src/validationSchema.ts
  56. 19 20
      pioneer/packages/joy-roles/src/classifiers.ts
  57. 18 8
      pioneer/packages/joy-utils/src/MemberProfilePreview.tsx
  58. 99 14
      pioneer/packages/joy-utils/src/consts/proposals.ts
  59. 2 2
      pioneer/packages/joy-utils/src/consts/workingGroups.ts
  60. 22 0
      pioneer/packages/joy-utils/src/functions/format.ts
  61. 3 3
      pioneer/packages/joy-utils/src/index.ts
  62. 102 0
      pioneer/packages/joy-utils/src/react/components/working-groups/ApplicationDetails.tsx
  63. 56 0
      pioneer/packages/joy-utils/src/react/components/working-groups/LeadInfo.tsx
  64. 4 3
      pioneer/packages/joy-utils/src/react/context/transport.tsx
  65. 22 3
      pioneer/packages/joy-utils/src/react/hooks/usePromise.tsx
  66. 25 10
      pioneer/packages/joy-utils/src/transport/base.ts
  67. 3 2
      pioneer/packages/joy-utils/src/transport/contentWorkingGroup.ts
  68. 4 3
      pioneer/packages/joy-utils/src/transport/council.ts
  69. 11 8
      pioneer/packages/joy-utils/src/transport/index.ts
  70. 59 27
      pioneer/packages/joy-utils/src/transport/proposals.ts
  71. 144 18
      pioneer/packages/joy-utils/src/transport/workingGroups.ts
  72. 10 2
      pioneer/packages/joy-utils/src/types/proposals.ts
  73. 29 2
      pioneer/packages/joy-utils/src/types/workingGroups.ts
  74. 2 2
      runtime-modules/hiring/Cargo.toml
  75. 2 4
      runtime-modules/proposals/codex/src/lib.rs
  76. 41 0
      runtime-modules/proposals/codex/src/proposal_types/mod.rs
  77. 65 1
      runtime-modules/proposals/codex/src/tests/mod.rs
  78. 1 1
      runtime-modules/proposals/engine/Cargo.toml
  79. 1 1
      runtime/Cargo.toml
  80. 26 0
      runtime/README.md
  81. 1 1
      runtime/src/lib.rs
  82. 2 1
      runtime/src/migration.rs
  83. 2 1
      scripts/create-test-chainspec.sh
  84. 1 0
      storage-node/.eslintrc.js
  85. 3 3
      storage-node/package.json
  86. 3 3
      storage-node/packages/cli/package.json
  87. 6 1
      storage-node/packages/cli/src/cli.ts
  88. 4 4
      storage-node/packages/cli/src/commands/dev.ts
  89. 35 10
      storage-node/packages/colossus/bin/cli.js
  90. 1 1
      storage-node/packages/colossus/lib/sync.js
  91. 1 1
      storage-node/packages/colossus/package.json
  92. 1 1
      storage-node/packages/colossus/paths/asset/v0/{id}.js
  93. 1 1
      storage-node/packages/discovery/package.json
  94. 10 25
      storage-node/packages/runtime-api/assets.js
  95. 4 3
      storage-node/packages/runtime-api/identities.js
  96. 211 174
      storage-node/packages/runtime-api/index.js
  97. 2 2
      storage-node/packages/runtime-api/package.json
  98. 12 9
      storage-node/packages/runtime-api/workers.js
  99. 1 1
      storage-node/packages/storage/package.json
  100. 1 1
      storage-node/packages/util/package.json

+ 0 - 2
.github/workflows/joystream-cli.yml

@@ -17,7 +17,6 @@ jobs:
     - name: checks
       run: |
         yarn install --frozen-lockfile
-        yarn madge --circular types/
         yarn workspace joystream-cli checks
 
   cli_build_osx:
@@ -35,5 +34,4 @@ jobs:
     - name: checks
       run: |
         yarn install --frozen-lockfile --network-timeout 120000
-        yarn madge --circular types/
         yarn workspace joystream-cli checks

+ 49 - 0
.github/workflows/joystream-types.yml

@@ -0,0 +1,49 @@
+name: joystream-types
+on: [pull_request, push]
+
+jobs:
+  types_checks_ubuntu:
+    name: Ubuntu Checks
+    runs-on: ubuntu-latest
+    strategy:
+      matrix:
+        node-version: [12.x]
+    steps:
+    - uses: actions/checkout@v1
+    - name: Use Node.js ${{ matrix.node-version }}
+      uses: actions/setup-node@v1
+      with:
+        node-version: ${{ matrix.node-version }}
+    - name: checks
+      run: |
+        yarn install --frozen-lockfile
+        yarn workspace @joystream/types checks
+    - name: npm pack test
+      run: |
+        cd types
+        npm pack | tail -1 | xargs tar xzf
+        cd package && npm install
+        node ./index.js
+
+  types_checks_osx:
+    name: MacOS Checks
+    runs-on: macos-latest
+    strategy:
+      matrix:
+        node-version: [12.x]
+    steps:
+    - uses: actions/checkout@v1
+    - name: Use Node.js ${{ matrix.node-version }}
+      uses: actions/setup-node@v1
+      with:
+        node-version: ${{ matrix.node-version }}
+    - name: checks
+      run: |
+        yarn install --frozen-lockfile --network-timeout 120000
+        yarn workspace @joystream/types checks
+    - name: npm pack test
+      run: |
+        cd types
+        npm pack | tail -1 | xargs tar xzf
+        cd package && npm install
+        node ./index.js

+ 37 - 0
.github/workflows/network-tests.yml

@@ -0,0 +1,37 @@
+name: network-tests
+on: [pull_request, push]
+
+jobs:
+  network_build_ubuntu:
+    name: Ubuntu Checks
+    runs-on: ubuntu-latest
+    strategy:
+      matrix:
+        node-version: [12.x]
+    steps:
+    - uses: actions/checkout@v1
+    - name: Use Node.js ${{ matrix.node-version }}
+      uses: actions/setup-node@v1
+      with:
+        node-version: ${{ matrix.node-version }}
+    - name: checks
+      run: |
+        yarn install --frozen-lockfile
+        yarn workspace joystream-testing checks
+
+  network_build_osx:
+    name: MacOS Checks
+    runs-on: macos-latest
+    strategy:
+      matrix:
+        node-version: [12.x]
+    steps:
+    - uses: actions/checkout@v1
+    - name: Use Node.js ${{ matrix.node-version }}
+      uses: actions/setup-node@v1
+      with:
+        node-version: ${{ matrix.node-version }}
+    - name: checks
+      run: |
+        yarn install --frozen-lockfile --network-timeout 120000
+        yarn workspace joystream-testing checks

+ 0 - 4
.github/workflows/pioneer.yml

@@ -17,7 +17,6 @@ jobs:
     - name: build
       run: |
         yarn install --frozen-lockfile
-        yarn madge --circular types/
         yarn workspace pioneer build
 
   pioneer_build_osx:
@@ -35,7 +34,6 @@ jobs:
     - name: build
       run: |
         yarn install --frozen-lockfile --network-timeout 120000
-        yarn madge --circular types/
         yarn workspace pioneer build
 
   pioneer_lint_ubuntu:
@@ -53,7 +51,6 @@ jobs:
     - name: lint
       run: |
         yarn install --frozen-lockfile
-        yarn madge --circular types/
         yarn workspace pioneer lint
 
   pioneer_lint_osx:
@@ -71,5 +68,4 @@ jobs:
     - name: lint
       run: |
         yarn install --frozen-lockfile --network-timeout 120000
-        yarn madge --circular types/
         yarn workspace pioneer lint

+ 37 - 0
.github/workflows/storage-node.yml

@@ -0,0 +1,37 @@
+name: storage-node
+on: [pull_request, push]
+
+jobs:
+  storage_node_build_ubuntu:
+    name: Ubuntu Checks
+    runs-on: ubuntu-latest
+    strategy:
+      matrix:
+        node-version: [12.x]
+    steps:
+    - uses: actions/checkout@v1
+    - name: Use Node.js ${{ matrix.node-version }}
+      uses: actions/setup-node@v1
+      with:
+        node-version: ${{ matrix.node-version }}
+    - name: checks
+      run: |
+        yarn install --frozen-lockfile
+        yarn workspace storage-node checks
+
+  storage_node_build_osx:
+    name: MacOS Checks
+    runs-on: macos-latest
+    strategy:
+      matrix:
+        node-version: [12.x]
+    steps:
+    - uses: actions/checkout@v1
+    - name: Use Node.js ${{ matrix.node-version }}
+      uses: actions/setup-node@v1
+      with:
+        node-version: ${{ matrix.node-version }}
+    - name: checks
+      run: |
+        yarn install --frozen-lockfile --network-timeout 120000
+        yarn workspace storage-node checks

+ 12 - 0
.travis.yml

@@ -17,6 +17,18 @@ matrix:
     - os: linux
       env: TARGET=x86_64-unknown-linux-gnu
 
+# Skip Rust build in a pull request if no rust project files were modified
+before_install:
+  - |
+    if [ "$TRAVIS_PULL_REQUEST" != "false" ]
+      then
+      if ! git diff --name-only $TRAVIS_COMMIT_RANGE | grep -qE "(.rs|Cargo.(lock|toml))$"
+        then
+        echo "No changes to Rust or Cargo Files, CI not running."
+        travis_terminate 0
+      fi
+    fi
+
 install:
   - rustup install nightly-2020-05-23
   - rustup target add wasm32-unknown-unknown --toolchain nightly-2020-05-23

+ 9 - 9
Cargo.lock

@@ -390,7 +390,7 @@ checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"
 
 [[package]]
 name = "chain-spec-builder"
-version = "2.0.0-alpha.3"
+version = "2.1.0"
 dependencies = [
  "ansi_term 0.12.1",
  "joystream-node",
@@ -918,9 +918,9 @@ dependencies = [
 
 [[package]]
 name = "fragile"
-version = "0.3.0"
+version = "1.0.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "05f8140122fa0d5dcb9fc8627cfce2b37cc1500f752636d46ea28bc26785c2f9"
+checksum = "69a039c3498dc930fe810151a34ba0c1c70b02b8625035592e74432f678591f2"
 
 [[package]]
 name = "fs-swap"
@@ -1569,7 +1569,7 @@ dependencies = [
 
 [[package]]
 name = "joystream-node"
-version = "2.6.0"
+version = "2.7.0"
 dependencies = [
  "ctrlc",
  "derive_more 0.14.1",
@@ -1614,7 +1614,7 @@ dependencies = [
 
 [[package]]
 name = "joystream-node-runtime"
-version = "6.20.0"
+version = "6.21.0"
 dependencies = [
  "parity-scale-codec",
  "safe-mix",
@@ -2502,9 +2502,9 @@ dependencies = [
 
 [[package]]
 name = "mockall"
-version = "0.6.0"
+version = "0.7.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b95a7e7cfbce0e99ebbf5356a085d3b5e320a7ef300f77cd50a7148aa362e7c2"
+checksum = "256489d4d106cd2bc9e98ed0337402db0044de0621745d5d9eb70a14295ff77b"
 dependencies = [
  "cfg-if",
  "downcast",
@@ -2517,9 +2517,9 @@ dependencies = [
 
 [[package]]
 name = "mockall_derive"
-version = "0.6.0"
+version = "0.7.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d5a615a1ad92048ad5d9633251edb7492b8abc057d7a679a9898476aef173935"
+checksum = "826e14e8643cb12103b56efb963e5f9640b69b0f7bdcc460002092df4b0e959f"
 dependencies = [
  "cfg-if",
  "proc-macro2 1.0.10",

+ 675 - 0
LICENSE

@@ -0,0 +1,675 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<https://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<https://www.gnu.org/licenses/why-not-lgpl.html>.
+

+ 70 - 98
README.md

@@ -1,164 +1,136 @@
 # Joystream [![Build Status](https://travis-ci.org/Joystream/joystream.svg?branch=master)](https://travis-ci.org/Joystream/joystream)
 
-This is the main code reposity for all joystream software. It will  house the substrate chain project, the full node and runtime and all reusable substrate runtime modules that make up the joystream runtime. In addition to all front-end apps and infrastructure servers necessary for operating the network.
-
-The repository is currently just a cargo workspace, but eventually will also contain yarn workspaces, and possibly other project type workspaces.
-
-## Build Status
-
-Development [![Development Branch Build Status](https://travis-ci.org/Joystream/joystream.svg?branch=development)](https://travis-ci.org/Joystream/joystream)
-
-More detailed build history on [Travis CI](https://travis-ci.org/github/Joystream/joystream/builds)
+This is the main code repository for all Joystream software. In this mono-repo you will find all the software required to run a Joystream network: The Joystream full node, runtime and all reusable substrate runtime modules that make up the Joystream runtime. In addition to all front-end apps and infrastructure servers necessary for operating the network.
 
 ## Overview
 
 The Joystream network builds on a pre-release version of [substrate v2.0](https://substrate.dev/) and adds additional
 functionality to support the [various roles](https://www.joystream.org/roles) that can be entered into on the platform.
 
+## Build Status
 
-## Validator
-![ Nodes for Joystream](./node/validator-node-banner.svg)
-
-Joystream node is the main server application that connects to the network, synchronizes the blockchain with other nodes and produces blocks if configured as a validator node.
-
-To setup a full node and validator review the [advanced guide from the helpdesk](https://github.com/Joystream/helpdesk/tree/master/roles/validators).
-
-
-###  Pre-built Binaries
-
-The latest pre-built binaries can be downloaded from the [releases](https://github.com/Joystream/joystream/releases) page.
+Development [![Development Branch Build Status](https://travis-ci.org/Joystream/joystream.svg?branch=development)](https://travis-ci.org/Joystream/joystream) - build history on [Travis](https://travis-ci.org/github/Joystream/joystream/builds)
 
+## Development Tools
 
-### Building from source
+The following tools are required for building, testing and contributing to this repo:
 
-Clone the repository and install build tools:
+- [Rust](https://www.rust-lang.org/tools/install) toolchain - _required_
+- [nodejs](https://nodejs.org/) v12.x - _required_
+- [yarn classic](https://classic.yarnpkg.com/en/docs/install) package manager v1.22.x- _required_
+- [docker](https://www.docker.com/get-started) - _optional_
+- [ansible](https://www.ansible.com/) - _optional_
 
-```bash
-git clone https://github.com/Joystream/joystream.git
+If you use VSCode as your code editor we recommend using the workspace [settings](devops/vscode/settings.json) for recommend eslint plugin to function properly.
 
-cd joystream/
+After cloning the repo run the following initialization scripts:
 
+```sh
+# Install rust toolchain
 ./setup.sh
-```
 
-### Building
+# Install npm package dependencies
+# Also good habit to run this when switching between branches
+yarn install
 
-```bash
-cargo build --release
+# run some tests
+yarn cargo-checks
 ```
 
-### Running a public node on the Rome testnet
+## Software
 
-Run the node and connect to the public testnet.
+**Substrate blockchain**
 
-```bash
-cargo run --release -- --chain ./rome-testnet.json
-```
+- [joystream-node](./node)
+- [runtime](./runtime)
+- [runtime modules](./runtime-modules)
 
-The `rome-testnet.json` chain file can be obtained from the [releases page](https://github.com/Joystream/joystream/releases/tag/v6.8.0)
+**Server Applications - infrastructure**
 
+- [Storage Node](./storage-node) - Media Storage Infrastructure
+- [Query Node](https://github.com/Joystream/joystream/tree/query_node/query-node) - _under development_
+- [Discovery Node](https://github.com/Joystream/joystream/tree/init_discovery_node/discovery_node) - _under development_
 
-### Installing a release build
-This will install the executable `joystream-node` to your `~/.cargo/bin` folder, which you would normally have in your `$PATH` environment.
+**Front-end Applications**
 
-```bash
-cargo install joystream-node --path node/
-```
+- [Pioneer](./pioneer) - Main UI for accessing all Joystream features
+- [Atlas](https://github.com/Joystream/joystream/tree/init_atlas/atlas) - Media Player- _under development_
 
-Now you can run
+**Tools and CLI**
 
-```bash
-joystream-node --chain ./rome-testnet.json
-```
+- [joystream-cli](./cli) - CLI for community and governance activities
 
-### Local development
+**Testing infrastructure**
 
-This will build and run a fresh new local development chain purging existing one:
+- [Network integration](./tests/network-tests) - Joystream network integration testing framework
 
-```bash
-./scripts/run-dev-chain.sh
-```
+## Exploring the network with Pioneer
 
-### Unit tests
+Pioneer is currently the main web interface to interact with the network:
 
-```bash
-cargo test
-```
+Currently hosted on: https://testnet.joystream.org
 
-### Network tests
+You may have to disable some privacy/ad-blocker extensions in your browser for proper functionality, especially when browsing media.
 
-```bash
-./scripts/run-test-chain.sh
-yarn test
-```
+You can also run a local development instance:
 
-To run the integration tests with a different chain, you can omit step running the local development chain and set the node URL using `NODE_URL` environment variable.
-Proposal grace periods should be set to 0, otherwise proposal network tests will fail.
+The HEAD of the master branch should always be used for the correct version of the applications to connect to the current testnet:
 
-### Rome-Constantinople migration network test
-
-Ensure Rome node is up and running, and node URL is set using `NODE_URL` environment variable (default value is `localhost:9944`).
-
-```bash
-yarn test-migration
+```sh
+git checkout master
+yarn install
+yarn workspace pioneer start
 ```
 
-## Joystream Runtime
-
-![Joystream Runtime](./runtime/runtime-banner.svg)
+This runs a local development web server on port 3000.
 
+Use the link below to browse the network using the publicly hosted endpoint:
+http://localhost:3000/?rpc=wss://rome-rpc-endpoint.joystream.org:9944/
 
-The runtime is the code that defines the consensus rules of the Joystream protocol.
-It is compiled to WASM and lives on chain.
-Joystream node execute the code's logic to validate transactions and blocks on the blockchain.
+## Running a local full node
 
-When building joystream-node as described abot with `cargo build --release`, in addition to the joystream-node binary being built the WASM blob artifact is produced in:
+You can also run your our own joystream-node:
 
-`target/release/wbuild/joystream-node-runtime/joystream_node_runtime.compact.wasm`
+```sh
+git checkout master
+cargo build --release
+cargo run --release -- --pruning archive --chain testnets/rome.json
+```
 
+Wait for the node to sync to the latest block, then change pioneer settings "remote node" option to "Local Node", or follow the link below:
 
-### Deployment
+http://localhost:3000/?rpc=ws://localhost:9944/
 
-Deploying the compiled runtime on a live system can be done in one of two ways:
+Learn more about [joystream-node](node/README.md).
 
-1. Joystream runtime upgrade proposals which will be voted on by the council. When the Joystream platform is live, this will be the only way to upgrade the chain's runtime code.
+A step by step guide to setup a full node and validator on the Joystream testnet, can be found [here](https://github.com/Joystream/helpdesk/tree/master/roles/validators).
 
-2. During development and testnet phases, we can send an extrinsic (transaction signed with the sudo key) invoking `system::setCode()`. This can be done either from the UI/extrinsics app, or directly with an admin script.
+### Contributing
 
-### Versioning the runtime
+We have lots of good first [issues](https://github.com/Joystream/joystream/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) open to help you get started on contributing code. If you are not a developer you can still make valuable contributions by testing our software and providing feedback and opening new issues.
 
-Versioning of the runtime is set in `runtime/src/lib.rs`
-For detailed information about how to set correct version numbers when developing a new runtime, [see this](https://github.com/Joystream/joystream/issues/1)
+A description of our [branching model](https://github.com/Joystream/joystream/issues/638) will help you to understand where work on different software components happens, and consequently where to direct your pull requests.
 
+We rely on `eslint` for code quality of our JavaScript and TypeScript code and `prettier` for consistent formatting. For Rust we rely on `rustfmt` and `clippy`.
 
-## Coding style
+The [husky](https://www.npmjs.com/package/husky#ci-servers) npm package is used to manage the project git-hooks. This is automatically installed and setup when you run `yarn install`.
 
-We use `cargo-fmt` to format the source code for consistency.
+When you `git commit` and `git push` some scripts will run automatically to ensure committed code passes lint, tests, and code-style checks.
 
-It should be available on your machine if you ran the `setup.sh` script, otherwise install it with rustup:
+During a rebase/merge you may want to skip all hooks, you can use `HUSKY_SKIP_HOOKS` environment variable.
 
-```bash
-rustup component add rustfmt
 ```
-
-Applying code formatting on all source files recursing subfolders:
-
+HUSKY_SKIP_HOOKS=1 git rebase ...
 ```
-cargo-fmt
-```
-
-## Contributing
-
-Please see our [contributing guidlines](./CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us.
 
 ## Authors
 
-See also the list of [CONTRIBUTORS](https://github.com/Joystream/joystream/graphs/contributors) who participated in this project.
+See the list of [contributors](https://github.com/Joystream/joystream/graphs/contributors) who participated in this project.
 
 ## License
 
-This project is licensed under the GPLv3 License - see the [LICENSE](./LICENSE) file for details
+All software under this project is licensed as [GPLv3](./LICENSE) unless otherwise indicated.
 
 ## Acknowledgments
 
-Thanks to the whole [Parity Tech](https://www.parity.io/) team for making substrate and helping on riot chat with tips, suggestions, tutorials and answering all our questions during development.
+Thanks to the whole [Parity Tech](https://www.parity.io/) team for making substrate and helping in chat with tips, suggestions, tutorials and answering all our questions during development.

+ 3 - 2
cli/package.json

@@ -8,7 +8,7 @@
   },
   "bugs": "https://github.com/Joystream/substrate-runtime-joystream/issues",
   "dependencies": {
-    "@joystream/types": "^0.11.0",
+    "@joystream/types": "^0.12.0",
     "@oclif/command": "^1.5.19",
     "@oclif/config": "^1.14.0",
     "@oclif/plugin-help": "^2.2.3",
@@ -42,7 +42,8 @@
     "typescript": "^3.8.3"
   },
   "engines": {
-    "node": ">=8.0.0"
+    "node": ">=12.18.0",
+    "yarn": "^1.22.0"
   },
   "files": [
     "/bin",

+ 3 - 3
cli/src/base/ApiCommandBase.ts

@@ -249,16 +249,16 @@ export default abstract class ApiCommandBase extends StateAwareCommandBase {
   }
 
   async promptForJsonBytes(
-    JsonStruct: Constructor<Struct>,
+    jsonStruct: Constructor<Struct>,
     argName?: string,
     defaultValue?: Bytes,
     schemaValidator?: ajv.ValidateFunction
   ) {
-    const rawType = new JsonStruct().toRawType()
+    const rawType = new jsonStruct().toRawType()
     const typeDef = getTypeDef(rawType)
 
     const defaultStruct =
-      defaultValue && new JsonStruct(JSON.parse(Buffer.from(defaultValue.toHex().replace('0x', ''), 'hex').toString()))
+      defaultValue && new jsonStruct(JSON.parse(Buffer.from(defaultValue.toHex().replace('0x', ''), 'hex').toString()))
 
     if (argName) {
       typeDef.name = argName

+ 31 - 7
devops/eslint-config/index.js

@@ -43,12 +43,36 @@ module.exports = {
     // should prefer using 'debug' package at least to allow control of
     // output verbosity if logging to console.
     'no-console': 'off',
+    '@typescript-eslint/camelcase': 'off',
+    '@typescript-eslint/class-name-casing': 'off',
+    "@typescript-eslint/naming-convention": [
+      "error",
+      {
+        selector: 'default',
+        format: ['camelCase'],
+      },
+      {
+        selector: 'variable',
+        format: ['camelCase', 'UPPER_CASE', 'PascalCase'],
+      },
+      {
+        selector: 'property',
+        format: [] // Don't force format of object properties, so they can be ie.: { "Some thing": 123 }, { some_thing: 123 } etc.
+      },
+      {
+        selector: 'accessor',
+        format: ['camelCase', 'snake_case']
+      },
+      {
+        selector: 'enumMember',
+        format: ['PascalCase']
+      },
+      {
+        selector: 'typeLike',
+        format: [],
+        custom: { regex: '^([A-Z][a-z0-9]*_?)+', match: true }, // combined PascalCase and snake_case to allow ie. OpeningType_Worker
+      }
+    ],
   },
-  plugins: [
-    'standard',
-    '@typescript-eslint',
-    'react',
-    'react-hooks',
-    'prettier',
-  ],
+  plugins: ['standard', '@typescript-eslint', 'react', 'react-hooks', 'prettier'],
 }

+ 1 - 0
devops/prettier-config/index.js

@@ -5,4 +5,5 @@ module.exports = {
   tabWidth: 2,
   semi: false,
   trailingComma: 'es5',
+  quoteProps: 'preserve'
 }

+ 10 - 0
devops/vscode/settings.json

@@ -0,0 +1,10 @@
+{
+  "eslint.workingDirectories": [
+    "./cli",
+    "./pioneer",
+    "./tests/network-tests",
+    "./types",
+    "./storage-node",
+    "./atlas"
+  ]
+}

+ 1 - 1
node/Cargo.toml

@@ -3,7 +3,7 @@ authors = ['Joystream']
 build = 'build.rs'
 edition = '2018'
 name = 'joystream-node'
-version = '2.6.0'
+version = '2.7.0'
 default-run = "joystream-node"
 
 [[bin]]

+ 98 - 0
node/README.md

@@ -0,0 +1,98 @@
+## Joystream-Node - full node/validator
+
+![ Nodes for Joystream](./validator-node-banner.svg)
+
+The joystream-node is the main server application that connects to the network, synchronizes the blockchain with other nodes and produces blocks if configured as a validator node.
+
+A step by step guide to setup a full node and validator on the Joystream testnet, can be found [here](https://github.com/Joystream/helpdesk/tree/master/roles/validators).
+
+### Pre-built binaries
+
+The latest pre-built binaries can be downloaded from the [releases](https://github.com/Joystream/joystream/releases) page.
+Generally these will be built from `master` branch and will pertain to the currently active testnet.
+
+### Building from source
+
+Clone the repository and install build tools:
+
+```bash
+git clone https://github.com/Joystream/joystream.git
+
+cd joystream/
+
+./setup.sh
+```
+
+Compile the node and runtime:
+
+```bash
+cargo build --release
+```
+
+This produces the binary in `./target/release/joystream-node`
+
+### Running local development chain
+
+```bash
+cargo run --release -- --dev
+```
+
+If you repeatedly need to restart a new chain,
+this script will build and run a fresh new local development chain (purging existing chain data):
+
+```bash
+./scripts/run-dev-chain.sh
+```
+
+### Joystream Public Testnets
+
+Use the `--chain` argument, and specify the path to the genesis `chain.json` file for that public network. The JSON "chain spec" files for Joystream public networks can be found in [../testnets/](../testnets/).
+
+```bash
+cargo run --release -- --chain testnets/rome.json
+```
+
+### Tests and code quality
+
+Running unit tests:
+
+```bash
+cargo test --all
+```
+
+Running full suite of checks, tests, formatting and linting:
+
+```bash
+yarn cargo-checks
+```
+
+Always format your rust code with `cargo fmt` before committing:
+
+```bash
+cargo fmt --all
+```
+
+### Integration tests
+
+```bash
+./scripts/run-test-chain.sh
+yarn workspace joystream-testing test
+```
+
+To run the integration tests with a different chain, you can omit the step of running the local development chain and simply set the node URL using `NODE_URL` environment variable.
+
+### Installing a release build
+
+If you are building a tagged release from `master` branch and want to install the executable to your path follow the step below.
+
+This will install the executable `joystream-node` to your `~/.cargo/bin` folder, which you would normally have in your `$PATH` environment.
+
+```bash
+cargo install joystream-node --path node/
+```
+
+Now you can run and connect to the Rome testnet:
+
+```bash
+joystream-node --chain testnets/rome.json
+```

+ 4 - 3
node/src/chain_spec.rs

@@ -108,6 +108,7 @@ impl Alternative {
                             get_account_id_from_seed::<sr25519::Public>("Alice//stash"),
                             get_account_id_from_seed::<sr25519::Public>("Bob//stash"),
                         ],
+                        crate::proposals_config::development(),
                     )
                 },
                 vec![],
@@ -140,6 +141,7 @@ impl Alternative {
                             get_account_id_from_seed::<sr25519::Public>("Eve//stash"),
                             get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),
                         ],
+                        crate::proposals_config::development(),
                     )
                 },
                 vec![],
@@ -181,14 +183,13 @@ pub fn testnet_genesis(
     initial_authorities: Vec<(AccountId, AccountId, GrandpaId, BabeId, ImOnlineId)>,
     root_key: AccountId,
     endowed_accounts: Vec<AccountId>,
+    cpcp: node_runtime::ProposalsConfigParameters,
 ) -> GenesisConfig {
     const CENTS: Balance = 1;
     const DOLLARS: Balance = 100 * CENTS;
     const STASH: Balance = 20 * DOLLARS;
     const ENDOWMENT: Balance = 100_000 * DOLLARS;
 
-    // default codex proposals config parameters
-    let cpcp = node_runtime::ProposalsConfigParameters::default();
     let default_text_constraint = node_runtime::working_group::default_text_constraint();
 
     GenesisConfig {
@@ -328,7 +329,7 @@ pub fn testnet_genesis(
             set_content_working_group_mint_capacity_proposal_grace_period: cpcp
                 .set_content_working_group_mint_capacity_proposal_grace_period,
             set_lead_proposal_voting_period: cpcp.set_lead_proposal_voting_period,
-            set_lead_proposal_grace_period: cpcp.set_lead_proposal_voting_period,
+            set_lead_proposal_grace_period: cpcp.set_lead_proposal_grace_period,
             spending_proposal_voting_period: cpcp.spending_proposal_voting_period,
             spending_proposal_grace_period: cpcp.spending_proposal_grace_period,
             add_working_group_opening_proposal_voting_period: cpcp

+ 1 - 0
node/src/lib.rs

@@ -2,4 +2,5 @@ pub mod chain_spec;
 pub mod cli;
 pub mod forum_config;
 pub mod members_config;
+pub mod proposals_config;
 pub mod service;

+ 17 - 0
node/src/proposals_config.rs

@@ -0,0 +1,17 @@
+use node_runtime::ProposalsConfigParameters;
+
+/// Development chain config. 0 grace period for all proposals, ie.
+/// proposals executed immediatly. Short voting period.
+pub fn development() -> ProposalsConfigParameters {
+    ProposalsConfigParameters::with_grace_and_voting_periods(0, 200)
+}
+
+/// Staging chain config. Shorter grace periods and voting periods than default.
+pub fn staging() -> ProposalsConfigParameters {
+    ProposalsConfigParameters::with_grace_and_voting_periods(200, 600)
+}
+
+/// The default configuration as defined in the runtime module
+pub fn default() -> ProposalsConfigParameters {
+    ProposalsConfigParameters::default()
+}

+ 4 - 0
package.json

@@ -42,5 +42,9 @@
       "pre-commit": "devops/git-hooks/pre-commit",
       "pre-push": "devops/git-hooks/pre-push"
     }
+  },
+  "engines": {
+    "node": ">=12.18.0",
+    "yarn": "^1.22.0"
   }
 }

+ 3 - 3
pioneer/package.json

@@ -2,8 +2,8 @@
   "version": "0.37.0-beta.63",
   "private": true,
   "engines": {
-    "node": ">=10.13.0",
-    "yarn": "^1.10.1"
+    "node": ">=12.18.0",
+    "yarn": "^1.22.0"
   },
   "homepage": ".",
   "name": "pioneer",
@@ -82,6 +82,6 @@
     "node-sass": "^4.13.0",
     "sass-loader": "^8.0.0",
     "style-loader": "^1.0.0",
-    "@joystream/types": "./types"
+    "@joystream/types": "link:../types"
   }
 }

+ 8 - 1
pioneer/packages/app-js/src/Playground.tsx

@@ -18,6 +18,7 @@ import uiKeyring from '@polkadot/ui-keyring';
 import * as types from '@polkadot/types';
 import * as util from '@polkadot/util';
 import * as hashing from '@polkadot/util-crypto';
+import * as joy_types from '@joystream/types';
 
 import makeWrapper from './snippets/wrapping';
 import allSnippets from './snippets';
@@ -39,6 +40,9 @@ interface Injected {
   types: typeof types;
   util: typeof util;
   window: null;
+  joy: {
+    types: typeof joy_types;
+  };
 }
 
 interface Props extends AppProps, I18nProps, RouteComponentProps<{}> {
@@ -195,7 +199,10 @@ function Playground ({ className, history, match: { params: { base64 } }, t }: P
         : null,
       types,
       util,
-      window: null
+      window: null,
+      joy: {
+        types: joy_types
+      }
     };
 
     await injectedRef.current.api.isReady;

+ 2 - 2
pioneer/packages/joy-election/src/Applicant.tsx

@@ -11,12 +11,12 @@ import CandidatePreview from './CandidatePreview';
 
 import translate from './translate';
 import { calcTotalStake } from '@polkadot/joy-utils/index';
-import { Stake } from '@joystream/types/council';
+import { ElectionStake } from '@joystream/types/council';
 
 type Props = ApiProps & I18nProps & {
   index: number;
   accountId: AccountId;
-  stake?: Stake;
+  stake?: ElectionStake;
 };
 
 class Applicant extends React.PureComponent<Props> {

+ 2 - 2
pioneer/packages/joy-election/src/ApplyForm.tsx

@@ -10,13 +10,13 @@ import { Balance } from '@polkadot/types/interfaces';
 import translate from './translate';
 import TxButton from '@polkadot/joy-utils/TxButton';
 import InputStake from '@polkadot/joy-utils/InputStake';
-import { Stake } from '@joystream/types/council';
+import { ElectionStake } from '@joystream/types/council';
 import { calcTotalStake, ZERO } from '@polkadot/joy-utils/index';
 import { MyAddressProps, withOnlyMembers } from '@polkadot/joy-utils/MyAccount';
 
 type Props = ApiProps & I18nProps & MyAddressProps & {
   minStake?: Balance;
-  alreadyStaked?: Stake;
+  alreadyStaked?: ElectionStake;
   myBalance?: Balance;
 };
 

+ 206 - 89
pioneer/packages/joy-proposals/src/Proposal/Body.tsx

@@ -1,25 +1,30 @@
 import React from 'react';
+import { Link } from 'react-router-dom';
 import { Card, Header, Button, Icon, Message } from 'semantic-ui-react';
 import { ProposalType } from '@polkadot/joy-utils/types/proposals';
 import { bytesToString } from '@polkadot/joy-utils/functions/misc';
-import { blake2AsHex } from '@polkadot/util-crypto';
 import styled from 'styled-components';
 import AddressMini from '@polkadot/react-components/AddressMiniJoy';
 import TxButton from '@polkadot/joy-utils/TxButton';
-import { ProposalId } from '@joystream/types/proposals';
+import { ProposalId, TerminateRoleParameters } from '@joystream/types/proposals';
 import { MemberId, Profile } from '@joystream/types/members';
 import ProfilePreview from '@polkadot/joy-utils/MemberProfilePreview';
 import { useTransport, usePromise } from '@polkadot/joy-utils/react/hooks';
 import { Option, Bytes } from '@polkadot/types/';
+import { BlockNumber } from '@polkadot/types/interfaces';
 import { formatBalance } from '@polkadot/util';
 import { PromiseComponent } from '@polkadot/joy-utils/react/components';
 import ReactMarkdown from 'react-markdown';
-import { WorkingGroupOpeningPolicyCommitment } from '@joystream/types/working-group';
+import { WorkingGroupOpeningPolicyCommitment, RewardPolicy } from '@joystream/types/working-group';
 import {
   ActivateOpeningAt,
-  ActivateOpeningAtKeys
+  ActivateOpeningAtKeys,
+  StakingPolicy
 } from '@joystream/types/hiring';
-import { WorkingGroup } from '@joystream/types/common';
+import { WorkingGroup, WorkingGroupKey } from '@joystream/types/common';
+import { ApplicationsDetailsByOpening } from '@polkadot/joy-utils/react/components/working-groups/ApplicationDetails';
+import { LeadInfoFromId } from '@polkadot/joy-utils/react/components/working-groups/LeadInfo';
+import { formatReward } from '@polkadot/joy-utils/functions/format';
 
 type BodyProps = {
   title: string;
@@ -81,91 +86,199 @@ const ParsedHRT = styled.pre`
   white-space: pre-wrap;
 `;
 
+type ParsedParamValue = string | number | JSX.Element;
+
+class ParsedParam {
+  name: string;
+  value: ParsedParamValue;
+  fullWidth: boolean;
+
+  constructor (name: string, value: ParsedParamValue, fullWidth = false) {
+    this.name = name;
+    this.value = value;
+    this.fullWidth = fullWidth;
+  }
+}
+
 // The methods for parsing params by Proposal type.
-// They take the params as array and return { LABEL: VALUE } object.
-const paramParsers: { [x in ProposalType]: (params: any[]) => { [key: string]: string | number | JSX.Element } } = {
-  Text: ([content]) => ({
-    Content: <ReactMarkdown className='TextProposalContent' source={content} linkTarget='_blank' />
-  }),
-  RuntimeUpgrade: ([wasm]) => {
-    const buffer: Buffer = Buffer.from(wasm.replace('0x', ''), 'hex');
-    return {
-      'Blake2b256 hash of WASM code': blake2AsHex(buffer, 256),
-      'File size': buffer.length + ' bytes'
-    };
-  },
-  SetElectionParameters: ([params]) => ({
-    'Announcing period': params.announcing_period + ' blocks',
-    'Voting period': params.voting_period + ' blocks',
-    'Revealing period': params.revealing_period + ' blocks',
-    'Council size': params.council_size + ' members',
-    'Candidacy limit': params.candidacy_limit + ' members',
-    'New term duration': params.new_term_duration + ' blocks',
-    'Min. council stake': formatBalance(params.min_council_stake),
-    'Min. voting stake': formatBalance(params.min_voting_stake)
-  }),
-  Spending: ([amount, account]) => ({
-    Amount: formatBalance(amount),
-    Account: <ProposedAddress address={account} />
-  }),
-  SetLead: ([memberId, accountId]) => ({
-    Member: <ProposedMember memberId={ memberId } />,
-    'Account id': <ProposedAddress address={accountId} />
-  }),
-  SetContentWorkingGroupMintCapacity: ([capacity]) => ({
-    'Mint capacity': formatBalance(capacity)
-  }),
-  EvictStorageProvider: ([accountId]) => ({
-    'Storage provider account': <ProposedAddress address={accountId} />
-  }),
-  SetValidatorCount: ([count]) => ({
-    'Validator count': count
-  }),
-  SetStorageRoleParameters: ([params]) => ({
-    'Min. stake': formatBalance(params.min_stake),
+const paramParsers: { [x in ProposalType]: (params: any[]) => ParsedParam[]} = {
+  Text: ([content]) => [
+    new ParsedParam(
+      'Content',
+      <ReactMarkdown className='TextProposalContent' source={content} linkTarget='_blank' />,
+      true
+    )
+  ],
+  RuntimeUpgrade: ([hash, filesize]) => [
+    new ParsedParam('Blake2b256 hash of WASM code', hash, true),
+    new ParsedParam('File size', filesize + ' bytes')
+  ],
+  SetElectionParameters: ([params]) => [
+    new ParsedParam('Announcing period', params.announcing_period + ' blocks'),
+    new ParsedParam('Voting period', params.voting_period + ' blocks'),
+    new ParsedParam('Revealing period', params.revealing_period + ' blocks'),
+    new ParsedParam('Council size', params.council_size + ' members'),
+    new ParsedParam('Candidacy limit', params.candidacy_limit + ' members'),
+    new ParsedParam('New term duration', params.new_term_duration + ' blocks'),
+    new ParsedParam('Min. council stake', formatBalance(params.min_council_stake)),
+    new ParsedParam('Min. voting stake', formatBalance(params.min_voting_stake))
+  ],
+  Spending: ([amount, account]) => [
+    new ParsedParam('Amount', formatBalance(amount)),
+    new ParsedParam('Account', <ProposedAddress address={account} />)
+  ],
+  SetLead: ([memberId, accountId]) => [
+    new ParsedParam('Member', <ProposedMember memberId={ memberId } />),
+    new ParsedParam('Account id', <ProposedAddress address={accountId} />)
+  ],
+  SetContentWorkingGroupMintCapacity: ([capacity]) => [
+    new ParsedParam('Mint capacity', formatBalance(capacity))
+  ],
+  EvictStorageProvider: ([accountId]) => [
+    new ParsedParam('Storage provider account', <ProposedAddress address={accountId} />)
+  ],
+  SetValidatorCount: ([count]) => [
+    new ParsedParam('Validator count', count)
+  ],
+  SetStorageRoleParameters: ([params]) => [
+    new ParsedParam('Min. stake', formatBalance(params.min_stake)),
     // "Min. actors": params.min_actors,
-    'Max. actors': params.max_actors,
-    Reward: formatBalance(params.reward),
-    'Reward period': params.reward_period + ' blocks',
+    new ParsedParam('Max. actors', params.max_actors),
+    new ParsedParam('Reward', formatBalance(params.reward)),
+    new ParsedParam('Reward period', params.reward_period + ' blocks'),
     // "Bonding period": params.bonding_period + " blocks",
-    'Unbonding period': params.unbonding_period + ' blocks',
+    new ParsedParam('Unbonding period', params.unbonding_period + ' blocks'),
     // "Min. service period": params.min_service_period + " blocks",
     // "Startup grace period": params.startup_grace_period + " blocks",
-    'Entry request fee': formatBalance(params.entry_request_fee)
-  }),
+    new ParsedParam('Entry request fee', formatBalance(params.entry_request_fee))
+  ],
   AddWorkingGroupLeaderOpening: ([{ activate_at, commitment, human_readable_text, working_group }]) => {
     const workingGroup = new WorkingGroup(working_group);
     const activateAt = new ActivateOpeningAt(activate_at);
     const activateAtBlock = activateAt.type === ActivateOpeningAtKeys.ExactBlock ? activateAt.value : null;
     const OPCommitment = new WorkingGroupOpeningPolicyCommitment(commitment);
     const {
-      application_staking_policy: aSP,
-      role_staking_policy: rSP,
+      application_staking_policy: applicationSP,
+      role_staking_policy: roleSP,
       application_rationing_policy: rationingPolicy
     } = OPCommitment;
     let HRT = bytesToString(new Bytes(human_readable_text));
     try { HRT = JSON.stringify(JSON.parse(HRT), undefined, 4); } catch (e) { /* Do nothing */ }
-    return {
-      'Working group': workingGroup.type,
-      'Activate at': `${activateAt.type}${activateAtBlock ? `(${activateAtBlock.toString()})` : ''}`,
-      'Application stake': aSP.isSome ? aSP.unwrap().amount_mode.type + `(${aSP.unwrap().amount})` : 'NONE',
-      'Role stake': rSP.isSome ? rSP.unwrap().amount_mode.type + `(${rSP.unwrap().amount})` : 'NONE',
-      'Max. applications': rationingPolicy.isSome ? rationingPolicy.unwrap().max_active_applicants.toNumber() : 'UNLIMITED',
-      'Terminate unstaking period (role stake)': OPCommitment.terminate_role_stake_unstaking_period.unwrapOr(0) + ' blocks',
-      'Exit unstaking period (role stake)': OPCommitment.exit_role_stake_unstaking_period.unwrapOr(0) + ' blocks',
+    const formatStake = (stake: Option<StakingPolicy>) => (
+      stake.isSome ? stake.unwrap().amount_mode.type + `(${stake.unwrap().amount})` : 'NONE'
+    );
+    const formatPeriod = (unstakingPeriod: Option<BlockNumber>) => (
+      unstakingPeriod.unwrapOr(0) + ' blocks'
+    );
+    return [
+      new ParsedParam('Working group', workingGroup.type),
+      new ParsedParam('Activate at', `${activateAt.type}${activateAtBlock ? `(${activateAtBlock.toString()})` : ''}`),
+      new ParsedParam('Application stake', formatStake(applicationSP)),
+      new ParsedParam('Role stake', formatStake(roleSP)),
+      new ParsedParam(
+        'Max. applications',
+        rationingPolicy.isSome ? rationingPolicy.unwrap().max_active_applicants.toNumber() : 'UNLIMITED'
+      ),
+      new ParsedParam(
+        'Terminate unstaking period (role stake)',
+        formatPeriod(OPCommitment.terminate_role_stake_unstaking_period)
+      ),
+      new ParsedParam(
+        'Exit unstaking period (role stake)',
+        formatPeriod(OPCommitment.exit_role_stake_unstaking_period)
+      ),
       // <required_to_prevent_sneaking>
-      'Terminate unstaking period (appl. stake)': OPCommitment.terminate_application_stake_unstaking_period.unwrapOr(0) + ' blocks',
-      'Exit unstaking period (appl. stake)': OPCommitment.exit_role_application_stake_unstaking_period.unwrapOr(0) + ' blocks',
-      'Appl. accepted unstaking period (appl. stake)': OPCommitment.fill_opening_successful_applicant_application_stake_unstaking_period.unwrapOr(0) + ' blocks',
-      'Appl. failed unstaking period (role stake)': OPCommitment.fill_opening_failed_applicant_role_stake_unstaking_period.unwrapOr(0) + ' blocks',
-      'Appl. failed unstaking period (appl. stake)': OPCommitment.fill_opening_failed_applicant_application_stake_unstaking_period.unwrapOr(0) + ' blocks',
-      'Crowded out unstaking period (role stake)': ((rSP.isSome && rSP.unwrap().crowded_out_unstaking_period_length.unwrapOr(0)) || 0) + ' blocks',
-      'Review period expierd unstaking period (role stake)': ((rSP.isSome && rSP.unwrap().review_period_expired_unstaking_period_length.unwrapOr(0)) || 0) + ' blocks',
-      'Crowded out unstaking period (appl. stake)': ((aSP.isSome && aSP.unwrap().crowded_out_unstaking_period_length.unwrapOr(0)) || 0) + ' blocks',
-      'Review period expierd unstaking period (appl. stake)': ((aSP.isSome && aSP.unwrap().review_period_expired_unstaking_period_length.unwrapOr(0)) || 0) + ' blocks',
+      new ParsedParam(
+        'Terminate unstaking period (appl. stake)',
+        formatPeriod(OPCommitment.terminate_application_stake_unstaking_period)
+      ),
+      new ParsedParam(
+        'Exit unstaking period (appl. stake)',
+        formatPeriod(OPCommitment.exit_role_application_stake_unstaking_period)
+      ),
+      new ParsedParam(
+        'Appl. accepted unstaking period (appl. stake)',
+        formatPeriod(OPCommitment.fill_opening_successful_applicant_application_stake_unstaking_period)
+      ),
+      new ParsedParam(
+        'Appl. failed unstaking period (role stake)',
+        formatPeriod(OPCommitment.fill_opening_failed_applicant_role_stake_unstaking_period)
+      ),
+      new ParsedParam(
+        'Appl. failed unstaking period (appl. stake)',
+        formatPeriod(OPCommitment.fill_opening_failed_applicant_application_stake_unstaking_period)
+      ),
+      new ParsedParam(
+        'Crowded out unstaking period (role stake)',
+        roleSP.isSome ? formatPeriod(roleSP.unwrap().crowded_out_unstaking_period_length) : '0 blocks'
+      ),
+      new ParsedParam(
+        'Review period expierd unstaking period (role stake)',
+        roleSP.isSome ? formatPeriod(roleSP.unwrap().review_period_expired_unstaking_period_length) : '0 blocks'
+      ),
+      new ParsedParam(
+        'Crowded out unstaking period (appl. stake)',
+        applicationSP.isSome ? formatPeriod(applicationSP.unwrap().crowded_out_unstaking_period_length) : '0 blocks'
+      ),
+      new ParsedParam(
+        'Review period expierd unstaking period (appl. stake)',
+        applicationSP.isSome ? formatPeriod(applicationSP.unwrap().review_period_expired_unstaking_period_length) : '0 blocks'
+      ),
       // </required_to_prevent_sneaking>
-      'Human readable text': <ParsedHRT>{ HRT }</ParsedHRT>
-    };
+      new ParsedParam('Human readable text', <ParsedHRT>{ HRT }</ParsedHRT>, true)
+    ];
+  },
+  SetWorkingGroupMintCapacity: ([capacity, group]) => [
+    new ParsedParam('Working group', (new WorkingGroup(group)).type),
+    new ParsedParam('Mint capacity', formatBalance(capacity))
+  ],
+  BeginReviewWorkingGroupLeaderApplication: ([id, group]) => [
+    new ParsedParam('Working group', (new WorkingGroup(group)).type),
+    // TODO: Adjust the link to work with multiple groups after working-groups are normalized!
+    new ParsedParam('Opening id', <Link to={`/working-groups/opportunities/storageProviders/${id}`}>#{id}</Link>)
+  ],
+  FillWorkingGroupLeaderOpening: ([params]) => {
+    const { opening_id, successful_application_id, reward_policy, working_group } = params;
+    const rewardPolicy = reward_policy && new RewardPolicy(reward_policy);
+    return [
+      new ParsedParam('Working group', (new WorkingGroup(working_group)).type),
+      // TODO: Adjust the link to work with multiple groups after working-groups are normalized!
+      new ParsedParam('Opening id', <Link to={`/working-groups/opportunities/storageProviders/${opening_id}`}>#{opening_id}</Link>),
+      new ParsedParam('Reward policy', rewardPolicy ? formatReward(rewardPolicy, true) : 'NONE'),
+      new ParsedParam(
+        'Result',
+        <ApplicationsDetailsByOpening
+          openingId={opening_id}
+          acceptedIds={[successful_application_id]}
+          group={(new WorkingGroup(working_group)).type as WorkingGroupKey}/>,
+        true
+      )
+    ];
+  },
+  SlashWorkingGroupLeaderStake: ([leadId, amount, group]) => [
+    new ParsedParam('Working group', (new WorkingGroup(group)).type),
+    new ParsedParam('Slash amount', formatBalance(amount)),
+    new ParsedParam('Lead', <LeadInfoFromId group={(new WorkingGroup(group).type as WorkingGroupKey)} leadId={leadId}/>, true)
+  ],
+  DecreaseWorkingGroupLeaderStake: ([leadId, amount, group]) => [
+    new ParsedParam('Working group', (new WorkingGroup(group)).type),
+    new ParsedParam('Decrease amount', formatBalance(amount)),
+    new ParsedParam('Lead', <LeadInfoFromId group={(new WorkingGroup(group).type as WorkingGroupKey)} leadId={leadId}/>, true)
+  ],
+  SetWorkingGroupLeaderReward: ([leadId, amount, group]) => [
+    new ParsedParam('Working group', (new WorkingGroup(group)).type),
+    new ParsedParam('New reward amount', formatBalance(amount)),
+    new ParsedParam('Lead', <LeadInfoFromId group={(new WorkingGroup(group).type as WorkingGroupKey)} leadId={leadId}/>, true)
+  ],
+  TerminateWorkingGroupLeaderRole: ([params]) => {
+    const paramsObj = new TerminateRoleParameters(params);
+    const { working_group: workingGroup, rationale, worker_id: leadId, slash } = paramsObj;
+    return [
+      new ParsedParam('Working group', workingGroup.type),
+      new ParsedParam('Rationale', bytesToString(rationale), true),
+      new ParsedParam('Slash stake', slash.isTrue ? 'YES' : 'NO'),
+      new ParsedParam('Lead', <LeadInfoFromId group={workingGroup.type as WorkingGroupKey} leadId={leadId.toNumber()}/>, true)
+    ];
   }
 };
 
@@ -173,14 +286,14 @@ const StyledProposalDescription = styled(Card.Description)`
   font-size: 1.15rem;
 `;
 const ProposalParams = styled.div`
-  display: grid;
-  font-weight: bold;
-  grid-template-columns: min-content 1fr;
-  grid-row-gap: 0.5rem;
   border: 1px solid rgba(0,0,0,.2);
-  padding: 1.5rem 1.5rem 1rem 1.25rem;
+  padding: 1.5rem 2rem 1rem 2rem;
   position: relative;
   margin-top: 1.7rem;
+  display: grid;
+  grid-template-columns: 1fr 1fr;
+  grid-column-gap: 1rem;
+  grid-row-gap: 0.5rem;
   @media screen and (max-width: 767px) {
     grid-template-columns: 1fr;
   }
@@ -194,21 +307,25 @@ const ParamsHeader = styled.h4`
   padding: 0.3rem;
   left: 0.5rem;
 `;
+type ProposalParamProps = { fullWidth?: boolean };
+const ProposalParam = ({ fullWidth, children }: React.PropsWithChildren<ProposalParamProps>) => (
+  <div style={{ gridColumn: (fullWidth || undefined) && '1/3' }}>
+    { children }
+  </div>
+);
 const ProposalParamName = styled.div`
-  margin-right: 1rem;
-  white-space: nowrap;
+  font-size: 0.9rem;
+  font-weight: normal;
 `;
 const ProposalParamValue = styled.div`
   color: black;
   word-wrap: break-word;
   word-break: break-word;
   font-size: 1.15rem;
+  font-weight: bold;
   & .TextProposalContent {
     font-weight: normal;
   }
-  @media screen and (max-width: 767px) {
-    margin-top: -0.25rem;
-  }
 `;
 
 export default function Body ({
@@ -235,15 +352,15 @@ export default function Body ({
         </StyledProposalDescription>
         <ProposalParams>
           <ParamsHeader>Parameters:</ParamsHeader>
-          { Object.entries(parsedParams).map(([paramName, paramValue]) => (
-            <React.Fragment key={paramName}>
-              <ProposalParamName>{paramName}:</ProposalParamName>
-              <ProposalParamValue>{paramValue}</ProposalParamValue>
-            </React.Fragment>
+          { parsedParams.map(({ name, value, fullWidth }) => (
+            <ProposalParam key={name} fullWidth={fullWidth}>
+              <ProposalParamName>{name}:</ProposalParamName>
+              <ProposalParamValue>{value}</ProposalParamValue>
+            </ProposalParam>
           ))}
         </ProposalParams>
         { iAmProposer && isCancellable && (<>
-          <Message warning active>
+          <Message warning visible>
             <Message.Content>
               <Message.Header>Proposal cancellation</Message.Header>
               <p style={{ margin: '0.5em 0', padding: '0' }}>

+ 2 - 12
pioneer/packages/joy-proposals/src/Proposal/ChooseProposalType.tsx

@@ -3,27 +3,17 @@ import ProposalTypePreview from './ProposalTypePreview';
 import { Item, Dropdown } from 'semantic-ui-react';
 
 import { useTransport, usePromise } from '@polkadot/joy-utils/react/hooks';
+import { Categories } from '@polkadot/joy-utils/types/proposals';
 import { PromiseComponent } from '@polkadot/joy-utils/react/components';
 import './ChooseProposalType.css';
 import { RouteComponentProps } from 'react-router-dom';
 
-export const Categories = {
-  storage: 'Storage',
-  council: 'Council',
-  validators: 'Validators',
-  cwg: 'Content Working Group',
-  other: 'Other'
-} as const;
-
-export type Category = typeof Categories[keyof typeof Categories];
-
 export default function ChooseProposalType (props: RouteComponentProps) {
   const transport = useTransport();
 
   const [proposalTypes, error, loading] = usePromise(() => transport.proposals.proposalsTypesParameters(), []);
   const [category, setCategory] = useState('');
 
-  console.log({ proposalTypes, loading, error });
   return (
     <div className="ChooseProposalType">
       <PromiseComponent error={error} loading={loading} message={'Fetching proposals\' parameters...'}>
@@ -39,7 +29,7 @@ export default function ChooseProposalType (props: RouteComponentProps) {
         </div>
         <Item.Group>
           {proposalTypes
-            .filter(typeInfo => !category || typeInfo.category === category)
+            .filter(typeInfo => (!category || typeInfo.category === category) && !typeInfo.outdated)
             .map((typeInfo, idx) => (
               <ProposalTypePreview key={`${typeInfo} - ${idx}`} typeInfo={typeInfo} history={props.history} />
             ))}

+ 5 - 3
pioneer/packages/joy-proposals/src/Proposal/Details.tsx

@@ -1,6 +1,7 @@
 import React from 'react';
-import { Item, Header } from 'semantic-ui-react';
+import { Item, Header, Label } from 'semantic-ui-react';
 import { ParsedProposal } from '@polkadot/joy-utils/types/proposals';
+import { metadata as proposalConsts } from '@polkadot/joy-utils/consts/proposals';
 import { ExtendedProposalStatus } from './ProposalDetails';
 import styled from 'styled-components';
 
@@ -71,7 +72,6 @@ type DetailsProps = {
 export default function Details ({ proposal, extendedStatus, proposerLink = false }: DetailsProps) {
   const { type, createdAt, createdAtBlock, proposer } = proposal;
   const { displayStatus, periodStatus, expiresIn, finalizedAtBlock, executedAtBlock, executionFailReason } = extendedStatus;
-  console.log(proposal);
   return (
     <DetailsContainer>
       <Detail name="Proposed By">
@@ -83,7 +83,9 @@ export default function Details ({ proposal, extendedStatus, proposerLink = fals
         />
         <Item.Extra>{ `${createdAt.toLocaleString()}` }</Item.Extra>
       </Detail>
-      <Detail name="Proposal type" value={type} />
+      <Detail name="Proposal type" value={type}>
+        <Item.Extra>{ proposalConsts[type].outdated && <Label size="small">Outdated proposal type</Label> }</Item.Extra>
+      </Detail>
       <Detail name="Stage" value={displayStatus}>
         <Item.Extra>
           { createdAtBlock && <BlockInfo>Created at block <b>#{ createdAtBlock }</b></BlockInfo> }

+ 2 - 1
pioneer/packages/joy-proposals/src/Proposal/ProposalFromId.tsx

@@ -3,6 +3,7 @@ import { RouteComponentProps } from 'react-router-dom';
 import ProposalDetails from './ProposalDetails';
 import { useProposalSubscription } from '@polkadot/joy-utils/react/hooks';
 import { PromiseComponent } from '@polkadot/joy-utils/react/components';
+import { ProposalId } from '@joystream/types/proposals';
 
 export default function ProposalFromId (props: RouteComponentProps<any>) {
   const {
@@ -11,7 +12,7 @@ export default function ProposalFromId (props: RouteComponentProps<any>) {
     }
   } = props;
 
-  const { proposal: proposalState, votes: votesState } = useProposalSubscription(id);
+  const { proposal: proposalState, votes: votesState } = useProposalSubscription(new ProposalId(id));
 
   return (
     <PromiseComponent

+ 1 - 2
pioneer/packages/joy-proposals/src/Proposal/ProposalTypePreview.tsx

@@ -3,8 +3,7 @@ import React from 'react';
 import { History } from 'history';
 import { Item, Icon, Button, Label } from 'semantic-ui-react';
 
-import { Category } from './ChooseProposalType';
-import { ProposalType } from '@polkadot/joy-utils/types/proposals';
+import { ProposalType, Category } from '@polkadot/joy-utils/types/proposals';
 import _ from 'lodash';
 import styled from 'styled-components';
 import useVoteStyles from './useVoteStyles';

+ 10 - 5
pioneer/packages/joy-proposals/src/forms/AddWorkingGroupOpeningForm.tsx

@@ -23,13 +23,13 @@ import { formatBalance } from '@polkadot/util';
 import _ from 'lodash';
 import { IWorkingGroupOpeningPolicyCommitment } from '@joystream/types/working-group';
 import { IAddOpeningParameters } from '@joystream/types/proposals';
-import { WorkingGroupKeys } from '@joystream/types/common';
+import { WorkingGroupKey, InputValidationLengthConstraint } from '@joystream/types/common';
 import { BlockNumber } from '@polkadot/types/interfaces';
 import { withCalls } from '@polkadot/react-api';
 import { SimplifiedTypeInterface } from '@polkadot/joy-utils/types/common';
 import Validation from '../validationSchema';
 
-type FormValues = WGFormValues & {
+export type FormValues = WGFormValues & {
   activateAt: ActivateOpeningAtKey;
   activateAtBlock: string;
   maxReviewPeriodLength: string;
@@ -64,7 +64,7 @@ const defaultValues: FormValues = {
   humanReadableText: ''
 };
 
-const HRTDefault: (memberHandle: string, group: WorkingGroupKeys) => GenericJoyStreamRoleSchema =
+const HRTDefault: (memberHandle: string, group: WorkingGroupKey) => GenericJoyStreamRoleSchema =
   (memberHandle, group) => ({
     version: 1,
     headline: `Looking for ${group} Working Group Leader!`,
@@ -101,6 +101,7 @@ type FormAdditionalProps = {}; // Aditional props coming all the way from export
 type ExportComponentProps = ProposalFormExportProps<FormAdditionalProps, FormValues>;
 type FormContainerProps = ProposalFormContainerProps<ExportComponentProps> & {
   currentBlock?: BlockNumber;
+  HRTConstraint?: InputValidationLengthConstraint;
 };
 type FormInnerProps = ProposalFormInnerProps<FormContainerProps, FormValues>;
 
@@ -344,14 +345,18 @@ const FormContainer = withFormContainer<FormContainerProps, FormValues>({
   }),
   validationSchema: (props: FormContainerProps) => Yup.object().shape({
     ...genericFormDefaultOptions.validationSchema,
-    ...Validation.AddWorkingGroupLeaderOpening(props.currentBlock?.toNumber() || 0)
+    ...Validation.AddWorkingGroupLeaderOpening(
+      props.currentBlock?.toNumber() || 0,
+      props.HRTConstraint || InputValidationLengthConstraint.createWithMaxAllowed()
+    )
   }),
   handleSubmit: genericFormDefaultOptions.handleSubmit,
   displayName: 'AddWorkingGroupOpeningForm'
 })(AddWorkingGroupOpeningForm);
 
 export default withCalls<ExportComponentProps>(
-  ['derive.chain.bestNumber', { propName: 'currentBlock' }]
+  ['derive.chain.bestNumber', { propName: 'currentBlock' }],
+  ['query.storageWorkingGroup.openingHumanReadableText', { propName: 'HRTConstraint' }]
 )(
   withProposalFormData<FormContainerProps, ExportComponentProps>(FormContainer)
 );

+ 118 - 0
pioneer/packages/joy-proposals/src/forms/BeginReviewLeaderApplicationsForm.tsx

@@ -0,0 +1,118 @@
+import React from 'react';
+import * as Yup from 'yup';
+import {
+  withProposalFormData,
+  ProposalFormExportProps,
+  ProposalFormContainerProps,
+  ProposalFormInnerProps,
+  genericFormDefaultOptions
+} from './GenericProposalForm';
+import {
+  GenericWorkingGroupProposalForm,
+  FormValues as WGFormValues,
+  defaultValues as wgFromDefaultValues
+} from './GenericWorkingGroupProposalForm';
+import FormField from './FormFields';
+import { withFormContainer } from './FormContainer';
+import './forms.css';
+import { Dropdown, Message } from 'semantic-ui-react';
+import _ from 'lodash';
+import Validation from '../validationSchema';
+import { useTransport, usePromise } from '@polkadot/joy-utils/react/hooks';
+import { OpeningData } from '@polkadot/joy-utils/types/workingGroups';
+import { PromiseComponent } from '@polkadot/joy-utils/react/components';
+import { getFormErrorLabelsProps } from './errorHandling';
+
+export type FormValues = WGFormValues & {
+  openingId: string;
+};
+
+const defaultValues: FormValues = {
+  ...wgFromDefaultValues,
+  openingId: ''
+};
+
+type FormAdditionalProps = {}; // Aditional props coming all the way from export component into the inner form.
+type ExportComponentProps = ProposalFormExportProps<FormAdditionalProps, FormValues>;
+type FormContainerProps = ProposalFormContainerProps<ExportComponentProps>;
+type FormInnerProps = ProposalFormInnerProps<FormContainerProps, FormValues>;
+
+const BeginReviewLeadeApplicationsForm: React.FunctionComponent<FormInnerProps> = props => {
+  const { handleChange, values, myMemberId, errors, touched } = props;
+  const errorLabelsProps = getFormErrorLabelsProps<FormValues>(errors, touched);
+  const transport = useTransport();
+  const [openings, openingsError, openingsLoading] = usePromise(
+    () => transport.workingGroups.activeOpenings(values.workingGroup, 'AcceptingApplications', 'Leader'),
+    [] as OpeningData[],
+    [values.workingGroup]
+  );
+  const openingsOptions = openings
+    // Map to options
+    .map(od => {
+      const hrt = od.hiringOpening.parse_human_readable_text_with_fallback();
+      return {
+        text: `${od.id.toString()}: ${hrt.headline} (${hrt.job.title})`,
+        value: od.id.toString()
+      };
+    });
+
+  return (
+    <GenericWorkingGroupProposalForm
+      {...props}
+      txMethod="createBeginReviewWorkingGroupLeaderApplicationsProposal"
+      proposalType="BeginReviewWorkingGroupLeaderApplication"
+      disabled={!openingsOptions.length}
+      submitParams={[
+        myMemberId,
+        values.title,
+        values.rationale,
+        '{STAKE}',
+        values.openingId,
+        values.workingGroup
+      ]}
+    >
+      <PromiseComponent error={openingsError} loading={openingsLoading} message="Fetching openings...">
+        { !openingsOptions.length
+          ? (
+            <Message error visible>
+              <Message.Header>No openings available!</Message.Header>
+              <Message.Content>
+                This proposal cannot be created, because no leader openings in <i>Accepting Applications</i> stage are currently available
+                in {values.workingGroup} Working Group.
+              </Message.Content>
+            </Message>
+          )
+          : (
+            <FormField
+              label="Working Group Opening"
+              error={errorLabelsProps.openingId}
+              showErrorMsg>
+              <Dropdown
+                onChange={handleChange}
+                name={'openingId'}
+                selection
+                options={openingsOptions}
+                value={values.openingId}
+              />
+            </FormField>
+          )
+        }
+      </PromiseComponent>
+    </GenericWorkingGroupProposalForm>
+  );
+};
+
+const FormContainer = withFormContainer<FormContainerProps, FormValues>({
+  mapPropsToValues: (props: FormContainerProps) => ({
+    ...defaultValues,
+    ...(props.initialData || {})
+  }),
+  validationSchema: Yup.object().shape({
+    ...genericFormDefaultOptions.validationSchema,
+    ...Validation.BeginReviewWorkingGroupLeaderApplication()
+  }),
+  handleSubmit: genericFormDefaultOptions.handleSubmit,
+  displayName: 'BeginReviewLeadeApplicationsForm'
+})(BeginReviewLeadeApplicationsForm);
+
+export default withProposalFormData<FormContainerProps, ExportComponentProps>(FormContainer);

+ 102 - 0
pioneer/packages/joy-proposals/src/forms/DecreaseWorkingGroupLeadStakeForm.tsx

@@ -0,0 +1,102 @@
+import React, { useState, useEffect } from 'react';
+import { getFormErrorLabelsProps } from './errorHandling';
+import * as Yup from 'yup';
+import {
+  withProposalFormData,
+  ProposalFormExportProps,
+  ProposalFormContainerProps,
+  ProposalFormInnerProps,
+  genericFormDefaultOptions
+} from './GenericProposalForm';
+import {
+  GenericWorkingGroupProposalForm,
+  FormValues as WGFormValues,
+  defaultValues as wgFromDefaultValues
+} from './GenericWorkingGroupProposalForm';
+import { InputFormField } from './FormFields';
+import { withFormContainer } from './FormContainer';
+import './forms.css';
+import { Grid } from 'semantic-ui-react';
+import { formatBalance } from '@polkadot/util';
+import _ from 'lodash';
+import Validation from '../validationSchema';
+import { WorkerData } from '@polkadot/joy-utils/types/workingGroups';
+
+export type FormValues = WGFormValues & {
+  amount: string;
+};
+
+const defaultValues: FormValues = {
+  ...wgFromDefaultValues,
+  amount: ''
+};
+
+type FormAdditionalProps = {}; // Aditional props coming all the way from export component into the inner form.
+type ExportComponentProps = ProposalFormExportProps<FormAdditionalProps, FormValues>;
+type FormContainerProps = ProposalFormContainerProps<ExportComponentProps>;
+type FormInnerProps = ProposalFormInnerProps<FormContainerProps, FormValues>;
+
+const DecreaseWorkingGroupLeadStakeForm: React.FunctionComponent<FormInnerProps> = props => {
+  const { handleChange, errors, touched, values, myMemberId, setFieldError } = props;
+  const errorLabelsProps = getFormErrorLabelsProps<FormValues>(errors, touched);
+  const [lead, setLead] = useState<WorkerData | null>(null);
+
+  // Here we validate if stake <= current lead stake.
+  // Because it depends on selected working group,
+  // there's no easy way to do it using validationSchema
+  useEffect(() => {
+    if (lead && parseInt(values.amount) > (lead.stake || 0) && !errors.amount) {
+      setFieldError('amount', `The stake cannot exceed current leader's stake (${formatBalance(lead.stake)})`);
+    }
+  });
+
+  return (
+    <GenericWorkingGroupProposalForm
+      {...props}
+      txMethod="createDecreaseWorkingGroupLeaderStakeProposal"
+      proposalType="DecreaseWorkingGroupLeaderStake"
+      leadRequired={true}
+      leadStakeRequired={true}
+      onLeadChange={(lead: WorkerData | null) => setLead(lead)}
+      submitParams={[
+        myMemberId,
+        values.title,
+        values.rationale,
+        '{STAKE}',
+        lead?.workerId,
+        values.amount,
+        values.workingGroup
+      ]}
+    >
+      { (lead && lead.stake) && (
+        <Grid columns="4" doubling stackable verticalAlign="bottom">
+          <Grid.Column>
+            <InputFormField
+              label="Amount to decrease"
+              onChange={handleChange}
+              name="amount"
+              error={errorLabelsProps.amount}
+              value={values.amount}
+              unit={formatBalance.getDefaults().unit}
+            />
+          </Grid.Column>
+        </Grid>
+      ) }
+    </GenericWorkingGroupProposalForm>
+  );
+};
+
+const FormContainer = withFormContainer<FormContainerProps, FormValues>({
+  mapPropsToValues: (props: FormContainerProps) => ({
+    ...defaultValues,
+    ...(props.initialData || {})
+  }),
+  validationSchema: Yup.object().shape({
+    ...genericFormDefaultOptions.validationSchema,
+    ...Validation.DecreaseWorkingGroupLeaderStake()
+  }),
+  handleSubmit: genericFormDefaultOptions.handleSubmit,
+  displayName: 'DecreaseWorkingGroupLeadStakeForm'
+})(DecreaseWorkingGroupLeadStakeForm);
+
+export default withProposalFormData<FormContainerProps, ExportComponentProps>(FormContainer);

+ 0 - 88
pioneer/packages/joy-proposals/src/forms/EvictStorageProviderForm.tsx

@@ -1,88 +0,0 @@
-import React from 'react';
-import { getFormErrorLabelsProps } from './errorHandling';
-import * as Yup from 'yup';
-import { Label, Loader } from 'semantic-ui-react';
-import {
-  GenericProposalForm,
-  GenericFormValues,
-  genericFormDefaultOptions,
-  genericFormDefaultValues,
-  withProposalFormData,
-  ProposalFormExportProps,
-  ProposalFormContainerProps,
-  ProposalFormInnerProps
-} from './GenericProposalForm';
-import Validation from '../validationSchema';
-import { FormField } from './FormFields';
-import { withFormContainer } from './FormContainer';
-import { InputAddress } from '@polkadot/react-components/index';
-import { accountIdsToOptions } from '@polkadot/joy-election/utils';
-import { AccountId } from '@polkadot/types/interfaces';
-import { useTransport, usePromise } from '@polkadot/joy-utils/react/hooks';
-import './forms.css';
-
-type FormValues = GenericFormValues & {
-  storageProvider: any;
-};
-
-const defaultValues: FormValues = {
-  ...genericFormDefaultValues,
-  storageProvider: ''
-};
-
-type FormAdditionalProps = {}; // Aditional props coming all the way from export comonent into the inner form.
-type ExportComponentProps = ProposalFormExportProps<FormAdditionalProps, FormValues>;
-type FormContainerProps = ProposalFormContainerProps<ExportComponentProps>;
-type FormInnerProps = ProposalFormInnerProps<FormContainerProps, FormValues>;
-
-const EvictStorageProviderForm: React.FunctionComponent<FormInnerProps> = props => {
-  const { errors, touched, values, setFieldValue } = props;
-  const errorLabelsProps = getFormErrorLabelsProps<FormValues>(errors, touched);
-  const transport = useTransport();
-  const [storageProviders /* error */, , loading] = usePromise<AccountId[]>(() => transport.storageProviders.providers(), []);
-  const storageProvidersOptions = accountIdsToOptions(storageProviders);
-  return (
-    <GenericProposalForm
-      {...props}
-      txMethod="createEvictStorageProviderProposal"
-      proposalType="EvictStorageProvider"
-      submitParams={[props.myMemberId, values.title, values.rationale, '{STAKE}', values.storageProvider]}
-    >
-      {loading ? (
-        <>
-          <Loader active inline style={{ marginRight: '5px' }} /> Fetching storage providers...
-        </>
-      ) : (
-        <FormField
-          error={errorLabelsProps.storageProvider}
-          label="Storage provider"
-          help="The storage provider you propose to evict"
-        >
-          <InputAddress
-            onChange={address => setFieldValue('storageProvider', address)}
-            type="address"
-            placeholder="Select storage provider"
-            value={values.storageProvider}
-            options={storageProvidersOptions}
-          />
-          {errorLabelsProps.storageProvider && <Label {...errorLabelsProps.storageProvider} prompt />}
-        </FormField>
-      )}
-    </GenericProposalForm>
-  );
-};
-
-const FormContainer = withFormContainer<FormContainerProps, FormValues>({
-  mapPropsToValues: (props: FormContainerProps) => ({
-    ...defaultValues,
-    ...(props.initialData || {})
-  }),
-  validationSchema: Yup.object().shape({
-    ...genericFormDefaultOptions.validationSchema,
-    storageProvider: Validation.EvictStorageProvider.storageProvider
-  }),
-  handleSubmit: genericFormDefaultOptions.handleSubmit,
-  displayName: 'EvictStorageProvidersForm'
-})(EvictStorageProviderForm);
-
-export default withProposalFormData<FormContainerProps, ExportComponentProps>(FormContainer);

+ 232 - 0
pioneer/packages/joy-proposals/src/forms/FillWorkingGroupLeaderOpeningForm.tsx

@@ -0,0 +1,232 @@
+import React from 'react';
+import * as Yup from 'yup';
+import {
+  withProposalFormData,
+  ProposalFormExportProps,
+  ProposalFormContainerProps,
+  ProposalFormInnerProps,
+  genericFormDefaultOptions
+} from './GenericProposalForm';
+import {
+  GenericWorkingGroupProposalForm,
+  FormValues as WGFormValues,
+  defaultValues as wgFromDefaultValues
+} from './GenericWorkingGroupProposalForm';
+import { FormField, RewardPolicyFields } from './FormFields';
+import { withFormContainer } from './FormContainer';
+import './forms.css';
+import { Dropdown, DropdownItemProps, Header, Checkbox, Message } from 'semantic-ui-react';
+import _ from 'lodash';
+import Validation from '../validationSchema';
+import { useTransport, usePromise } from '@polkadot/joy-utils/react/hooks';
+import { OpeningData, ParsedApplication } from '@polkadot/joy-utils/types/workingGroups';
+import { PromiseComponent } from '@polkadot/joy-utils/react/components';
+import { formatBalance } from '@polkadot/util';
+import { withCalls } from '@polkadot/react-api';
+import { Option } from '@polkadot/types';
+import { BlockNumber } from '@polkadot/types/interfaces';
+import { u32 as U32, u128 as U128 } from '@polkadot/types/primitive';
+import { getFormErrorLabelsProps } from './errorHandling';
+import { RewardPolicy } from '@joystream/types/working-group';
+import { FillOpeningParameters } from '@joystream/types/proposals';
+import { WorkingGroup } from '@joystream/types/common';
+import { OpeningId, ApplicationId } from '@joystream/types/hiring';
+import { ApplicationsDetails } from '@polkadot/joy-utils/react/components/working-groups/ApplicationDetails';
+
+export type FormValues = WGFormValues & {
+  openingId: string;
+  successfulApplicant: string;
+  includeReward: boolean;
+  rewardAmount: string;
+  rewardNextBlock: string;
+  rewardRecurring: boolean;
+  rewardInterval: string;
+};
+
+const defaultValues: FormValues = {
+  ...wgFromDefaultValues,
+  openingId: '',
+  successfulApplicant: '',
+  includeReward: true,
+  rewardAmount: '',
+  rewardNextBlock: '',
+  rewardRecurring: true,
+  rewardInterval: ''
+};
+
+type FormAdditionalProps = {}; // Aditional props coming all the way from export component into the inner form.
+type ExportComponentProps = ProposalFormExportProps<FormAdditionalProps, FormValues>;
+type FormContainerProps = ProposalFormContainerProps<ExportComponentProps> & {
+  currentBlock?: BlockNumber;
+};
+type FormInnerProps = ProposalFormInnerProps<FormContainerProps, FormValues>;
+
+const valuesToFillOpeningParams = (values: FormValues): FillOpeningParameters => (
+  new FillOpeningParameters({
+    working_group: new WorkingGroup(values.workingGroup),
+    successful_application_id: new ApplicationId(values.successfulApplicant),
+    opening_id: new OpeningId(values.openingId),
+    reward_policy: new (Option.with(RewardPolicy))(
+      values.includeReward
+        ? new RewardPolicy({
+          amount_per_payout: new U128(values.rewardAmount),
+          next_payment_at_block: new U32(values.rewardNextBlock),
+          payout_interval: new (Option.with('BlockNumber'))(
+            values.rewardRecurring ? values.rewardInterval : null
+          ) as Option<BlockNumber>
+        })
+        : null
+    ) as Option<RewardPolicy>
+  })
+);
+
+const FillWorkingGroupLeaderOpeningForm: React.FunctionComponent<FormInnerProps> = props => {
+  const { handleChange, setFieldValue, values, myMemberId, errors, touched } = props;
+  const errorLabelsProps = getFormErrorLabelsProps<FormValues>(errors, touched);
+  const transport = useTransport();
+  const [openings, openingsError, openingsLoading] = usePromise<OpeningData[]>(
+    () => transport.workingGroups.activeOpenings(values.workingGroup, 'ReviewPeriod', 'Leader'),
+    [],
+    [values.workingGroup]
+  );
+  const openingsOptions: DropdownItemProps[] = openings
+    // Map to options
+    .map(od => {
+      const hrt = od.hiringOpening.parse_human_readable_text_with_fallback();
+      return {
+        text: `${od.id.toString()}: ${hrt.headline} (${hrt.job.title})`,
+        value: od.id.toString()
+      };
+    });
+  const [activeApplications, applError, applLoading] = usePromise<ParsedApplication[]>(
+    () => values.openingId !== ''
+      ? transport.workingGroups.openingActiveApplications(values.workingGroup, parseInt(values.openingId))
+      : new Promise((resolve, reject) => resolve([] as ParsedApplication[])),
+    [],
+    [values.workingGroup, values.openingId]
+  );
+  const applicationsOptions = activeApplications
+    .map(a => {
+      return {
+        text: `${a.wgApplicationId}: ${a.member.handle}`,
+        image: a.member.avatar_uri.toString() ? { avatar: true, src: a.member.avatar_uri.toString() } : undefined,
+        description:
+          (a.stakes.application ? `Appl. stake: ${formatBalance(a.stakes.application)}` : '') +
+          (a.stakes.role ? (a.stakes.application && ', ') + `Role stake: ${formatBalance(a.stakes.role)}` : ''),
+        value: a.wgApplicationId.toString()
+      };
+    });
+
+  return (
+    <GenericWorkingGroupProposalForm
+      {...props}
+      txMethod="createFillWorkingGroupLeaderOpeningProposal"
+      proposalType="FillWorkingGroupLeaderOpening"
+      disabled={!openingsOptions.length || !applicationsOptions.length}
+      submitParams={[
+        myMemberId,
+        values.title,
+        values.rationale,
+        '{STAKE}',
+        valuesToFillOpeningParams(values)
+      ]}
+    >
+      <PromiseComponent error={openingsError} loading={openingsLoading} message="Fetching openings...">
+        { !openingsOptions.length
+          ? (
+            <Message error visible>
+              <Message.Header>No openings available!</Message.Header>
+              <Message.Content>
+                This proposal cannot be created, because no leader openings in <i>Review Period</i> are currently available
+                in {values.workingGroup} Working Group.
+              </Message.Content>
+            </Message>
+          )
+          : (
+            <FormField
+              label="Working Group Opening"
+              error={errorLabelsProps.openingId}>
+              <Dropdown
+                onChange={(...args) => {
+                  setFieldValue('successfulApplicants', []);
+                  // "as any" assert is required due to some invalid typing of Formik's "handleChange" function (it takes 2 args, not 1)
+                  return (handleChange as any)(...args);
+                }}
+                placeholder={'Select an opening'}
+                name={'openingId'}
+                selection
+                options={openingsOptions}
+                value={values.openingId}
+              />
+            </FormField>
+          )
+        }
+      </PromiseComponent>
+      { values.openingId && (
+        <PromiseComponent error={applError} loading={applLoading} message="Fetching applications...">
+          { !applicationsOptions.length
+            ? (
+              <Message error visible>
+                <Message.Header>No applications available!</Message.Header>
+                <Message.Content>
+                  FillWorkingGroupLeaderOpening proposal cannot be created for this opening,
+                  because there are no active applications to select from.
+                </Message.Content>
+              </Message>
+            )
+            : (
+              <>
+                <FormField
+                  label="Successful applicant"
+                  error={errorLabelsProps.successfulApplicant}>
+                  <Dropdown
+                    placeholder="Select successful applicant"
+                    fluid
+                    selection
+                    options={applicationsOptions}
+                    value={values.successfulApplicant}
+                    onChange={handleChange}
+                    name="successfulApplicant"/>
+                </FormField>
+                {values.successfulApplicant && (<>
+                  <Header as="h3">Selected applicant:</Header>
+                  <ApplicationsDetails applications={
+                    [activeApplications.find(a => a.wgApplicationId.toString() === values.successfulApplicant)!]
+                  }/>
+                  <Header as="h3">Reward policy:</Header>
+                  <FormField>
+                    <Checkbox
+                      toggle
+                      onChange={(e, data) => { setFieldValue('includeReward', data.checked); }}
+                      label={'Include reward'}
+                      checked={values.includeReward}/>
+                  </FormField>
+                  { values.includeReward && <RewardPolicyFields {...{ values, errorLabelsProps, handleChange, setFieldValue }}/> }
+                </>)}
+              </>
+            )
+          }
+        </PromiseComponent>
+      ) }
+    </GenericWorkingGroupProposalForm>
+  );
+};
+
+const FormContainer = withFormContainer<FormContainerProps, FormValues>({
+  mapPropsToValues: (props: FormContainerProps) => ({
+    ...defaultValues,
+    ...(props.initialData || {})
+  }),
+  validationSchema: (props: FormContainerProps) => Yup.object().shape({
+    ...genericFormDefaultOptions.validationSchema,
+    ...Validation.FillWorkingGroupLeaderOpening(props.currentBlock?.toNumber() || 0)
+  }),
+  handleSubmit: genericFormDefaultOptions.handleSubmit,
+  displayName: 'FillWorkingGroupLeaderOpeningForm'
+})(FillWorkingGroupLeaderOpeningForm);
+
+export default withCalls<ExportComponentProps>(
+  ['derive.chain.bestNumber', { propName: 'currentBlock' }]
+)(
+  withProposalFormData<FormContainerProps, ExportComponentProps>(FormContainer)
+);

+ 82 - 11
pioneer/packages/joy-proposals/src/forms/FormFields.tsx

@@ -1,6 +1,10 @@
 import React from 'react';
-import { Form, FormInputProps, FormTextAreaProps } from 'semantic-ui-react';
+import { Form, FormInputProps, FormTextAreaProps, Label, LabelProps, Checkbox } from 'semantic-ui-react';
+import { FormikProps } from 'formik';
 import LabelWithHelp from './LabelWithHelp';
+import { FormErrorLabelsProps } from './errorHandling';
+import { formatBalance } from '@polkadot/util';
+import styled from 'styled-components';
 
 /*
  * Generic form field components
@@ -10,16 +14,17 @@ import LabelWithHelp from './LabelWithHelp';
  * and to easily switch the structure/display of a typical form field.
 */
 
-type InputFormFieldProps = FormInputProps & {
+type InputFormFieldProps = Omit<FormInputProps, 'error'> & {
   help?: string;
   unit?: string;
+  error?: LabelProps;
 };
 
 export function InputFormField (props: InputFormFieldProps) {
   const { unit } = props;
-  const fieldProps = { ...props, label: undefined };
+  const fieldProps = { ...props, label: undefined, error: undefined };
   return (
-    <FormField {...props}>
+    <FormField {...props} showErrorMsg={true}>
       <Form.Input
         {...fieldProps}
         style={ unit ? { display: 'flex', alignItems: 'center' } : undefined }>
@@ -30,31 +35,97 @@ export function InputFormField (props: InputFormFieldProps) {
   );
 }
 
-type TextareaFormFieldProps = FormTextAreaProps & {
+type TextareaFormFieldProps = Omit<FormTextAreaProps, 'error'> & {
   help?: string;
+  error?: LabelProps;
 };
 
 export function TextareaFormField (props: TextareaFormFieldProps) {
-  const fieldProps = { ...props, label: undefined };
+  const fieldProps = { ...props, label: undefined, error: undefined };
   return (
-    <FormField {...props}>
+    <FormField {...props} showErrorMsg={true}>
       <Form.TextArea {...fieldProps}/>
     </FormField>
   );
 }
 
-type FormFieldProps = InputFormFieldProps | TextareaFormFieldProps;
+type FormFieldProps = Omit<(InputFormFieldProps | TextareaFormFieldProps), 'error'> & {
+  error?: LabelProps;
+  showErrorMsg?: boolean;
+};
+
+const StyledFormField = styled(Form.Field)`
+  & .field {
+    margin-bottom: 0 !important;
+  }
+`;
 
 export function FormField (props: React.PropsWithChildren<FormFieldProps>) {
-  const { error, label, help, children } = props;
+  const { error, showErrorMsg = false, label, help, children } = props;
   return (
-    <Form.Field error={Boolean(error)}>
+    <StyledFormField error={!!error}>
       { (label && help)
         ? <LabelWithHelp text={ label.toString() } help={ help }/>
         : (label ? <label>{ label.toString() }</label> : null)
       }
       { children }
-    </Form.Field>
+      { Boolean(showErrorMsg && error) && <Label {...error} prompt/> }
+    </StyledFormField>
+  );
+}
+
+type ReawrdPolicyFieldsType = {
+  rewardAmount: string;
+  rewardNextBlock: string;
+  rewardRecurring: boolean;
+  rewardInterval: string;
+}
+type RewardPolicyFieldsProps<ValuesT extends ReawrdPolicyFieldsType> =
+  Pick<FormikProps<ValuesT>, 'values' | 'handleChange' | 'setFieldValue'> & {
+    errorLabelsProps: FormErrorLabelsProps<ValuesT>;
+  };
+export function RewardPolicyFields<ValuesT extends ReawrdPolicyFieldsType> ({
+  values,
+  errorLabelsProps,
+  handleChange,
+  setFieldValue
+}: RewardPolicyFieldsProps<ValuesT>) {
+  return (
+    <>
+      <InputFormField
+        label="Amount per payout"
+        unit={formatBalance.getDefaults().unit}
+        onChange={handleChange}
+        name={'rewardAmount'}
+        error={errorLabelsProps.rewardAmount}
+        value={values.rewardAmount}
+        placeholder={'ie. 100'}
+      />
+      <InputFormField
+        label="Next payment at block"
+        onChange={handleChange}
+        name={'rewardNextBlock'}
+        error={errorLabelsProps.rewardNextBlock}
+        value={values.rewardNextBlock}
+      />
+      <FormField>
+        <Checkbox
+          toggle
+          onChange={(e, data) => { setFieldValue('rewardRecurring', data.checked); }}
+          label={'Recurring'}
+          checked={values.rewardRecurring}/>
+      </FormField>
+      { values.rewardRecurring && (
+        <InputFormField
+          label="Reward interval"
+          onChange={handleChange}
+          name={'rewardInterval'}
+          error={errorLabelsProps.rewardInterval}
+          value={values.rewardInterval}
+          unit={'Blocks'}
+        />
+      ) }
+    </>
   );
 }
 

+ 5 - 6
pioneer/packages/joy-proposals/src/forms/GenericProposalForm.tsx

@@ -49,6 +49,7 @@ type GenericProposalFormAdditionalProps = {
   txMethod?: string;
   submitParams?: any[];
   proposalType?: ProposalType;
+  disabled?: boolean;
 };
 
 type GenericFormContainerProps = ProposalFormContainerProps<
@@ -66,10 +67,7 @@ export const genericFormDefaultOptions: GenericFormDefaultOptions = {
     ...(props.initialData || {})
   }),
   validationSchema: {
-
-    title: Validation.All.title,
-    rationale: Validation.All.rationale
-
+    ...Validation.All()
   },
   handleSubmit: (values, { setSubmitting, resetForm }) => {
     // This is handled via TxButton
@@ -96,7 +94,8 @@ export const GenericProposalForm: React.FunctionComponent<GenericFormInnerProps>
     setSubmitting,
     history,
     balances_totalIssuance,
-    proposalType
+    proposalType,
+    disabled = false
   } = props;
   const errorLabelsProps = getFormErrorLabelsProps<GenericFormValues>(errors, touched);
   const [afterSubmit, setAfterSubmit] = useState(null as (() => () => void) | null);
@@ -198,7 +197,7 @@ export const GenericProposalForm: React.FunctionComponent<GenericFormInnerProps>
               type="button" // Tx button uses custom submit handler - "onTxButtonClick"
               label="Submit proposal"
               icon="paper plane"
-              isDisabled={isSubmitting}
+              isDisabled={disabled || isSubmitting}
               params={(submitParams || []).map(p => (p === '{STAKE}' ? requiredStake : p))}
               tx={`proposalsCodex.${txMethod}`}
               txFailedCb={onTxFailed}

+ 47 - 14
pioneer/packages/joy-proposals/src/forms/GenericWorkingGroupProposalForm.tsx

@@ -10,15 +10,16 @@ import {
 } from './GenericProposalForm';
 import { FormField } from './FormFields';
 import { ProposalType } from '@polkadot/joy-utils/types/proposals';
-import { WorkingGroupKeys, WorkingGroupDef } from '@joystream/types/common';
+import { WorkingGroupKey, WorkingGroupDef } from '@joystream/types/common';
 import './forms.css';
 import { Dropdown, Message } from 'semantic-ui-react';
 import { usePromise, useTransport } from '@polkadot/joy-utils/react/hooks';
 import { PromiseComponent } from '@polkadot/joy-utils/react/components';
-import { ProfilePreviewFromStruct as MemberPreview } from '@polkadot/joy-utils/MemberProfilePreview';
+import { WorkerData } from '@polkadot/joy-utils/types/workingGroups';
+import { LeadInfo } from '@polkadot/joy-utils/react/components/working-groups/LeadInfo';
 
 export type FormValues = GenericFormValues & {
-  workingGroup: WorkingGroupKeys;
+  workingGroup: WorkingGroupKey;
 };
 
 export const defaultValues: FormValues = {
@@ -32,6 +33,11 @@ type FormAdditionalProps = {
   submitParams: any[];
   proposalType: ProposalType;
   showLead?: boolean;
+  leadRequired?: boolean;
+  leadStakeRequired?: boolean;
+  leadRewardRequired?: boolean;
+  onLeadChange?: (lead: WorkerData | null) => void;
+  disabled?: boolean;
 };
 
 // We don't exactly use "container" and "export" components here, but those types are useful for
@@ -41,18 +47,34 @@ type FormContainerProps = ProposalFormContainerProps<ExportComponentProps>;
 export type FormInnerProps = ProposalFormInnerProps<FormContainerProps, FormValues>;
 
 export const GenericWorkingGroupProposalForm: React.FunctionComponent<FormInnerProps> = props => {
-  const { handleChange, errors, touched, values, showLead = true } = props;
+  const {
+    handleChange,
+    errors,
+    touched,
+    values,
+    showLead = true,
+    leadRequired = false,
+    leadStakeRequired = false,
+    leadRewardRequired = false,
+    onLeadChange,
+    disabled = false
+  } = props;
   const transport = useTransport();
   const [lead, error, loading] = usePromise(
     () => transport.workingGroups.currentLead(values.workingGroup),
     null,
-    [values.workingGroup]
+    [values.workingGroup],
+    onLeadChange
   );
   const leadRes = { lead, error, loading };
+  const leadMissing = leadRequired && (!leadRes.loading && !leadRes.error) && !leadRes.lead;
+  const stakeMissing = leadStakeRequired && (!leadRes.loading && !leadRes.error) && (leadRes.lead && !leadRes.lead.stake);
+  const rewardMissing = leadRewardRequired && (!leadRes.loading && !leadRes.error) && (leadRes.lead && !leadRes.lead.reward);
+  const isDisabled = disabled || leadMissing || stakeMissing || rewardMissing || leadRes.error;
 
   const errorLabelsProps = getFormErrorLabelsProps<FormValues>(errors, touched);
   return (
-    <GenericProposalForm {...props}>
+    <GenericProposalForm {...props} disabled={isDisabled}>
       <FormField
         error={errorLabelsProps.workingGroup}
         label="Working group"
@@ -68,16 +90,27 @@ export const GenericWorkingGroupProposalForm: React.FunctionComponent<FormInnerP
       </FormField>
       { showLead && (
         <PromiseComponent message={'Fetching current lead...'} {...leadRes}>
-          <Message info>
-            <Message.Content>
-              <Message.Header>Current {values.workingGroup} Working Group lead:</Message.Header>
-              <div style={{ padding: '0.5rem 0' }}>
-                { leadRes.lead ? <MemberPreview profile={leadRes.lead.profile} /> : 'NONE' }
-              </div>
-            </Message.Content>
-          </Message>
+          <LeadInfo lead={leadRes.lead} group={values.workingGroup} header={true}/>
         </PromiseComponent>
       ) }
+      { leadMissing && (
+        <Message error visible>
+          <Message.Header>Leader required</Message.Header>
+          Selected working group has no active leader. An active leader is required in order to create this proposal.
+        </Message>
+      ) }
+      { stakeMissing && (
+        <Message error visible>
+          <Message.Header>No role stake</Message.Header>
+          Selected working group leader has no associated role stake, which is required in order to create this proposal.
+        </Message>
+      ) }
+      { rewardMissing && (
+        <Message error visible>
+          <Message.Header>No reward relationship</Message.Header>
+          Selected working group leader has no reward relationship, which is required in order to create this proposal.
+        </Message>
+      ) }
       { props.children }
     </GenericProposalForm>
   );

+ 2 - 2
pioneer/packages/joy-proposals/src/forms/MintCapacityForm.tsx

@@ -18,7 +18,7 @@ import { ProposalType } from '@polkadot/joy-utils/types/proposals';
 import { formatBalance } from '@polkadot/util';
 import './forms.css';
 
-type FormValues = GenericFormValues & {
+export type FormValues = GenericFormValues & {
   capacity: string;
 };
 
@@ -70,7 +70,7 @@ const FormContainer = withFormContainer<FormContainerProps, FormValues>({
   }),
   validationSchema: Yup.object().shape({
     ...genericFormDefaultOptions.validationSchema,
-    capacity: Validation.SetContentWorkingGroupMintCapacity.mintCapacity
+    ...Validation.SetContentWorkingGroupMintCapacity()
   }),
   handleSubmit: genericFormDefaultOptions.handleSubmit,
   displayName: 'MintCapacityForm'

+ 2 - 2
pioneer/packages/joy-proposals/src/forms/RuntimeUpgradeForm.tsx

@@ -16,7 +16,7 @@ import { withFormContainer } from './FormContainer';
 import './forms.css';
 import FileDropdown from './FileDropdown';
 
-type FormValues = GenericFormValues & {
+export type FormValues = GenericFormValues & {
   // wasm blob as ArrayBuffer, or an Error string
   WASM: ArrayBuffer | string;
 };
@@ -62,7 +62,7 @@ const FormContainer = withFormContainer<FormContainerProps, FormValues>({
   }),
   validationSchema: Yup.object().shape({
     ...genericFormDefaultOptions.validationSchema,
-    WASM: Validation.RuntimeUpgrade.WASM
+    ...Validation.RuntimeUpgrade()
   }),
   handleSubmit: genericFormDefaultOptions.handleSubmit,
   displayName: 'RuntimeUpgradeForm'

+ 4 - 3
pioneer/packages/joy-proposals/src/forms/SetContentWorkingGroupLeadForm.tsx

@@ -21,7 +21,7 @@ import { PromiseComponent } from '@polkadot/joy-utils/react/components';
 import _ from 'lodash';
 import './forms.css';
 
-type FormValues = GenericFormValues & {
+export type FormValues = GenericFormValues & {
   workingGroupLead: any;
 };
 
@@ -120,7 +120,8 @@ const SetContentWorkingGroupsLeadForm: React.FunctionComponent<FormInnerProps> =
             label="New Content Working Group Lead"
             help={
               'The member you propose to set as a new Content Working Group Lead. ' +
-              'Start typing handle or use "id:[ID]" query.'
+              'Start typing handle or use "id:[ID]" query. ' +
+              'Current council members are not allowed to be selected and are excluded from the list.'
             }
           >
             {
@@ -178,7 +179,7 @@ const FormContainer = withFormContainer<FormContainerProps, FormValues>({
   }),
   validationSchema: Yup.object().shape({
     ...genericFormDefaultOptions.validationSchema,
-    workingGroupLead: Validation.SetLead.workingGroupLead
+    ...Validation.SetLead()
   }),
   handleSubmit: genericFormDefaultOptions.handleSubmit,
   displayName: 'SetContentWorkingGroupLeadForm'

+ 2 - 9
pioneer/packages/joy-proposals/src/forms/SetCouncilParamsForm.tsx

@@ -22,7 +22,7 @@ import _ from 'lodash';
 import { ElectionParameters } from '@joystream/types/council';
 import { PromiseComponent } from '@polkadot/joy-utils/react/components';
 
-type FormValues = GenericFormValues & {
+export type FormValues = GenericFormValues & {
   announcingPeriod: string;
   votingPeriod: string;
   minVotingStake: string;
@@ -203,14 +203,7 @@ const FormContainer = withFormContainer<FormContainerProps, FormValues>({
   }),
   validationSchema: Yup.object().shape({
     ...genericFormDefaultOptions.validationSchema,
-    announcingPeriod: Validation.SetElectionParameters.announcingPeriod,
-    votingPeriod: Validation.SetElectionParameters.votingPeriod,
-    minVotingStake: Validation.SetElectionParameters.minVotingStake,
-    revealingPeriod: Validation.SetElectionParameters.revealingPeriod,
-    minCouncilStake: Validation.SetElectionParameters.minCouncilStake,
-    newTermDuration: Validation.SetElectionParameters.newTermDuration,
-    candidacyLimit: Validation.SetElectionParameters.candidacyLimit,
-    councilSize: Validation.SetElectionParameters.councilSize
+    ...Validation.SetElectionParameters()
   }),
   handleSubmit: genericFormDefaultOptions.handleSubmit,
   displayName: 'SetCouncilParamsForm'

+ 3 - 3
pioneer/packages/joy-proposals/src/forms/SetMaxValidatorCountForm.tsx

@@ -17,7 +17,7 @@ import { withFormContainer } from './FormContainer';
 import { useTransport, usePromise } from '@polkadot/joy-utils/react/hooks';
 import './forms.css';
 
-type FormValues = GenericFormValues & {
+export type FormValues = GenericFormValues & {
   maxValidatorCount: string;
 };
 
@@ -33,7 +33,7 @@ type FormInnerProps = ProposalFormInnerProps<FormContainerProps, FormValues>;
 
 const SetMaxValidatorCountForm: React.FunctionComponent<FormInnerProps> = props => {
   const transport = useTransport();
-  const [validatorCount] = usePromise<number>(() => transport.validators.maxCount(), NaN);
+  const [validatorCount] = usePromise<number>(() => transport.validators.maxCount(), 20);
   const { handleChange, errors, touched, values, setFieldValue } = props;
   const errorLabelsProps = getFormErrorLabelsProps<FormValues>(errors, touched);
 
@@ -69,7 +69,7 @@ const FormContainer = withFormContainer<FormContainerProps, FormValues>({
   }),
   validationSchema: Yup.object().shape({
     ...genericFormDefaultOptions.validationSchema,
-    maxValidatorCount: Validation.SetValidatorCount.maxValidatorCount
+    ...Validation.SetValidatorCount()
   }),
   handleSubmit: genericFormDefaultOptions.handleSubmit,
   displayName: 'SetMaxValidatorCountForm'

+ 0 - 256
pioneer/packages/joy-proposals/src/forms/SetStorageRoleParamsForm.tsx

@@ -1,256 +0,0 @@
-import React, { useState, useEffect } from 'react';
-import { Form, Divider } from 'semantic-ui-react';
-import { getFormErrorLabelsProps } from './errorHandling';
-import * as Yup from 'yup';
-import {
-  GenericProposalForm,
-  GenericFormValues,
-  genericFormDefaultOptions,
-  genericFormDefaultValues,
-  withProposalFormData,
-  ProposalFormExportProps,
-  ProposalFormContainerProps,
-  ProposalFormInnerProps
-} from './GenericProposalForm';
-import Validation from '../validationSchema';
-import { InputFormField } from './FormFields';
-import { withFormContainer } from './FormContainer';
-import { BlockNumber, Balance } from '@polkadot/types/interfaces';
-import { u32 } from '@polkadot/types/primitive';
-import { createType } from '@polkadot/types';
-import { useTransport, usePromise } from '@polkadot/joy-utils/react/hooks';
-import { StorageRoleParameters, IStorageRoleParameters } from '@polkadot/joy-utils/types/storageProviders';
-import { formatBalance } from '@polkadot/util';
-import './forms.css';
-
-// Move to joy-types?
-type RoleParameters = {
-  min_stake: Balance;
-  min_actors: u32;
-  max_actors: u32;
-  reward: Balance;
-  reward_period: BlockNumber;
-  bonding_period: BlockNumber;
-  unbonding_period: BlockNumber;
-  min_service_period: BlockNumber;
-  startup_grace_period: BlockNumber;
-  entry_request_fee: Balance;
-};
-
-// All of those are strings, because that's how those values are beeing passed from inputs
-type FormValues = GenericFormValues &
-{
-  [K in keyof RoleParameters]: string;
-};
-
-const defaultValues: FormValues = {
-  ...genericFormDefaultValues,
-  min_stake: '',
-  min_actors: '',
-  max_actors: '',
-  reward: '',
-  reward_period: '',
-  bonding_period: '',
-  unbonding_period: '',
-  min_service_period: '',
-  startup_grace_period: '',
-  entry_request_fee: ''
-};
-
-type FormAdditionalProps = {}; // Aditional props coming all the way from export comonent into the inner form.
-type ExportComponentProps = ProposalFormExportProps<FormAdditionalProps, FormValues>;
-type FormContainerProps = ProposalFormContainerProps<ExportComponentProps>;
-type FormInnerProps = ProposalFormInnerProps<FormContainerProps, FormValues>;
-
-function createRoleParameters (values: FormValues): RoleParameters {
-  return {
-    min_stake: createType('Balance', values.min_stake),
-    min_actors: createType('u32', values.min_actors),
-    max_actors: createType('u32', values.max_actors),
-    reward: createType('Balance', values.reward),
-    reward_period: createType('BlockNumber', values.reward_period),
-    bonding_period: createType('BlockNumber', values.bonding_period),
-    unbonding_period: createType('BlockNumber', values.unbonding_period),
-    min_service_period: createType('BlockNumber', values.min_service_period),
-    startup_grace_period: createType('BlockNumber', values.startup_grace_period),
-    entry_request_fee: createType('Balance', values.entry_request_fee)
-  };
-}
-
-const SetStorageRoleParamsForm: React.FunctionComponent<FormInnerProps> = props => {
-  const transport = useTransport();
-  const [params] = usePromise<IStorageRoleParameters | null>(() => transport.storageProviders.roleParameters(), null);
-  const { handleChange, errors, touched, values, setFieldValue } = props;
-  const [placeholders, setPlaceholders] = useState<{ [k in keyof FormValues]: string }>(defaultValues);
-  const errorLabelsProps = getFormErrorLabelsProps<FormValues>(errors, touched);
-
-  useEffect(() => {
-    if (params) {
-      const stringParams = Object.keys(params).reduce((obj, key) => {
-        return { ...obj, [`${key}`]: String(params[key as keyof IStorageRoleParameters]) };
-      }, {});
-      const fetchedPlaceholders = { ...placeholders, ...stringParams };
-
-      StorageRoleParameters.forEach(field => {
-        setFieldValue(field, params[field].toString());
-      });
-      setPlaceholders(fetchedPlaceholders);
-    }
-  }, [params]);
-
-  return (
-    <GenericProposalForm
-      {...props}
-      txMethod="createSetStorageRoleParametersProposal"
-      proposalType="SetStorageRoleParameters"
-      submitParams={[props.myMemberId, values.title, values.rationale, '{STAKE}', createRoleParameters(values)]}
-    >
-      <Divider horizontal>Parameters</Divider>
-      <Form.Group widths="equal" style={{ marginBottom: '2em' }}>
-        <InputFormField
-          label="Min. actors"
-          help="Minimum number of actors in this role"
-          onChange={handleChange}
-          name="min_actors"
-          placeholder={placeholders.min_actors}
-          error={errorLabelsProps.min_actors}
-          value={values.min_actors}
-          disabled
-        />
-        <InputFormField
-          label="Max. actors"
-          help="Maximum number of actors in this role"
-          fluid
-          onChange={handleChange}
-          name="max_actors"
-          placeholder={placeholders.max_actors}
-          error={errorLabelsProps.max_actors}
-          value={values.max_actors}
-        />
-      </Form.Group>
-      <Form.Group widths="equal" style={{ marginBottom: '2em' }}>
-        <InputFormField
-          label="Reward"
-          help="Reward for performing this role (for each period)"
-          fluid
-          onChange={handleChange}
-          name="reward"
-          placeholder={placeholders.reward}
-          error={errorLabelsProps.reward}
-          value={values.reward}
-          unit={ formatBalance.getDefaults().unit }
-        />
-        <InputFormField
-          label="Reward period"
-          help="Reward period in blocks"
-          fluid
-          onChange={handleChange}
-          name="reward_period"
-          placeholder={placeholders.reward_period}
-          error={errorLabelsProps.reward_period}
-          value={values.reward_period}
-          unit="blocks"
-          disabled
-        />
-      </Form.Group>
-      <Form.Group widths="equal" style={{ marginBottom: '2em' }}>
-        <InputFormField
-          label="Min. stake"
-          help="Minimum stake for this role"
-          onChange={handleChange}
-          name="min_stake"
-          placeholder={placeholders.min_stake}
-          error={errorLabelsProps.min_stake}
-          value={values.min_stake}
-          unit={ formatBalance.getDefaults().unit }
-        />
-        <InputFormField
-          label="Min. service period"
-          help="Minimum period of service in blocks"
-          fluid
-          onChange={handleChange}
-          name="min_service_period"
-          placeholder={placeholders.min_service_period}
-          error={errorLabelsProps.min_service_period}
-          value={values.min_service_period}
-          unit="blocks"
-          disabled
-        />
-      </Form.Group>
-      <Form.Group widths="equal" style={{ marginBottom: '2em' }}>
-        <InputFormField
-          label="Bonding period"
-          help="Bonding period in blocks"
-          fluid
-          onChange={handleChange}
-          name="bonding_period"
-          placeholder={placeholders.bonding_period}
-          error={errorLabelsProps.bonding_period}
-          value={values.bonding_period}
-          unit="blocks"
-          disabled
-        />
-        <InputFormField
-          label="Unbounding period"
-          help="Unbounding period in blocks"
-          fluid
-          onChange={handleChange}
-          name="unbonding_period"
-          placeholder={placeholders.unbonding_period}
-          error={errorLabelsProps.unbonding_period}
-          value={values.unbonding_period}
-          unit="blocks"
-        />
-      </Form.Group>
-      <Form.Group widths="equal" style={{ marginBottom: '2em' }}>
-        <InputFormField
-          label="Startup grace period"
-          help="Startup grace period in blocks"
-          fluid
-          onChange={handleChange}
-          name="startup_grace_period"
-          placeholder={placeholders.startup_grace_period}
-          error={errorLabelsProps.startup_grace_period}
-          value={values.startup_grace_period}
-          unit="blocks"
-          disabled
-        />
-        <InputFormField
-          label="Entry request fee"
-          help="Entry request fee"
-          fluid
-          onChange={handleChange}
-          name="entry_request_fee"
-          placeholder={placeholders.entry_request_fee}
-          error={errorLabelsProps.entry_request_fee}
-          value={values.entry_request_fee}
-          unit={ formatBalance.getDefaults().unit }
-        />
-      </Form.Group>
-    </GenericProposalForm>
-  );
-};
-
-const FormContainer = withFormContainer<FormContainerProps, FormValues>({
-  mapPropsToValues: (props: FormContainerProps) => ({
-    ...defaultValues,
-    ...(props.initialData || {})
-  }),
-  validationSchema: Yup.object().shape({
-    ...genericFormDefaultOptions.validationSchema,
-    min_stake: Validation.SetStorageRoleParameters.min_stake,
-    min_actors: Validation.SetStorageRoleParameters.min_actors,
-    max_actors: Validation.SetStorageRoleParameters.max_actors,
-    reward: Validation.SetStorageRoleParameters.reward,
-    reward_period: Validation.SetStorageRoleParameters.reward_period,
-    bonding_period: Validation.SetStorageRoleParameters.bonding_period,
-    unbonding_period: Validation.SetStorageRoleParameters.unbonding_period,
-    min_service_period: Validation.SetStorageRoleParameters.min_service_period,
-    startup_grace_period: Validation.SetStorageRoleParameters.startup_grace_period,
-    entry_request_fee: Validation.SetStorageRoleParameters.entry_request_fee
-  }),
-  handleSubmit: genericFormDefaultOptions.handleSubmit,
-  displayName: 'SetStorageRoleParamsForm'
-})(SetStorageRoleParamsForm);
-
-export default withProposalFormData(FormContainer);

+ 93 - 0
pioneer/packages/joy-proposals/src/forms/SetWorkingGroupLeadRewardForm.tsx

@@ -0,0 +1,93 @@
+import React, { useState } from 'react';
+import { getFormErrorLabelsProps } from './errorHandling';
+import * as Yup from 'yup';
+import {
+  withProposalFormData,
+  ProposalFormExportProps,
+  ProposalFormContainerProps,
+  ProposalFormInnerProps,
+  genericFormDefaultOptions
+} from './GenericProposalForm';
+import {
+  GenericWorkingGroupProposalForm,
+  FormValues as WGFormValues,
+  defaultValues as wgFromDefaultValues
+} from './GenericWorkingGroupProposalForm';
+import { InputFormField } from './FormFields';
+import { withFormContainer } from './FormContainer';
+import './forms.css';
+import { Grid } from 'semantic-ui-react';
+import { formatBalance } from '@polkadot/util';
+import _ from 'lodash';
+import Validation from '../validationSchema';
+import { WorkerData } from '@polkadot/joy-utils/types/workingGroups';
+
+export type FormValues = WGFormValues & {
+  amount: string;
+};
+
+const defaultValues: FormValues = {
+  ...wgFromDefaultValues,
+  amount: ''
+};
+
+type FormAdditionalProps = {}; // Aditional props coming all the way from export component into the inner form.
+type ExportComponentProps = ProposalFormExportProps<FormAdditionalProps, FormValues>;
+type FormContainerProps = ProposalFormContainerProps<ExportComponentProps>;
+type FormInnerProps = ProposalFormInnerProps<FormContainerProps, FormValues>;
+
+const SetWorkingGroupLeadRewardForm: React.FunctionComponent<FormInnerProps> = props => {
+  const { handleChange, errors, touched, values, myMemberId } = props;
+  const errorLabelsProps = getFormErrorLabelsProps<FormValues>(errors, touched);
+  const [lead, setLead] = useState<WorkerData | null>(null);
+
+  return (
+    <GenericWorkingGroupProposalForm
+      {...props}
+      txMethod="createSetWorkingGroupLeaderRewardProposal"
+      proposalType="SetWorkingGroupLeaderReward"
+      leadRequired={true}
+      leadRewardRequired={true}
+      onLeadChange={(lead: WorkerData | null) => setLead(lead)}
+      submitParams={[
+        myMemberId,
+        values.title,
+        values.rationale,
+        '{STAKE}',
+        lead?.workerId,
+        values.amount,
+        values.workingGroup
+      ]}
+    >
+      { (lead && lead.reward) && (
+        <Grid columns="4" doubling stackable verticalAlign="bottom">
+          <Grid.Column>
+            <InputFormField
+              label="New reward amount"
+              onChange={handleChange}
+              name="amount"
+              error={errorLabelsProps.amount}
+              value={values.amount}
+              unit={formatBalance.getDefaults().unit}
+            />
+          </Grid.Column>
+        </Grid>
+      ) }
+    </GenericWorkingGroupProposalForm>
+  );
+};
+
+const FormContainer = withFormContainer<FormContainerProps, FormValues>({
+  mapPropsToValues: (props: FormContainerProps) => ({
+    ...defaultValues,
+    ...(props.initialData || {})
+  }),
+  validationSchema: Yup.object().shape({
+    ...genericFormDefaultOptions.validationSchema,
+    ...Validation.SetWorkingGroupLeaderReward()
+  }),
+  handleSubmit: genericFormDefaultOptions.handleSubmit,
+  displayName: 'SetWorkingGroupLeadRewardForm'
+})(SetWorkingGroupLeadRewardForm);
+
+export default withProposalFormData<FormContainerProps, ExportComponentProps>(FormContainer);

+ 86 - 0
pioneer/packages/joy-proposals/src/forms/SetWorkingGroupMintCapacityForm.tsx

@@ -0,0 +1,86 @@
+import React from 'react';
+import { getFormErrorLabelsProps } from './errorHandling';
+import * as Yup from 'yup';
+import {
+  withProposalFormData,
+  ProposalFormExportProps,
+  ProposalFormContainerProps,
+  ProposalFormInnerProps,
+  genericFormDefaultOptions
+} from './GenericProposalForm';
+import {
+  GenericWorkingGroupProposalForm,
+  FormValues as WGFormValues,
+  defaultValues as wgFromDefaultValues
+} from './GenericWorkingGroupProposalForm';
+import { InputFormField } from './FormFields';
+import { withFormContainer } from './FormContainer';
+import './forms.css';
+import { Grid } from 'semantic-ui-react';
+import { formatBalance } from '@polkadot/util';
+import _ from 'lodash';
+import Validation from '../validationSchema';
+
+export type FormValues = WGFormValues & {
+  capacity: string;
+};
+
+const defaultValues: FormValues = {
+  ...wgFromDefaultValues,
+  capacity: ''
+};
+
+type FormAdditionalProps = {}; // Aditional props coming all the way from export component into the inner form.
+type ExportComponentProps = ProposalFormExportProps<FormAdditionalProps, FormValues>;
+type FormContainerProps = ProposalFormContainerProps<ExportComponentProps>;
+type FormInnerProps = ProposalFormInnerProps<FormContainerProps, FormValues>;
+
+const SetWorkingGroupMintCapacityForm: React.FunctionComponent<FormInnerProps> = props => {
+  const { handleChange, errors, touched, values, myMemberId } = props;
+  const errorLabelsProps = getFormErrorLabelsProps<FormValues>(errors, touched);
+
+  return (
+    <GenericWorkingGroupProposalForm
+      {...props}
+      txMethod="createSetWorkingGroupMintCapacityProposal"
+      proposalType="SetWorkingGroupMintCapacity"
+      submitParams={[
+        myMemberId,
+        values.title,
+        values.rationale,
+        '{STAKE}',
+        values.capacity,
+        values.workingGroup
+      ]}
+    >
+      <Grid columns="4" doubling stackable verticalAlign="bottom">
+        <Grid.Column>
+          <InputFormField
+            label="Mint capacity"
+            onChange={handleChange}
+            name="capacity"
+            error={errorLabelsProps.capacity}
+            value={values.capacity}
+            placeholder={'ie. 100000'}
+            unit={formatBalance.getDefaults().unit}
+          />
+        </Grid.Column>
+      </Grid>
+    </GenericWorkingGroupProposalForm>
+  );
+};
+
+const FormContainer = withFormContainer<FormContainerProps, FormValues>({
+  mapPropsToValues: (props: FormContainerProps) => ({
+    ...defaultValues,
+    ...(props.initialData || {})
+  }),
+  validationSchema: Yup.object().shape({
+    ...genericFormDefaultOptions.validationSchema,
+    ...Validation.SetWorkingGroupMintCapacity()
+  }),
+  handleSubmit: genericFormDefaultOptions.handleSubmit,
+  displayName: 'SetWorkingGroupMintCapacityForm'
+})(SetWorkingGroupMintCapacityForm);
+
+export default withProposalFormData<FormContainerProps, ExportComponentProps>(FormContainer);

+ 2 - 2
pioneer/packages/joy-proposals/src/forms/SignalForm.tsx

@@ -16,7 +16,7 @@ import { TextareaFormField } from './FormFields';
 import { withFormContainer } from './FormContainer';
 import './forms.css';
 
-type FormValues = GenericFormValues & {
+export type FormValues = GenericFormValues & {
   description: string;
 };
 
@@ -61,7 +61,7 @@ const FormContainer = withFormContainer<FormContainerProps, FormValues>({
   }),
   validationSchema: Yup.object().shape({
     ...genericFormDefaultOptions.validationSchema,
-    description: Validation.Text.description
+    ...Validation.Text()
   }),
   handleSubmit: genericFormDefaultOptions.handleSubmit,
   displayName: 'SignalForm'

+ 101 - 0
pioneer/packages/joy-proposals/src/forms/SlashWorkingGroupLeadStakeForm.tsx

@@ -0,0 +1,101 @@
+import React, { useState, useEffect } from 'react';
+import { getFormErrorLabelsProps } from './errorHandling';
+import * as Yup from 'yup';
+import {
+  withProposalFormData,
+  ProposalFormExportProps,
+  ProposalFormContainerProps,
+  ProposalFormInnerProps,
+  genericFormDefaultOptions
+} from './GenericProposalForm';
+import {
+  GenericWorkingGroupProposalForm,
+  FormValues as WGFormValues,
+  defaultValues as wgFromDefaultValues
+} from './GenericWorkingGroupProposalForm';
+import { InputFormField } from './FormFields';
+import { withFormContainer } from './FormContainer';
+import './forms.css';
+import { Grid } from 'semantic-ui-react';
+import { formatBalance } from '@polkadot/util';
+import _ from 'lodash';
+import Validation from '../validationSchema';
+import { WorkerData } from '@polkadot/joy-utils/types/workingGroups';
+
+export type FormValues = WGFormValues & {
+  amount: string;
+};
+
+const defaultValues: FormValues = {
+  ...wgFromDefaultValues,
+  amount: ''
+};
+
+type FormAdditionalProps = {}; // Aditional props coming all the way from export component into the inner form.
+type ExportComponentProps = ProposalFormExportProps<FormAdditionalProps, FormValues>;
+type FormContainerProps = ProposalFormContainerProps<ExportComponentProps>;
+type FormInnerProps = ProposalFormInnerProps<FormContainerProps, FormValues>;
+
+const SlashWorkingGroupLeadStakeForm: React.FunctionComponent<FormInnerProps> = props => {
+  const { handleChange, errors, touched, values, myMemberId, setFieldError } = props;
+  const errorLabelsProps = getFormErrorLabelsProps<FormValues>(errors, touched);
+  const [lead, setLead] = useState<WorkerData | null>(null);
+  // Here we validate if stake <= current lead stake.
+  // Because it depends on selected working group,
+  // there's no easy way to do it using validationSchema
+  useEffect(() => {
+    if (lead && parseInt(values.amount) > (lead.stake || 0) && !errors.amount) {
+      setFieldError('amount', `The stake cannot exceed current leader's stake (${formatBalance(lead.stake)})`);
+    }
+  });
+
+  return (
+    <GenericWorkingGroupProposalForm
+      {...props}
+      txMethod="createSlashWorkingGroupLeaderStakeProposal"
+      proposalType="SlashWorkingGroupLeaderStake"
+      leadRequired={true}
+      leadStakeRequired={true}
+      onLeadChange={(lead: WorkerData | null) => setLead(lead)}
+      submitParams={[
+        myMemberId,
+        values.title,
+        values.rationale,
+        '{STAKE}',
+        lead?.workerId,
+        values.amount,
+        values.workingGroup
+      ]}
+    >
+      { (lead && lead.stake) && (
+        <Grid columns="4" doubling stackable verticalAlign="bottom">
+          <Grid.Column>
+            <InputFormField
+              label="Amount to slash"
+              onChange={handleChange}
+              name="amount"
+              error={errorLabelsProps.amount}
+              value={values.amount}
+              unit={formatBalance.getDefaults().unit}
+            />
+          </Grid.Column>
+        </Grid>
+      ) }
+    </GenericWorkingGroupProposalForm>
+  );
+};
+
+const FormContainer = withFormContainer<FormContainerProps, FormValues>({
+  mapPropsToValues: (props: FormContainerProps) => ({
+    ...defaultValues,
+    ...(props.initialData || {})
+  }),
+  validationSchema: Yup.object().shape({
+    ...genericFormDefaultOptions.validationSchema,
+    ...Validation.SlashWorkingGroupLeaderStake()
+  }),
+  handleSubmit: genericFormDefaultOptions.handleSubmit,
+  displayName: 'SlashWorkingGroupLeadStakeForm'
+})(SlashWorkingGroupLeadStakeForm);
+
+export default withProposalFormData<FormContainerProps, ExportComponentProps>(FormContainer);

+ 2 - 3
pioneer/packages/joy-proposals/src/forms/SpendingProposalForm.tsx

@@ -19,7 +19,7 @@ import { InputAddress } from '@polkadot/react-components/index';
 import { formatBalance } from '@polkadot/util';
 import './forms.css';
 
-type FormValues = GenericFormValues & {
+export type FormValues = GenericFormValues & {
   destinationAccount: any;
   tokens: string;
 };
@@ -86,8 +86,7 @@ const FormContainer = withFormContainer<FormContainerProps, FormValues>({
   }),
   validationSchema: Yup.object().shape({
     ...genericFormDefaultOptions.validationSchema,
-    tokens: Validation.Spending.tokens,
-    destinationAccount: Validation.Spending.destinationAccount
+    ...Validation.Spending()
   }),
   handleSubmit: genericFormDefaultOptions.handleSubmit,
   displayName: 'SpendingProposalsForm'

+ 125 - 0
pioneer/packages/joy-proposals/src/forms/TerminateWorkingGroupLeaderForm.tsx

@@ -0,0 +1,125 @@
+import React, { useState } from 'react';
+import * as Yup from 'yup';
+import {
+  withProposalFormData,
+  ProposalFormExportProps,
+  ProposalFormContainerProps,
+  ProposalFormInnerProps,
+  genericFormDefaultOptions
+} from './GenericProposalForm';
+import {
+  GenericWorkingGroupProposalForm,
+  FormValues as WGFormValues,
+  defaultValues as wgFromDefaultValues
+} from './GenericWorkingGroupProposalForm';
+import { withFormContainer } from './FormContainer';
+import './forms.css';
+import _ from 'lodash';
+import Validation from '../validationSchema';
+import { WorkerData } from '@polkadot/joy-utils/types/workingGroups';
+import { getFormErrorLabelsProps } from './errorHandling';
+import FormField, { TextareaFormField } from './FormFields';
+import { Checkbox } from 'semantic-ui-react';
+import { TerminateRoleParameters } from '@joystream/types/proposals';
+import { WorkerId } from '@joystream/types/working-group';
+import { Bytes } from '@polkadot/types';
+import { WorkingGroup, InputValidationLengthConstraint } from '@joystream/types/common';
+import { bool as Bool } from '@polkadot/types/primitive';
+import { withCalls } from '@polkadot/react-api';
+import { formatBalance } from '@polkadot/util';
+
+export type FormValues = WGFormValues & {
+  terminationRationale: string;
+  slashStake: boolean;
+};
+
+const defaultValues: FormValues = {
+  ...wgFromDefaultValues,
+  terminationRationale: '',
+  slashStake: false
+};
+
+type FormAdditionalProps = {}; // Aditional props coming all the way from export component into the inner form.
+type ExportComponentProps = ProposalFormExportProps<FormAdditionalProps, FormValues>;
+type FormContainerProps = ProposalFormContainerProps<ExportComponentProps> & {
+  terminationRationaleConstraint?: InputValidationLengthConstraint;
+};
+type FormInnerProps = ProposalFormInnerProps<FormContainerProps, FormValues>;
+
+const valuesToTerminateRoleParams = (values: FormValues, lead: WorkerData): TerminateRoleParameters => {
+  return new TerminateRoleParameters({
+    worker_id: new WorkerId(lead.workerId),
+    rationale: new Bytes(values.terminationRationale),
+    slash: lead.stake ? new Bool(values.slashStake) : new Bool(false),
+    working_group: new WorkingGroup(values.workingGroup)
+  });
+};
+
+const TerminateWorkingGroupLeaderForm: React.FunctionComponent<FormInnerProps> = props => {
+  const { handleChange, errors, touched, values, myMemberId, setFieldValue } = props;
+  const errorLabelsProps = getFormErrorLabelsProps<FormValues>(errors, touched);
+  const [lead, setLead] = useState<WorkerData | null>(null);
+
+  return (
+    <GenericWorkingGroupProposalForm
+      {...props}
+      txMethod="createTerminateWorkingGroupLeaderRoleProposal"
+      proposalType="TerminateWorkingGroupLeaderRole"
+      leadRequired={true}
+      onLeadChange={(lead: WorkerData | null) => setLead(lead)}
+      submitParams={[
+        myMemberId,
+        values.title,
+        values.rationale,
+        '{STAKE}',
+        lead && valuesToTerminateRoleParams(values, lead)
+      ]}
+    >
+      { lead && (<>
+        <TextareaFormField
+          label="Termination rationale"
+          help={
+            'This rationale is an required argument of "terminateWorkerRole" extrinsic, ' +
+            'it may differ from proposal rationale and has different length constraints. ' +
+            'If the propsal gets executed, this rationale will become part of "TerminatedLeader" event.'
+          }
+          onChange={handleChange}
+          name="terminationRationale"
+          placeholder="Provide a clear rationale for terminating the leader role..."
+          error={errorLabelsProps.terminationRationale}
+          value={values.terminationRationale}
+        />
+        { lead.stake && (
+          <FormField>
+            <Checkbox
+              toggle
+              onChange={(e, data) => { setFieldValue('slashStake', data.checked); }}
+              label={ `Slash leader stake (${formatBalance(lead.stake)})` }
+              checked={values.slashStake}/>
+          </FormField>
+        ) }
+      </>) }
+    </GenericWorkingGroupProposalForm>
+  );
+};
+
+const FormContainer = withFormContainer<FormContainerProps, FormValues>({
+  mapPropsToValues: (props: FormContainerProps) => ({
+    ...defaultValues,
+    ...(props.initialData || {})
+  }),
+  validationSchema: (props: FormContainerProps) => Yup.object().shape({
+    ...genericFormDefaultOptions.validationSchema,
+    ...Validation.TerminateWorkingGroupLeaderRole(
+      props.terminationRationaleConstraint || InputValidationLengthConstraint.createWithMaxAllowed()
+    )
+  }),
+  handleSubmit: genericFormDefaultOptions.handleSubmit,
+  displayName: 'TerminateWorkingGroupLeaderForm'
+})(TerminateWorkingGroupLeaderForm);
+
+export default withCalls<ExportComponentProps>(
+  ['query.storageWorkingGroup.workerExitRationaleText', { propName: 'terminationRationaleConstraint' }]
+)(
+  withProposalFormData<FormContainerProps, ExportComponentProps>(FormContainer)
+);

+ 4 - 4
pioneer/packages/joy-proposals/src/forms/errorHandling.ts

@@ -1,7 +1,7 @@
 import { FormikErrors, FormikTouched } from 'formik';
 import { LabelProps } from 'semantic-ui-react';
 
-type FieldErrorLabelProps = LabelProps | null; // This is used for displaying semantic-ui errors
+type FieldErrorLabelProps = LabelProps | undefined; // This is used for displaying semantic-ui errors
 export type FormErrorLabelsProps<ValuesT> = { [T in keyof ValuesT]: FieldErrorLabelProps };
 
 // Single form field error state.
@@ -13,10 +13,10 @@ export function getErrorLabelProps<ValuesT> (
   fieldName: keyof ValuesT,
   pointing: LabelProps['pointing'] = undefined
 
-): FieldErrorLabelProps {
+): FieldErrorLabelProps | undefined {
   return (errors[fieldName] && touched[fieldName])
-    ? { content: errors[fieldName], pointing }
-    : null;
+    ? { content: errors[fieldName], pointing, size: 'large' }
+    : undefined;
 }
 
 // All form fields error states (uses default value for "pointing").

+ 7 - 2
pioneer/packages/joy-proposals/src/forms/index.ts

@@ -1,12 +1,17 @@
 export { default as SignalForm } from './SignalForm';
 export { default as SpendingProposalForm } from './SpendingProposalForm';
-export { default as EvictStorageProviderForm } from './EvictStorageProviderForm';
 export { default as MintCapacityForm } from './MintCapacityForm';
 export { default as SetCouncilParamsForm } from './SetCouncilParamsForm';
 export { default as SetContentWorkingGroupLeadForm } from './SetContentWorkingGroupLeadForm';
-export { default as SetStorageRoleParamsForm } from './SetStorageRoleParamsForm';
 export { default as RuntimeUpgradeForm } from './RuntimeUpgradeForm';
 export { default as SetContentWorkingGroupMintCapForm } from './SetContentWorkingGroupMintCapForm';
 export { default as SetCouncilMintCapForm } from './SetCouncilMintCapForm';
 export { default as SetMaxValidatorCountForm } from './SetMaxValidatorCountForm';
 export { default as AddWorkingGroupOpeningForm } from './AddWorkingGroupOpeningForm';
+export { default as SetWorkingGroupMintCapacityForm } from './SetWorkingGroupMintCapacityForm';
+export { default as BeginReviewLeaderApplicationsForm } from './BeginReviewLeaderApplicationsForm';
+export { default as FillWorkingGroupLeaderOpeningForm } from './FillWorkingGroupLeaderOpeningForm';
+export { default as DecreaseWorkingGroupLeadStakeFrom } from './DecreaseWorkingGroupLeadStakeForm';
+export { default as SlashWorkingGroupLeadStakeForm } from './SlashWorkingGroupLeadStakeForm';
+export { default as SetWorkingGroupLeadRewardForm } from './SetWorkingGroupLeadRewardForm';
+export { default as TerminateWorkingGroupLeaderForm } from './TerminateWorkingGroupLeaderForm';

+ 25 - 5
pioneer/packages/joy-proposals/src/index.tsx

@@ -7,6 +7,7 @@ import { Breadcrumb } from 'semantic-ui-react';
 import { AppProps, I18nProps } from '@polkadot/react-components/types';
 import { TransportProvider } from '@polkadot/joy-utils/react/context';
 import { ProposalPreviewList, ProposalFromId, ChooseProposalType } from './Proposal';
+import _ from 'lodash';
 
 import './index.css';
 
@@ -14,15 +15,20 @@ import translate from './translate';
 import NotDone from './NotDone';
 import {
   SignalForm,
-  EvictStorageProviderForm,
   SpendingProposalForm,
   SetContentWorkingGroupLeadForm,
   SetContentWorkingGroupMintCapForm,
   SetCouncilParamsForm,
-  SetStorageRoleParamsForm,
   SetMaxValidatorCountForm,
   RuntimeUpgradeForm,
-  AddWorkingGroupOpeningForm
+  AddWorkingGroupOpeningForm,
+  SetWorkingGroupMintCapacityForm,
+  BeginReviewLeaderApplicationsForm,
+  FillWorkingGroupLeaderOpeningForm,
+  DecreaseWorkingGroupLeadStakeFrom,
+  SlashWorkingGroupLeadStakeForm,
+  SetWorkingGroupLeadRewardForm,
+  TerminateWorkingGroupLeaderForm
 } from './forms';
 
 interface Props extends AppProps, I18nProps {}
@@ -45,6 +51,15 @@ function App (props: Props): React.ReactElement<Props> {
         <StyledHeader>
           <Breadcrumb>
             <Switch>
+              <Route path={`${basePath}/new/:type`} render={props => (
+                <>
+                  <Breadcrumb.Section link as={Link} to={basePath}>Proposals</Breadcrumb.Section>
+                  <Breadcrumb.Divider icon="right angle" />
+                  <Breadcrumb.Section link as={Link} to={`${basePath}/new`}>New proposal</Breadcrumb.Section>
+                  <Breadcrumb.Divider icon="right angle" />
+                  <Breadcrumb.Section active>{_.startCase(props.match.params.type)}</Breadcrumb.Section>
+                </>
+              )} />
               <Route path={`${basePath}/new`}>
                 <Breadcrumb.Section link as={Link} to={basePath}>Proposals</Breadcrumb.Section>
                 <Breadcrumb.Divider icon="right angle" />
@@ -68,10 +83,15 @@ function App (props: Props): React.ReactElement<Props> {
             path={`${basePath}/new/set-content-working-group-mint-capacity`}
             component={SetContentWorkingGroupMintCapForm}
           />
-          <Route exact path={`${basePath}/new/evict-storage-provider`} component={EvictStorageProviderForm} />
           <Route exact path={`${basePath}/new/set-validator-count`} component={SetMaxValidatorCountForm} />
-          <Route exact path={`${basePath}/new/set-storage-role-parameters`} component={SetStorageRoleParamsForm} />
           <Route exact path={`${basePath}/new/add-working-group-leader-opening`} component={AddWorkingGroupOpeningForm} />
+          <Route exact path={`${basePath}/new/set-working-group-mint-capacity`} component={SetWorkingGroupMintCapacityForm} />
+          <Route exact path={`${basePath}/new/begin-review-working-group-leader-application`} component={BeginReviewLeaderApplicationsForm} />
+          <Route exact path={`${basePath}/new/fill-working-group-leader-opening`} component={FillWorkingGroupLeaderOpeningForm} />
+          <Route exact path={`${basePath}/new/decrease-working-group-leader-stake`} component={DecreaseWorkingGroupLeadStakeFrom} />
+          <Route exact path={`${basePath}/new/slash-working-group-leader-stake`} component={SlashWorkingGroupLeadStakeForm} />
+          <Route exact path={`${basePath}/new/set-working-group-leader-reward`} component={SetWorkingGroupLeadRewardForm} />
+          <Route exact path={`${basePath}/new/terminate-working-group-leader-role`} component={TerminateWorkingGroupLeaderForm} />
           <Route exact path={`${basePath}/active`} component={NotDone} />
           <Route exact path={`${basePath}/finalized`} component={NotDone} />
           <Route exact path={`${basePath}/:id`} component={ProposalFromId} />

+ 0 - 6
pioneer/packages/joy-proposals/src/stories/ProposalForms.stories.tsx

@@ -1,11 +1,9 @@
 import '../index.css';
 import {
   SignalForm,
-  EvictStorageProviderForm,
   SpendingProposalForm,
   SetCouncilParamsForm,
   SetContentWorkingGroupLeadForm,
-  SetStorageRoleParamsForm,
   RuntimeUpgradeForm,
   SetContentWorkingGroupMintCapForm,
   SetCouncilMintCapForm,
@@ -19,16 +17,12 @@ export default {
 
 export const Signal = () => withMock(SignalForm);
 
-export const StorageProviders = () => withMock(EvictStorageProviderForm);
-
 export const SpendingProposal = () => withMock(SpendingProposalForm);
 
 export const SetCouncilParams = () => withMock(SetCouncilParamsForm);
 
 export const SetContentWorkingGroupLead = () => withMock(SetContentWorkingGroupLeadForm);
 
-export const SetStorageRoleParams = () => withMock(SetStorageRoleParamsForm);
-
 export const RuntimeUpgrade = () => withMock(RuntimeUpgradeForm);
 
 export const ContentWorkingGroupMintCap = () => withMock(SetContentWorkingGroupMintCapForm);

+ 3 - 3
pioneer/packages/joy-proposals/src/stories/data/ProposalTypesInfo.mock.ts

@@ -1,5 +1,5 @@
 import { ProposalTypeInfo } from '../../Proposal/ProposalTypePreview';
-import { Categories } from '../../Proposal/ChooseProposalType';
+import { Categories } from '@polkadot/joy-utils/types/proposals';
 
 const MockProposalTypesInfo: ProposalTypeInfo[] = [
   {
@@ -52,7 +52,7 @@ const MockProposalTypesInfo: ProposalTypeInfo[] = [
   },
   {
     type: 'EvictStorageProvider',
-    category: Categories.storage,
+    category: Categories.other,
     description:
         'Change the total reward across all validators in a given block.' +
         'This is not the direct reward, but base reward for Pallet staking module.' +
@@ -68,7 +68,7 @@ const MockProposalTypesInfo: ProposalTypeInfo[] = [
   },
   {
     type: 'SetStorageRoleParameters',
-    category: Categories.storage,
+    category: Categories.other,
     description:
         'Change the total reward across all validators in a given block.' +
         'This is not the direct reward, but base reward for Pallet staking module.' +

+ 163 - 185
pioneer/packages/joy-proposals/src/validationSchema.ts

@@ -1,5 +1,23 @@
 import * as Yup from 'yup';
 import { schemaValidator, ActivateOpeningAtKeys } from '@joystream/types/hiring';
+import { ProposalTypes } from '@polkadot/joy-utils/types/proposals';
+import { GenericFormValues } from './forms/GenericProposalForm';
+import { InputValidationLengthConstraint } from '@joystream/types/common';
+import { FormValues as SignalFormValues } from './forms/SignalForm';
+import { FormValues as RuntimeUpgradeFormValues } from './forms/RuntimeUpgradeForm';
+import { FormValues as SetCouncilParamsFormValues } from './forms/SetCouncilParamsForm';
+import { FormValues as SpendingProposalFormValues } from './forms/SpendingProposalForm';
+import { FormValues as SetContentWorkingGroupLeadFormValues } from './forms/SetContentWorkingGroupLeadForm';
+import { FormValues as SetContentWorkingGroupMintCapacityFormValues } from './forms/MintCapacityForm';
+import { FormValues as SetMaxValidatorCountFormValues } from './forms/SetMaxValidatorCountForm';
+import { FormValues as AddWorkingGroupLeaderOpeningFormValues } from './forms/AddWorkingGroupOpeningForm';
+import { FormValues as SetWorkingGroupMintCapacityFormValues } from './forms/SetWorkingGroupMintCapacityForm';
+import { FormValues as BeginReviewLeaderApplicationsFormValues } from './forms/BeginReviewLeaderApplicationsForm';
+import { FormValues as FillWorkingGroupLeaderOpeningFormValues } from './forms/FillWorkingGroupLeaderOpeningForm';
+import { FormValues as DecreaseWorkingGroupLeadStakeFormValues } from './forms/DecreaseWorkingGroupLeadStakeForm';
+import { FormValues as SlashWorkingGroupLeadStakeFormValues } from './forms/SlashWorkingGroupLeadStakeForm';
+import { FormValues as SetWorkingGroupLeadRewardFormValues } from './forms/SetWorkingGroupLeadRewardForm';
+import { FormValues as TerminateWorkingGroupLeaderFormValues } from './forms/TerminateWorkingGroupLeaderForm';
 
 // TODO: If we really need this (currency unit) we can we make "Validation" a functiction that returns an object.
 // We could then "instantialize" it in "withFormContainer" where instead of passing
@@ -49,28 +67,6 @@ const MAX_VALIDATOR_COUNT_MAX = 100;
 const MINT_CAPACITY_MIN = 0;
 const MINT_CAPACITY_MAX = 1000000;
 
-// Set Storage Role Parameters
-const MIN_STAKE_MIN = 1;
-const MIN_STAKE_MAX = 10000000;
-const MIN_ACTORS_MIN = 0;
-const MIN_ACTORS_MAX = 1;
-const MAX_ACTORS_MIN = 2;
-const MAX_ACTORS_MAX = 99;
-const REWARD_MIN = 1;
-const REWARD_MAX = 99999;
-const REWARD_PERIOD_MIN = 600;
-const REWARD_PERIOD_MAX = 3600;
-const BONDING_PERIOD_MIN = 600;
-const BONDING_PERIOD_MAX = 28800;
-const UNBONDING_PERIOD_MIN = 600;
-const UNBONDING_PERIOD_MAX = 28800;
-const MIN_SERVICE_PERIOD_MIN = 600;
-const MIN_SERVICE_PERIOD_MAX = 28800;
-const STARTUP_GRACE_PERIOD_MIN = 600;
-const STARTUP_GRACE_PERIOD_MAX = 28800;
-const ENTRY_REQUEST_FEE_MIN = 1;
-const ENTRY_REQUEST_FEE_MAX = 100000;
-
 // Add Working Group Leader Opening Parameters
 // TODO: Discuss the actual values
 const MIN_EXACT_BLOCK_MINUS_CURRENT = 14400 * 5; // ~5 days
@@ -88,6 +84,27 @@ const TERMINATE_ROLE_UNSTAKING_MAX = 14 * 14400; // 14 days
 const LEAVE_ROLE_UNSTAKING_MIN = 0;
 const LEAVE_ROLE_UNSTAKING_MAX = 14 * 14400; // 14 days
 
+// Set Working Group Mint Capacity
+// TODO: Discuss the actual values
+const WG_MINT_CAP_MIN = 0;
+const WG_MINT_CAP_MAX = 1000000;
+
+// Fill Working Group Leader Opening / Set Working Group Lead Reward
+// TODO: Discuss the actual values
+const MIN_REWARD_AMOUNT = 1;
+const MAX_REWARD_AMOUNT = 100000;
+const MIN_REWARD_INTERVAL = 1;
+const MAX_REWARD_INTERVAL = 30 * 14400; // 30 days
+// 3 days margin (voting_period) to prevent FillOpeningInvalidNextPaymentBlock
+// Should we worry that much about it though?
+const MIN_NEXT_PAYMENT_BLOCK_MINUS_CURRENT = 3 * 14400;
+const MAX_NEXT_PAYMENT_BLOCK_MINUS_CURRENT = 30 * 14400; // 30 days
+
+// Decrease/Slash Working Group Leader Stake
+const DECREASE_LEAD_STAKE_MIN = 1;
+const SLASH_LEAD_STAKE_MIN = 1;
+// Max is validated in form component, because it depends on selected working group's leader stake
+
 function errorMessage (name: string, min?: number | string, max?: number | string, unit?: string): string {
   return `${name} should be at least ${min} and no more than ${max}${unit ? ` ${unit}.` : '.'}`;
 }
@@ -97,80 +114,59 @@ Validation is used to validate a proposal form.
 Each proposal type should validate the fields of his form, anything is valid as long as it fits in a Yup Schema.
 In a form, validation should be injected in the Yup Schema just by accessing it in this object.
 Ex:
-// EvictStorageProvider Form
+// Text Form
 
 import Validation from 'path/to/validationSchema'
 ...
   validationSchema: Yup.object().shape({
     ...genericFormDefaultOptions.validationSchema,
-    storageProvider: Validation.EvictStorageProvider.storageProvider
+    ...Validation.Text()
   }),
 
 */
 
+type ProposalTypeKeys = typeof ProposalTypes[number];
+type OutdatedProposals = 'EvictStorageProvider' | 'SetStorageRoleParameters';
+type ValidationTypeKeys = Exclude<ProposalTypeKeys, OutdatedProposals> | 'All';
+
+/* eslint-disable @typescript-eslint/indent */
+// /\ This prevents eslint from trying to make "stairs" out of those multiple conditions.
+// They are more readable when one is directly under the other (switch-case style)
+type FormValuesByType<T extends ValidationTypeKeys> =
+  T extends 'All' ? GenericFormValues :
+  T extends 'Text' ? Omit<SignalFormValues, keyof GenericFormValues> :
+  T extends 'RuntimeUpgrade' ? Omit<RuntimeUpgradeFormValues, keyof GenericFormValues> :
+  T extends 'SetElectionParameters' ? Omit<SetCouncilParamsFormValues, keyof GenericFormValues> :
+  T extends 'Spending' ? Omit<SpendingProposalFormValues, keyof GenericFormValues> :
+  T extends 'SetLead' ? Omit<SetContentWorkingGroupLeadFormValues, keyof GenericFormValues> :
+  T extends 'SetContentWorkingGroupMintCapacity' ? Omit<SetContentWorkingGroupMintCapacityFormValues, keyof GenericFormValues> :
+  T extends 'SetValidatorCount' ? Omit<SetMaxValidatorCountFormValues, keyof GenericFormValues> :
+  T extends 'AddWorkingGroupLeaderOpening' ? Omit<AddWorkingGroupLeaderOpeningFormValues, keyof GenericFormValues> :
+  T extends 'SetWorkingGroupMintCapacity' ? Omit<SetWorkingGroupMintCapacityFormValues, keyof GenericFormValues> :
+  T extends 'BeginReviewWorkingGroupLeaderApplication' ? Omit<BeginReviewLeaderApplicationsFormValues, keyof GenericFormValues> :
+  T extends 'FillWorkingGroupLeaderOpening' ? Omit<FillWorkingGroupLeaderOpeningFormValues, keyof GenericFormValues> :
+  T extends 'DecreaseWorkingGroupLeaderStake' ? Omit<DecreaseWorkingGroupLeadStakeFormValues, keyof GenericFormValues> :
+  T extends 'SlashWorkingGroupLeaderStake' ? Omit<SlashWorkingGroupLeadStakeFormValues, keyof GenericFormValues> :
+  T extends 'SetWorkingGroupLeaderReward' ? Omit<SetWorkingGroupLeadRewardFormValues, keyof GenericFormValues> :
+  T extends 'TerminateWorkingGroupLeaderRole' ? Omit<TerminateWorkingGroupLeaderFormValues, keyof GenericFormValues> :
+  never;
+
+type ValidationSchemaFuncParamsByType<T extends ValidationTypeKeys> =
+  T extends 'AddWorkingGroupLeaderOpening' ? [number, InputValidationLengthConstraint] :
+  T extends 'FillWorkingGroupLeaderOpening' ? [number] :
+  T extends 'TerminateWorkingGroupLeaderRole' ? [InputValidationLengthConstraint] :
+  [];
+
+/* eslint-enable @typescript-eslint/indent */
+
+type ValidationSchemaFunc<FieldValuesT extends {}, ParamsT extends any[] = []> = (...params: ParamsT) =>
+({ [fieldK in keyof FieldValuesT]: Yup.Schema<any> });
+
 type ValidationType = {
-  All: {
-    title: Yup.StringSchema<string>;
-    rationale: Yup.StringSchema<string>;
-  };
-  Text: {
-    description: Yup.StringSchema<string>;
-  };
-  RuntimeUpgrade: {
-    WASM: Yup.MixedSchema<any>;
-  };
-  SetElectionParameters: {
-    announcingPeriod: Yup.NumberSchema<number>;
-    votingPeriod: Yup.NumberSchema<number>;
-    minVotingStake: Yup.NumberSchema<number>;
-    revealingPeriod: Yup.NumberSchema<number>;
-    minCouncilStake: Yup.NumberSchema<number>;
-    newTermDuration: Yup.NumberSchema<number>;
-    candidacyLimit: Yup.NumberSchema<number>;
-    councilSize: Yup.NumberSchema<number>;
-  };
-  Spending: {
-    tokens: Yup.NumberSchema<number>;
-    destinationAccount: Yup.StringSchema<string>;
-  };
-  SetLead: {
-    workingGroupLead: Yup.StringSchema<string>;
-  };
-  SetContentWorkingGroupMintCapacity: {
-    mintCapacity: Yup.NumberSchema<number>;
-  };
-  EvictStorageProvider: {
-    storageProvider: Yup.StringSchema<string | null>;
-  };
-  SetValidatorCount: {
-    maxValidatorCount: Yup.NumberSchema<number>;
-  };
-  SetStorageRoleParameters: {
-    min_stake: Yup.NumberSchema<number>;
-    min_actors: Yup.NumberSchema<number>;
-    max_actors: Yup.NumberSchema<number>;
-    reward: Yup.NumberSchema<number>;
-    reward_period: Yup.NumberSchema<number>;
-    bonding_period: Yup.NumberSchema<number>;
-    unbonding_period: Yup.NumberSchema<number>;
-    min_service_period: Yup.NumberSchema<number>;
-    startup_grace_period: Yup.NumberSchema<number>;
-    entry_request_fee: Yup.NumberSchema<number>;
-  };
-  AddWorkingGroupLeaderOpening: (currentBlock: number) => {
-    applicationsLimited: Yup.BooleanSchema<boolean>;
-    activateAt: Yup.StringSchema<string>;
-    activateAtBlock: Yup.NumberSchema<number>;
-    maxReviewPeriodLength: Yup.NumberSchema<number>;
-    maxApplications: Yup.NumberSchema<number>;
-    applicationStakeRequired: Yup.BooleanSchema<boolean>;
-    applicationStakeValue: Yup.NumberSchema<number>;
-    roleStakeRequired: Yup.BooleanSchema<boolean>;
-    roleStakeValue: Yup.NumberSchema<number>;
-    terminateRoleUnstakingPeriod: Yup.NumberSchema<number>;
-    leaveRoleUnstakingPeriod: Yup.NumberSchema<number>;
-    humanReadableText: Yup.StringSchema<string>;
-  };
+  [validationTypeK in ValidationTypeKeys]: ValidationSchemaFunc<
+  FormValuesByType<validationTypeK>,
+  ValidationSchemaFuncParamsByType<validationTypeK>
+  >
 };
 
 // Helpers for common validation
@@ -183,26 +179,26 @@ function minMaxInt (min: number, max: number, fieldName: string) {
 }
 
 const Validation: ValidationType = {
-  All: {
+  All: () => ({
     title: Yup.string()
       .required('Title is required!')
       .max(TITLE_MAX_LENGTH, `Title should be under ${TITLE_MAX_LENGTH} characters.`),
     rationale: Yup.string()
       .required('Rationale is required!')
       .max(RATIONALE_MAX_LENGTH, `Rationale should be under ${RATIONALE_MAX_LENGTH} characters.`)
-  },
-  Text: {
+  }),
+  Text: () => ({
     description: Yup.string()
       .required('Description is required!')
       .max(DESCRIPTION_MAX_LENGTH, `Description should be under ${DESCRIPTION_MAX_LENGTH}`)
-  },
-  RuntimeUpgrade: {
+  }),
+  RuntimeUpgrade: () => ({
     WASM: Yup.mixed()
       .test('fileArrayBuffer', 'Unexpected data format, file cannot be processed.', value => typeof value.byteLength !== 'undefined')
       .test('fileSizeMin', `Minimum file size is ${FILE_SIZE_BYTES_MIN} bytes.`, value => value.byteLength >= FILE_SIZE_BYTES_MIN)
       .test('fileSizeMax', `Maximum file size is ${FILE_SIZE_BYTES_MAX} bytes.`, value => value.byteLength <= FILE_SIZE_BYTES_MAX)
-  },
-  SetElectionParameters: {
+  }),
+  SetElectionParameters: () => ({
     announcingPeriod: Yup.number()
       .required('All fields must be filled!')
       .integer('This field must be an integer.')
@@ -273,8 +269,8 @@ const Validation: ValidationType = {
       .integer('This field must be an integer.')
       .min(COUNCIL_SIZE_MIN, errorMessage('The council size', COUNCIL_SIZE_MIN, COUNCIL_SIZE_MAX))
       .max(COUNCIL_SIZE_MAX, errorMessage('The council size', COUNCIL_SIZE_MIN, COUNCIL_SIZE_MAX))
-  },
-  Spending: {
+  }),
+  Spending: () => ({
     tokens: Yup.number()
       .positive('The token amount should be positive.')
       .integer('This field must be an integer.')
@@ -282,24 +278,19 @@ const Validation: ValidationType = {
       .required('You need to specify an amount of tokens.'),
     destinationAccount: Yup.string()
       .required('Select a destination account!')
-  },
-  SetLead: {
+  }),
+  SetLead: () => ({
     workingGroupLead: Yup.string().required('Select a proposed lead!')
-  },
-  SetContentWorkingGroupMintCapacity: {
-    mintCapacity: Yup.number()
+  }),
+  SetContentWorkingGroupMintCapacity: () => ({
+    capacity: Yup.number()
       .positive('Mint capacity should be positive.')
       .integer('This field must be an integer.')
       .min(MINT_CAPACITY_MIN, errorMessage('Mint capacity', MINT_CAPACITY_MIN, MINT_CAPACITY_MAX, CURRENCY_UNIT))
       .max(MINT_CAPACITY_MAX, errorMessage('Mint capacity', MINT_CAPACITY_MIN, MINT_CAPACITY_MAX, CURRENCY_UNIT))
       .required('You need to specify a mint capacity.')
-  },
-  EvictStorageProvider: {
-    storageProvider: Yup.string()
-      .nullable()
-      .required('Select a storage provider!')
-  },
-  SetValidatorCount: {
+  }),
+  SetValidatorCount: () => ({
     maxValidatorCount: Yup.number()
       .required('Enter the max validator count')
       .integer('This field must be an integer.')
@@ -311,84 +302,9 @@ const Validation: ValidationType = {
         MAX_VALIDATOR_COUNT_MAX,
         errorMessage('The max validator count', MAX_VALIDATOR_COUNT_MIN, MAX_VALIDATOR_COUNT_MAX)
       )
-  },
-  SetStorageRoleParameters: {
-    min_stake: Yup.number()
-      .required('All parameters are required')
-      .positive('The minimum stake should be positive.')
-      .integer('This field must be an integer.')
-      .max(MIN_STAKE_MAX, errorMessage('Minimum stake', MIN_STAKE_MIN, MIN_STAKE_MAX, CURRENCY_UNIT)),
-    min_actors: Yup.number()
-      .required('All parameters are required')
-      .integer('This field must be an integer.')
-      .min(MIN_ACTORS_MIN, errorMessage('Minimum actors', MIN_ACTORS_MIN, MIN_ACTORS_MAX))
-      .max(MIN_ACTORS_MAX, errorMessage('Minimum actors', MIN_ACTORS_MIN, MIN_ACTORS_MAX)),
-    max_actors: Yup.number()
-      .required('All parameters are required')
-      .integer('This field must be an integer.')
-      .min(MAX_ACTORS_MIN, errorMessage('Max actors', MAX_ACTORS_MIN, MAX_ACTORS_MAX))
-      .max(MAX_ACTORS_MAX, errorMessage('Max actors', MAX_ACTORS_MIN, MAX_ACTORS_MAX)),
-    reward: Yup.number()
-      .required('All parameters are required')
-      .integer('This field must be an integer.')
-      .min(REWARD_MIN, errorMessage('Reward', REWARD_MIN, REWARD_MAX, CURRENCY_UNIT))
-      .max(REWARD_MAX, errorMessage('Reward', REWARD_MIN, REWARD_MAX, CURRENCY_UNIT)),
-    reward_period: Yup.number()
-      .required('All parameters are required')
-      .integer('This field must be an integer.')
-      .min(REWARD_PERIOD_MIN, errorMessage('The reward period', REWARD_PERIOD_MIN, REWARD_PERIOD_MAX, 'blocks'))
-      .max(REWARD_PERIOD_MAX, errorMessage('The reward period', REWARD_PERIOD_MIN, REWARD_PERIOD_MAX, 'blocks')),
-    bonding_period: Yup.number()
-      .required('All parameters are required')
-      .integer('This field must be an integer.')
-      .min(BONDING_PERIOD_MIN, errorMessage('The bonding period', BONDING_PERIOD_MIN, BONDING_PERIOD_MAX, 'blocks'))
-      .max(BONDING_PERIOD_MAX, errorMessage('The bonding period', BONDING_PERIOD_MIN, BONDING_PERIOD_MAX, 'blocks')),
-    unbonding_period: Yup.number()
-      .required('All parameters are required')
-      .integer('This field must be an integer.')
-      .min(
-        UNBONDING_PERIOD_MIN,
-        errorMessage('The unbonding period', UNBONDING_PERIOD_MIN, UNBONDING_PERIOD_MAX, 'blocks')
-      )
-      .max(
-        UNBONDING_PERIOD_MAX,
-        errorMessage('The unbonding period', UNBONDING_PERIOD_MIN, UNBONDING_PERIOD_MAX, 'blocks')
-      ),
-    min_service_period: Yup.number()
-      .required('All parameters are required')
-      .integer('This field must be an integer.')
-      .min(
-        MIN_SERVICE_PERIOD_MIN,
-        errorMessage('The minimum service period', MIN_SERVICE_PERIOD_MIN, MIN_SERVICE_PERIOD_MAX, 'blocks')
-      )
-      .max(
-        MIN_SERVICE_PERIOD_MAX,
-        errorMessage('The minimum service period', MIN_SERVICE_PERIOD_MIN, MIN_SERVICE_PERIOD_MAX, 'blocks')
-      ),
-    startup_grace_period: Yup.number()
-      .required('All parameters are required')
-      .integer('This field must be an integer.')
-      .min(
-        STARTUP_GRACE_PERIOD_MIN,
-        errorMessage('The startup grace period', STARTUP_GRACE_PERIOD_MIN, STARTUP_GRACE_PERIOD_MAX, 'blocks')
-      )
-      .max(
-        STARTUP_GRACE_PERIOD_MAX,
-        errorMessage('The startup grace period', STARTUP_GRACE_PERIOD_MIN, STARTUP_GRACE_PERIOD_MAX, 'blocks')
-      ),
-    entry_request_fee: Yup.number()
-      .required('All parameters are required')
-      .integer('This field must be an integer.')
-      .min(
-        ENTRY_REQUEST_FEE_MIN,
-        errorMessage('The entry request fee', ENTRY_REQUEST_FEE_MIN, ENTRY_REQUEST_FEE_MAX, CURRENCY_UNIT)
-      )
-      .max(
-        STARTUP_GRACE_PERIOD_MAX,
-        errorMessage('The entry request fee', ENTRY_REQUEST_FEE_MIN, ENTRY_REQUEST_FEE_MAX, CURRENCY_UNIT)
-      )
-  },
-  AddWorkingGroupLeaderOpening: (currentBlock: number) => ({
+  }),
+  AddWorkingGroupLeaderOpening: (currentBlock: number, { min: HRTMin, max: HRTMax }: InputValidationLengthConstraint) => ({
+    workingGroup: Yup.string(),
     activateAt: Yup.string().required(),
     activateAtBlock: Yup.number()
       .when('activateAt', {
@@ -407,12 +323,14 @@ const Validation: ValidationType = {
         then: minMaxInt(MAX_APPLICATIONS_MIN, MAX_APPLICATIONS_MAX, 'Max. number of applications')
       }),
     applicationStakeRequired: Yup.boolean(),
+    applicationStakeMode: Yup.string(),
     applicationStakeValue: Yup.number()
       .when('applicationStakeRequired', {
         is: true,
         then: minMaxInt(APPLICATION_STAKE_VALUE_MIN, APPLICATION_STAKE_VALUE_MAX, 'Application stake value')
       }),
     roleStakeRequired: Yup.boolean(),
+    roleStakeMode: Yup.string(),
     roleStakeValue: Yup.number()
       .when('roleStakeRequired', {
         is: true,
@@ -450,6 +368,66 @@ const Validation: ValidationType = {
           return true;
         }
       )
+      .min(HRTMin.toNumber(), `human_readable_text must be at least ${HRTMin.toNumber()} character(s) long`)
+      .max(HRTMax.toNumber(), `human_readable_text cannot be more than ${HRTMax.toNumber()} character(s) long`)
+  }),
+  SetWorkingGroupMintCapacity: () => ({
+    workingGroup: Yup.string(),
+    capacity: minMaxInt(WG_MINT_CAP_MIN, WG_MINT_CAP_MAX, 'Mint capacity')
+  }),
+  BeginReviewWorkingGroupLeaderApplication: () => ({
+    workingGroup: Yup.string(),
+    openingId: Yup.number().required('Select an opening!')
+  }),
+  FillWorkingGroupLeaderOpening: (currentBlock: number) => ({
+    workingGroup: Yup.string(),
+    openingId: Yup.number().required('Select an opening!'),
+    successfulApplicant: Yup.number().required('Select a succesful applicant!'),
+    includeReward: Yup.boolean(),
+    rewardAmount: Yup.number()
+      .when('includeReward', {
+        is: true,
+        then: minMaxInt(MIN_REWARD_AMOUNT, MAX_REWARD_AMOUNT, 'Reward amount')
+      }),
+    rewardNextBlock: Yup.number()
+      .when('includeReward', {
+        is: true,
+        then: minMaxInt(
+          MIN_NEXT_PAYMENT_BLOCK_MINUS_CURRENT + currentBlock,
+          MAX_NEXT_PAYMENT_BLOCK_MINUS_CURRENT + currentBlock,
+          'Next payment block'
+        )
+      }),
+    rewardRecurring: Yup.boolean(),
+    rewardInterval: Yup.number()
+      .when(['includeReward', 'rewardRecurring'], {
+        is: true,
+        then: minMaxInt(MIN_REWARD_INTERVAL, MAX_REWARD_INTERVAL, 'Reward interval')
+      })
+  }),
+  DecreaseWorkingGroupLeaderStake: () => ({
+    workingGroup: Yup.string(),
+    amount: Yup.number()
+      .required('Amount is required!')
+      .min(DECREASE_LEAD_STAKE_MIN, `Amount must be greater than ${DECREASE_LEAD_STAKE_MIN}`)
+  }),
+  SlashWorkingGroupLeaderStake: () => ({
+    workingGroup: Yup.string(),
+    amount: Yup.number()
+      .required('Amount is required!')
+      .min(SLASH_LEAD_STAKE_MIN, `Amount must be greater than ${SLASH_LEAD_STAKE_MIN}`)
+  }),
+  SetWorkingGroupLeaderReward: () => ({
+    workingGroup: Yup.string(),
+    amount: minMaxInt(MIN_REWARD_AMOUNT, MAX_REWARD_AMOUNT, 'Reward amount')
+  }),
+  TerminateWorkingGroupLeaderRole: ({ min, max }: InputValidationLengthConstraint) => ({
+    workingGroup: Yup.string(),
+    terminationRationale: Yup.string()
+      .required('Termination rationale is required')
+      .min(min.toNumber(), `Termination rationale must be at least ${min.toNumber()} character(s) long`)
+      .max(max.toNumber(), `Termination rationale cannot be more than ${max.toNumber()} character(s) long`),
+    slashStake: Yup.boolean()
   })
 };
 

+ 19 - 20
pioneer/packages/joy-roles/src/classifiers.ts

@@ -7,7 +7,7 @@ import {
   Application,
   AcceptingApplications, ReviewPeriod,
   WaitingToBeingOpeningStageVariant,
-  ActiveOpeningStageVariant, ActiveOpeningStageKeys,
+  ActiveOpeningStageVariant,
   Opening,
   OpeningStageKeys,
   Deactivated, OpeningDeactivationCauseKeys,
@@ -133,25 +133,24 @@ async function classifyActiveOpeningStage (
   queryer: IBlockQueryer,
   stage: ActiveOpeningStageVariant
 ): Promise<OpeningStageClassification> {
-  switch (stage.stage.type) {
-    case ActiveOpeningStageKeys.AcceptingApplications:
-      return classifyActiveOpeningStageAcceptingApplications(
-        queryer,
-        stage.stage.value as AcceptingApplications
-      );
-
-    case ActiveOpeningStageKeys.ReviewPeriod:
-      return classifyActiveOpeningStageReviewPeriod(
-        opening,
-        queryer,
-        stage.stage.value as ReviewPeriod
-      );
-
-    case ActiveOpeningStageKeys.Deactivated:
-      return classifyActiveOpeningStageDeactivated(
-        queryer,
-        stage.stage.value as Deactivated
-      );
+  if (stage.stage.isOfType('AcceptingApplications')) {
+    return classifyActiveOpeningStageAcceptingApplications(
+      queryer,
+      stage.stage.asType('AcceptingApplications')
+    );
+  }
+  if (stage.stage.isOfType('ReviewPeriod')) {
+    return classifyActiveOpeningStageReviewPeriod(
+      opening,
+      queryer,
+      stage.stage.asType('ReviewPeriod')
+    );
+  }
+  if (stage.stage.isOfType('Deactivated')) {
+    return classifyActiveOpeningStageDeactivated(
+      queryer,
+      stage.stage.value as Deactivated
+    );
   }
 
   throw new Error('Unknown active opening stage: ' + stage.stage.type);

+ 18 - 8
pioneer/packages/joy-utils/src/MemberProfilePreview.tsx

@@ -25,23 +25,26 @@ const StyledProfilePreview = styled.div`
   }
 `;
 
-const Details = styled.div``;
+const Details = styled.div`
+  margin-left: 1rem;
+  display: grid;
+  grid-row-gap: 0.25rem;
+  grid-template-columns: 100%;
+`;
 
 const DetailsHandle = styled.h4`
   margin: 0;
-  margin-left: 1rem;
   font-weight: bold;
   color: #333;
 `;
 
 const DetailsID = styled.div`
-  margin: 0;
-  margin-top: 0.25rem;
-  margin-left: 1rem;
   color: #777;
 `;
 
-export default function ProfilePreview ({ id, avatar_uri, root_account, handle, link = false }: ProfileItemProps) {
+export default function ProfilePreview (
+  { id, avatar_uri, root_account, handle, link = false, children }: React.PropsWithChildren<ProfileItemProps>
+) {
   const Preview = (
     <StyledProfilePreview>
       {avatar_uri.toString() ? (
@@ -52,6 +55,7 @@ export default function ProfilePreview ({ id, avatar_uri, root_account, handle,
       <Details>
         <DetailsHandle>{handle.toString()}</DetailsHandle>
         { id !== undefined && <DetailsID>ID: {id.toString()}</DetailsID> }
+        { children }
       </Details>
     </StyledProfilePreview>
   );
@@ -69,7 +73,13 @@ type ProfilePreviewFromStructProps = {
   id?: number | MemberId;
 };
 
-export function ProfilePreviewFromStruct ({ profile, link, id }: ProfilePreviewFromStructProps) {
+export function ProfilePreviewFromStruct (
+  { profile, link, id, children }: React.PropsWithChildren<ProfilePreviewFromStructProps>
+) {
   const { avatar_uri, root_account, handle } = profile;
-  return <ProfilePreview {...{ avatar_uri, root_account, handle, link, id }} />;
+  return (
+    <ProfilePreview {...{ avatar_uri, root_account, handle, link, id }}>
+      {children}
+    </ProfilePreview>
+  );
 }

+ 99 - 14
pioneer/packages/joy-utils/src/consts/proposals.ts

@@ -3,12 +3,13 @@ import { ProposalType, ProposalMeta } from '../types/proposals';
 export const metadata: { [k in ProposalType]: ProposalMeta } = {
   EvictStorageProvider: {
     description: 'Evicting Storage Provider Proposal',
-    category: 'Storage',
+    category: 'Other',
     stake: 25000,
     approvalQuorum: 50,
     approvalThreshold: 75,
     slashingQuorum: 60,
-    slashingThreshold: 80
+    slashingThreshold: 80,
+    outdated: true
   },
   Text: {
     description: 'Signal Proposal',
@@ -21,12 +22,13 @@ export const metadata: { [k in ProposalType]: ProposalMeta } = {
   },
   SetStorageRoleParameters: {
     description: 'Set Storage Role Params Proposal',
-    category: 'Storage',
+    category: 'Other',
     stake: 100000,
     approvalQuorum: 66,
     approvalThreshold: 80,
     slashingQuorum: 60,
-    slashingThreshold: 80
+    slashingThreshold: 80,
+    outdated: true
   },
   SetValidatorCount: {
     description: 'Set Max Validator Count Proposal',
@@ -84,12 +86,75 @@ export const metadata: { [k in ProposalType]: ProposalMeta } = {
   },
   AddWorkingGroupLeaderOpening: {
     description: 'Add Working Group Leader Opening Proposal',
-    category: 'Other',
+    category: 'Working Groups',
     stake: 100000,
     approvalQuorum: 60,
     approvalThreshold: 80,
     slashingQuorum: 60,
     slashingThreshold: 80
+  },
+  SetWorkingGroupMintCapacity: {
+    description: 'Set Working Group Mint Capacity Proposal',
+    category: 'Working Groups',
+    stake: 50000,
+    approvalQuorum: 60,
+    approvalThreshold: 75,
+    slashingQuorum: 60,
+    slashingThreshold: 80
+  },
+  BeginReviewWorkingGroupLeaderApplication: {
+    description: 'Begin Working Group Leader Applications Review Proposal',
+    category: 'Working Groups',
+    stake: 25000,
+    approvalQuorum: 60,
+    approvalThreshold: 75,
+    slashingQuorum: 60,
+    slashingThreshold: 80
+  },
+  FillWorkingGroupLeaderOpening: {
+    description: 'Fill Working Group Leader Opening Proposal',
+    category: 'Working Groups',
+    stake: 50000,
+    approvalQuorum: 60,
+    approvalThreshold: 75,
+    slashingQuorum: 60,
+    slashingThreshold: 80
+  },
+  DecreaseWorkingGroupLeaderStake: {
+    description: 'Decrease Working Group Leader Stake Proposal',
+    category: 'Working Groups',
+    stake: 50000,
+    approvalQuorum: 60,
+    approvalThreshold: 75,
+    slashingQuorum: 60,
+    slashingThreshold: 80
+  },
+  SlashWorkingGroupLeaderStake: {
+    description: 'Slash Working Group Leader Stake Proposal',
+    category: 'Working Groups',
+    stake: 50000,
+    approvalQuorum: 60,
+    approvalThreshold: 75,
+    slashingQuorum: 60,
+    slashingThreshold: 80
+  },
+  SetWorkingGroupLeaderReward: {
+    description: 'Set Working Group Leader Reward Proposal',
+    category: 'Working Groups',
+    stake: 50000,
+    approvalQuorum: 60,
+    approvalThreshold: 75,
+    slashingQuorum: 60,
+    slashingThreshold: 80
+  },
+  TerminateWorkingGroupLeaderRole: {
+    description: 'Terminate Working Group Leader Role Proposal',
+    category: 'Working Groups',
+    stake: 100000,
+    approvalQuorum: 66,
+    approvalThreshold: 80,
+    slashingQuorum: 60,
+    slashingThreshold: 80
   }
 };
 
@@ -97,19 +162,11 @@ type ProposalsApiMethodNames = {
   votingPeriod: string;
   gracePeriod: string;
 }
-export const apiMethods: { [k in ProposalType]: ProposalsApiMethodNames } = {
-  EvictStorageProvider: {
-    votingPeriod: 'evictStorageProviderProposalVotingPeriod',
-    gracePeriod: 'evictStorageProviderProposalPeriod'
-  },
+export const apiMethods: { [k in ProposalType]?: ProposalsApiMethodNames } = {
   Text: {
     votingPeriod: 'textProposalVotingPeriod',
     gracePeriod: 'textProposalGracePeriod'
   },
-  SetStorageRoleParameters: {
-    votingPeriod: 'setStorageRoleParametersProposalVotingPeriod',
-    gracePeriod: 'setStorageRoleParametersProposalGracePeriod'
-  },
   SetValidatorCount: {
     votingPeriod: 'setValidatorCountProposalVotingPeriod',
     gracePeriod: 'setValidatorCountProposalGracePeriod'
@@ -137,6 +194,34 @@ export const apiMethods: { [k in ProposalType]: ProposalsApiMethodNames } = {
   AddWorkingGroupLeaderOpening: {
     votingPeriod: 'addWorkingGroupOpeningProposalVotingPeriod',
     gracePeriod: 'addWorkingGroupOpeningProposalGracePeriod'
+  },
+  SetWorkingGroupMintCapacity: {
+    votingPeriod: 'setWorkingGroupMintCapacityProposalVotingPeriod',
+    gracePeriod: 'setWorkingGroupMintCapacityProposalGracePeriod'
+  },
+  BeginReviewWorkingGroupLeaderApplication: {
+    votingPeriod: 'beginReviewWorkingGroupLeaderApplicationsProposalVotingPeriod',
+    gracePeriod: 'beginReviewWorkingGroupLeaderApplicationsProposalGracePeriod'
+  },
+  FillWorkingGroupLeaderOpening: {
+    votingPeriod: 'fillWorkingGroupLeaderOpeningProposalVotingPeriod',
+    gracePeriod: 'fillWorkingGroupLeaderOpeningProposalGracePeriod'
+  },
+  DecreaseWorkingGroupLeaderStake: {
+    votingPeriod: 'decreaseWorkingGroupLeaderStakeProposalVotingPeriod',
+    gracePeriod: 'decreaseWorkingGroupLeaderStakeProposalGracePeriod'
+  },
+  SlashWorkingGroupLeaderStake: {
+    votingPeriod: 'slashWorkingGroupLeaderStakeProposalVotingPeriod',
+    gracePeriod: 'slashWorkingGroupLeaderStakeProposalGracePeriod'
+  },
+  SetWorkingGroupLeaderReward: {
+    votingPeriod: 'setWorkingGroupLeaderRewardProposalVotingPeriod',
+    gracePeriod: 'setWorkingGroupLeaderRewardProposalGracePeriod'
+  },
+  TerminateWorkingGroupLeaderRole: {
+    votingPeriod: 'terminateWorkingGroupLeaderRoleProposalVotingPeriod',
+    gracePeriod: 'terminateWorkingGroupLeaderRoleProposalGracePeriod'
   }
 } as const;
 

+ 2 - 2
pioneer/packages/joy-utils/src/consts/workingGroups.ts

@@ -1,4 +1,4 @@
-import { WorkingGroupKeys } from '@joystream/types/common';
-export const apiModuleByGroup: { [k in WorkingGroupKeys]: string } = {
+import { WorkingGroupKey } from '@joystream/types/common';
+export const apiModuleByGroup: { [k in WorkingGroupKey]: string } = {
   Storage: 'storageWorkingGroup'
 };

+ 22 - 0
pioneer/packages/joy-utils/src/functions/format.ts

@@ -0,0 +1,22 @@
+import { RewardRelationship } from '@joystream/types/recurring-rewards';
+import { formatBalance } from '@polkadot/util';
+import { Option } from '@polkadot/types';
+import { RewardPolicy } from '@joystream/types/working-group';
+
+export const formatReward = (
+  {
+    amount_per_payout: amount,
+    payout_interval: interval,
+    next_payment_at_block
+  }: RewardRelationship | RewardPolicy,
+  showNextPaymentBlock = false
+) => {
+  const nextPaymentBlock = (next_payment_at_block instanceof Option)
+    ? next_payment_at_block.unwrapOr(null)
+    : next_payment_at_block;
+
+  return (
+    `${formatBalance(amount)}${interval.isSome ? ` / ${interval.unwrap()} block(s)` : ''}` +
+    ((showNextPaymentBlock && nextPaymentBlock) ? ` (Next payment: #${nextPaymentBlock})` : '')
+  );
+};

+ 3 - 3
pioneer/packages/joy-utils/src/index.ts

@@ -7,7 +7,7 @@ import keyring from '@polkadot/ui-keyring';
 // Joystream Stake utils
 // --------------------------------------
 
-import { Stake, Backer } from '@joystream/types/council';
+import { ElectionStake, Backer } from '@joystream/types/council';
 
 // Substrate/Polkadot API utils
 // --------------------------------------
@@ -117,11 +117,11 @@ export function newOptionalText (str?: string): OptionalText {
   return new Option(Text, text);
 }
 
-export function calcTotalStake (stakes: Stake | Stake[] | undefined): BN {
+export function calcTotalStake (stakes: ElectionStake | ElectionStake[] | undefined): BN {
   if (typeof stakes === 'undefined') {
     return ZERO;
   }
-  const total = (stake: Stake) => stake.new.add(stake.transferred);
+  const total = (stake: ElectionStake) => stake.new.add(stake.transferred);
   try {
     if (Array.isArray(stakes)) {
       return stakes.reduce((accum, stake) => {

+ 102 - 0
pioneer/packages/joy-utils/src/react/components/working-groups/ApplicationDetails.tsx

@@ -0,0 +1,102 @@
+import React, { useState } from 'react';
+import { ParsedApplication } from '../../../types/workingGroups';
+import { ProfilePreviewFromStruct as MemberPreview } from '../../../MemberProfilePreview';
+import { useTransport, usePromise } from '../../hooks';
+import { Item, Label, Button } from 'semantic-ui-react';
+import { formatBalance } from '@polkadot/util';
+import { WorkingGroupKey } from '@joystream/types/common';
+import PromiseComponent from '../PromiseComponent';
+
+type ApplicationsDetailsProps = {
+  applications: ParsedApplication[];
+  acceptedIds?: number[];
+}
+
+export const ApplicationsDetails = ({ applications, acceptedIds }: ApplicationsDetailsProps) => {
+  const rejectedApplications = acceptedIds !== undefined ? applications.filter(a => !acceptedIds.includes(a.wgApplicationId)) : [];
+  const [showAll, setShowAll] = useState(!rejectedApplications.length);
+  const shownApplications = applications.filter(a => showAll || acceptedIds?.includes(a.wgApplicationId));
+  return (<>
+    <Item.Group>
+      {
+        shownApplications.map(({ member, stakes, wgApplicationId, humanReadableText }) => {
+          let HRT = humanReadableText.toString();
+          const accepted = acceptedIds?.includes(wgApplicationId);
+          try { HRT = JSON.stringify(JSON.parse(HRT), undefined, 4); } catch (e) { /* Do nothing */ }
+          return (
+            <Item key={wgApplicationId} style={{
+              background: 'white',
+              padding: '1em 1.5em',
+              boxShadow: `0 0 0.5rem 1px ${accepted ? '#21ba45' : (acceptedIds !== undefined ? '#db282899' : '#00000050')}`
+            }}>
+              <Item.Content>
+                <Item.Header><MemberPreview profile={member}></MemberPreview></Item.Header>
+                <Item.Meta>
+                  <Label>Application id: {wgApplicationId}</Label>
+                  { stakes.application > 0 && <Label>Appl. stake: {formatBalance(stakes.application)}</Label> }
+                  { stakes.role > 0 && <Label>Role stake: {formatBalance(stakes.role)}</Label> }
+                </Item.Meta>
+                <Item.Description>
+                  <pre style={{
+                    whiteSpace: 'pre-wrap',
+                    fontWeight: 'normal'
+                  }}>
+                    {HRT}
+                  </pre>
+                </Item.Description>
+              </Item.Content>
+            </Item>
+          );
+        })
+      }
+    </Item.Group>
+    {rejectedApplications.length > 0 && (
+      <Button fluid onClick={() => setShowAll(current => !current)}>
+        { showAll ? 'Hide rejected applications' : 'Show rejected applications' }
+      </Button>
+    )}
+  </>);
+};
+
+type ApplicationsDetailsByIdsProps = {
+  group: WorkingGroupKey;
+  ids: number[];
+  acceptedIds?: number[];
+};
+
+export const ApplicationsDetailsByIds = ({ group, ids, acceptedIds }: ApplicationsDetailsByIdsProps) => {
+  const transport = useTransport();
+  const [applications, error, loading] = usePromise<ParsedApplication[]>(
+    () => Promise.all(ids.map(id => transport.workingGroups.parsedApplicationById(group, id))),
+    [],
+    [ids]
+  );
+
+  return (
+    <PromiseComponent {...{ error, loading }} message="Fetching application(s)...">
+      <ApplicationsDetails applications={applications} acceptedIds={acceptedIds}/>
+    </PromiseComponent>
+  );
+};
+
+type ApplicationsDetailsByOpeningProps = {
+  group: WorkingGroupKey;
+  openingId: number;
+  acceptedIds?: number[];
+};
+
+export const ApplicationsDetailsByOpening = ({ group, openingId, acceptedIds }: ApplicationsDetailsByOpeningProps) => {
+  const transport = useTransport();
+  const [applications, error, loading] = usePromise<ParsedApplication[]>(
+    // Cannot filter by active, otherwise the details will be broken once opening is filled!
+    () => transport.workingGroups.openingApplications(group, openingId),
+    [],
+    [openingId]
+  );
+
+  return (
+    <PromiseComponent {...{ error, loading }} message="Fetching applications...">
+      <ApplicationsDetails applications={applications} acceptedIds={acceptedIds}/>
+    </PromiseComponent>
+  );
+};

+ 56 - 0
pioneer/packages/joy-utils/src/react/components/working-groups/LeadInfo.tsx

@@ -0,0 +1,56 @@
+import React from 'react';
+import { WorkerData } from '../../../types/workingGroups';
+import { ProfilePreviewFromStruct as MemberPreview } from '../../../MemberProfilePreview';
+import { Label, Message } from 'semantic-ui-react';
+import { formatBalance } from '@polkadot/util';
+import { WorkingGroupKey } from '@joystream/types/common';
+import { useTransport, usePromise } from '../../hooks';
+import PromiseComponent from '../PromiseComponent';
+import { formatReward } from '@polkadot/joy-utils/functions/format';
+
+type LeadInfoProps = {
+  lead: WorkerData | null;
+  group?: WorkingGroupKey;
+  header?: boolean;
+  emptyMessage?: string;
+};
+
+export const LeadInfo = ({ lead, group, header = false, emptyMessage = 'NONE' }: LeadInfoProps) => (
+  <Message>
+    <Message.Content>
+      { header && <Message.Header>Current {group && `${group} `}Working Group lead:</Message.Header> }
+      <div style={{ padding: '0.5rem 0' }}>
+        { lead
+          ? (
+            <MemberPreview profile={lead.profile}>
+              <div>
+                <Label>Role stake: <b>{ lead.stake ? formatBalance(lead.stake) : 'NONE'}</b></Label>
+                <Label>Reward: <b>{ lead.reward ? formatReward(lead.reward) : 'NONE' }</b></Label>
+              </div>
+            </MemberPreview>
+          ) : emptyMessage
+        }
+      </div>
+    </Message.Content>
+  </Message>
+);
+
+type LeadInfoFromIdProps = {
+  leadId: number;
+  group: WorkingGroupKey;
+};
+
+export const LeadInfoFromId = ({ leadId, group }: LeadInfoFromIdProps) => {
+  const transport = useTransport();
+  const [lead, error, loading] = usePromise<WorkerData | null>(
+    () => transport.workingGroups.groupMemberById(group, leadId),
+    null,
+    [leadId]
+  );
+
+  return (
+    <PromiseComponent error={error} loading={loading} message="Fetching current lead...">
+      <LeadInfo lead={lead} group={group} header={false} emptyMessage="Leader no longer active!"/>
+    </PromiseComponent>
+  );
+};

+ 4 - 3
pioneer/packages/joy-utils/src/react/context/transport.tsx

@@ -1,4 +1,4 @@
-import React, { createContext, useContext } from 'react';
+import React, { createContext, useContext, useState } from 'react';
 import { ApiContext } from '@polkadot/react-api';
 import { ApiProps } from '@polkadot/react-api/types';
 
@@ -15,7 +15,8 @@ export function TransportProvider ({ children }: { children: React.PropsWithChil
     throw new Error('Cannot create Transport: The Substrate API is not ready yet.');
   }
 
-  const transport = new Transport(api.api);
+  // Preserve transport instance in state to allow more effective caching
+  const [transportInstance] = useState<Transport>(() => new Transport(api.api));
 
-  return <TransportContext.Provider value={transport}>{children}</TransportContext.Provider>;
+  return <TransportContext.Provider value={transportInstance}>{children}</TransportContext.Provider>;
 }

+ 22 - 3
pioneer/packages/joy-utils/src/react/hooks/usePromise.tsx

@@ -2,7 +2,12 @@ import { useState, useEffect, useCallback } from 'react';
 
 export type UsePromiseReturnValues<T> = [T, any, boolean, () => Promise<void|null>];
 
-export default function usePromise<T> (promise: () => Promise<T>, defaultValue: T, dependsOn: any[] = []): UsePromiseReturnValues<T> {
+export default function usePromise<T> (
+  promise: () => Promise<T>,
+  defaultValue: T,
+  dependsOn: any[] = [],
+  onUpdate?: (newValue: T) => void
+): UsePromiseReturnValues<T> {
   const [state, setState] = useState<{
     value: T;
     error: any;
@@ -12,8 +17,22 @@ export default function usePromise<T> (promise: () => Promise<T>, defaultValue:
   let isSubscribed = true;
   const execute = useCallback(() => {
     return promise()
-      .then(value => (isSubscribed ? setState({ value, error: null, isPending: false }) : null))
-      .catch(error => (isSubscribed ? setState({ value: defaultValue, error: error, isPending: false }) : null));
+      .then(value => {
+        if (isSubscribed) {
+          setState({ value, error: null, isPending: false });
+          if (onUpdate) {
+            onUpdate(value);
+          }
+        }
+      })
+      .catch(error => {
+        if (isSubscribed) {
+          setState({ value: defaultValue, error: error, isPending: false });
+          if (onUpdate) {
+            onUpdate(defaultValue); // This should represent an empty value in most cases
+          }
+        }
+      });
   }, [promise]);
 
   useEffect(() => {

+ 25 - 10
pioneer/packages/joy-utils/src/transport/base.ts

@@ -1,47 +1,62 @@
 import { ApiPromise } from '@polkadot/api';
 import { Codec } from '@polkadot/types/types';
+import { APIQueryCache } from '../APIQueryCache';
 
 export default abstract class BaseTransport {
   protected api: ApiPromise;
+  protected cacheApi: APIQueryCache;
 
-  constructor (api: ApiPromise) {
+  constructor (api: ApiPromise, cacheApi: APIQueryCache) {
     this.api = api;
+    this.cacheApi = cacheApi;
   }
 
   protected get proposalsEngine () {
-    return this.api.query.proposalsEngine;
+    return this.cacheApi.query.proposalsEngine;
   }
 
   protected get proposalsCodex () {
-    return this.api.query.proposalsCodex;
+    return this.cacheApi.query.proposalsCodex;
   }
 
   protected get proposalsDiscussion () {
-    return this.api.query.proposalsDiscussion;
+    return this.cacheApi.query.proposalsDiscussion;
   }
 
   protected get members () {
-    return this.api.query.members;
+    return this.cacheApi.query.members;
   }
 
   protected get council () {
-    return this.api.query.council;
+    return this.cacheApi.query.council;
   }
 
   protected get councilElection () {
-    return this.api.query.councilElection;
+    return this.cacheApi.query.councilElection;
   }
 
   protected get actors () {
-    return this.api.query.actors;
+    return this.cacheApi.query.actors;
   }
 
   protected get contentWorkingGroup () {
-    return this.api.query.contentWorkingGroup;
+    return this.cacheApi.query.contentWorkingGroup;
   }
 
   protected get minting () {
-    return this.api.query.minting;
+    return this.cacheApi.query.minting;
+  }
+
+  protected get hiring () {
+    return this.cacheApi.query.hiring;
+  }
+
+  protected get stake () {
+    return this.cacheApi.query.stake;
+  }
+
+  protected get recurringRewards () {
+    return this.cacheApi.query.recurringRewards;
   }
 
   protected queryMethodByName (name: string) {

+ 3 - 2
pioneer/packages/joy-utils/src/transport/contentWorkingGroup.ts

@@ -5,12 +5,13 @@ import { MintId, Mint } from '@joystream/types/mint';
 import { LeadId } from '@joystream/types/content-working-group';
 import { ApiPromise } from '@polkadot/api';
 import MembersTransport from './members';
+import { APIQueryCache } from '../APIQueryCache';
 
 export default class ContentWorkingGroupTransport extends BaseTransport {
   private membersT: MembersTransport;
 
-  constructor (api: ApiPromise, membersTransport: MembersTransport) {
-    super(api);
+  constructor (api: ApiPromise, cacheApi: APIQueryCache, membersTransport: MembersTransport) {
+    super(api, cacheApi);
     this.membersT = membersTransport;
   }
 

+ 4 - 3
pioneer/packages/joy-utils/src/transport/council.ts

@@ -8,13 +8,14 @@ import { FIRST_MEMBER_ID } from '../consts/members';
 import { ApiPromise } from '@polkadot/api';
 import MembersTransport from './members';
 import ChainTransport from './chain';
+import { APIQueryCache } from '../APIQueryCache';
 
 export default class CouncilTransport extends BaseTransport {
   private membersT: MembersTransport;
   private chainT: ChainTransport;
 
-  constructor (api: ApiPromise, membersTransport: MembersTransport, chainTransport: ChainTransport) {
-    super(api);
+  constructor (api: ApiPromise, cacheApi: APIQueryCache, membersTransport: MembersTransport, chainTransport: ChainTransport) {
+    super(api, cacheApi);
     this.membersT = membersTransport;
     this.chainT = chainTransport;
   }
@@ -22,7 +23,7 @@ export default class CouncilTransport extends BaseTransport {
   async councilMembersLength (atBlock?: number): Promise<number> {
     if (atBlock) {
       const blockHash = await this.chainT.blockHash(atBlock);
-      return ((await this.council.activeCouncil.at(blockHash)) as Seats).length;
+      return ((await this.api.query.council.activeCouncil.at(blockHash)) as Seats).length;
     }
 
     return ((await this.council.activeCouncil()) as Seats).length;

+ 11 - 8
pioneer/packages/joy-utils/src/transport/index.ts

@@ -7,9 +7,11 @@ import CouncilTransport from './council';
 import StorageProvidersTransport from './storageProviders';
 import ValidatorsTransport from './validators';
 import WorkingGroupsTransport from './workingGroups';
+import { APIQueryCache } from '../APIQueryCache';
 
 export default class Transport {
   protected api: ApiPromise;
+  protected cacheApi: APIQueryCache;
   // Specific transports
   public chain: ChainTransport;
   public members: MembersTransport;
@@ -22,13 +24,14 @@ export default class Transport {
 
   constructor (api: ApiPromise) {
     this.api = api;
-    this.chain = new ChainTransport(api);
-    this.members = new MembersTransport(api);
-    this.storageProviders = new StorageProvidersTransport(api);
-    this.validators = new ValidatorsTransport(api);
-    this.council = new CouncilTransport(api, this.members, this.chain);
-    this.contentWorkingGroup = new ContentWorkingGroupTransport(api, this.members);
-    this.proposals = new ProposalsTransport(api, this.members, this.chain, this.council);
-    this.workingGroups = new WorkingGroupsTransport(api, this.members);
+    this.cacheApi = new APIQueryCache(api);
+    this.chain = new ChainTransport(api, this.cacheApi);
+    this.members = new MembersTransport(api, this.cacheApi);
+    this.storageProviders = new StorageProvidersTransport(api, this.cacheApi);
+    this.validators = new ValidatorsTransport(api, this.cacheApi);
+    this.council = new CouncilTransport(api, this.cacheApi, this.members, this.chain);
+    this.contentWorkingGroup = new ContentWorkingGroupTransport(api, this.cacheApi, this.members);
+    this.proposals = new ProposalsTransport(api, this.cacheApi, this.members, this.chain, this.council);
+    this.workingGroups = new WorkingGroupsTransport(api, this.cacheApi, this.members);
   }
 }

+ 59 - 27
pioneer/packages/joy-utils/src/transport/proposals.ts

@@ -13,9 +13,9 @@ import { ParsedMember } from '../types/members';
 import BaseTransport from './base';
 
 import { ThreadId, PostId } from '@joystream/types/common';
-import { Proposal, ProposalId, VoteKind, DiscussionThread, DiscussionPost } from '@joystream/types/proposals';
+import { Proposal, ProposalId, VoteKind, DiscussionThread, DiscussionPost, ProposalDetails } from '@joystream/types/proposals';
 import { MemberId } from '@joystream/types/members';
-import { u32, u64 } from '@polkadot/types/';
+import { u32, u64, Bytes, Vec } from '@polkadot/types/';
 import { BalanceOf } from '@polkadot/types/interfaces';
 
 import { bytesToString } from '../functions/misc';
@@ -28,43 +28,80 @@ import MembersTransport from './members';
 import ChainTransport from './chain';
 import CouncilTransport from './council';
 
+import { blake2AsHex } from '@polkadot/util-crypto';
+import { APIQueryCache } from '../APIQueryCache';
+
+type ProposalDetailsCacheEntry = {
+  type: ProposalType;
+  details: any[];
+}
+type ProposalDetailsCache = {
+  [id: number]: ProposalDetailsCacheEntry | undefined;
+}
+
 export default class ProposalsTransport extends BaseTransport {
   private membersT: MembersTransport;
   private chainT: ChainTransport;
   private councilT: CouncilTransport;
+  private proposalDetailsCache: ProposalDetailsCache = {};
 
   constructor (
     api: ApiPromise,
+    cacheApi: APIQueryCache,
     membersTransport: MembersTransport,
     chainTransport: ChainTransport,
     councilTransport: CouncilTransport
   ) {
-    super(api);
+    super(api, cacheApi);
     this.membersT = membersTransport;
     this.chainT = chainTransport;
     this.councilT = councilTransport;
   }
 
   proposalCount () {
-    return this.proposalsEngine.proposalCount<u32>();
+    return this.proposalsEngine.proposalCount() as Promise<u32>;
   }
 
   rawProposalById (id: ProposalId) {
-    return this.proposalsEngine.proposals<Proposal>(id);
+    return this.proposalsEngine.proposals(id) as Promise<Proposal>;
   }
 
-  proposalDetailsById (id: ProposalId) {
-    return this.proposalsCodex.proposalDetailsByProposalId(id);
+  rawProposalDetails (id: ProposalId) {
+    return this.proposalsCodex.proposalDetailsByProposalId(id) as Promise<ProposalDetails>;
   }
 
   cancellationFee (): number {
     return (this.api.consts.proposalsEngine.cancellationFee as BalanceOf).toNumber();
   }
 
+  async typeAndDetails (id: ProposalId) {
+    const cachedProposalDetails = this.proposalDetailsCache[id.toNumber()];
+    // Avoid fetching runtime upgrade proposal details if we already have them cached
+    if (cachedProposalDetails) {
+      return cachedProposalDetails;
+    } else {
+      // TODO: The right typesafe handling with JoyEnum would be very useful here
+      const rawDetails = await this.rawProposalDetails(id);
+      const type = rawDetails.type as ProposalType;
+      let details: any[];
+      if (type === 'RuntimeUpgrade') {
+        // In case of RuntimeUpgrade proposal we override details to just contain the hash and filesize
+        // (instead of full WASM bytecode)
+        const wasm = rawDetails.value as Bytes;
+        details = [blake2AsHex(wasm, 256), wasm.length];
+      } else {
+        const detailsJSON = rawDetails.value.toJSON();
+        details = Array.isArray(detailsJSON) ? detailsJSON : [detailsJSON];
+      }
+      // Save entry in cache
+      this.proposalDetailsCache[id.toNumber()] = { type, details };
+
+      return { type, details };
+    }
+  }
+
   async proposalById (id: ProposalId): Promise<ParsedProposal> {
-    const rawDetails = (await this.proposalDetailsById(id)).toJSON() as { [k: string]: any };
-    const type = Object.keys(rawDetails)[0] as ProposalType;
-    const details = Array.isArray(rawDetails[type]) ? rawDetails[type] : [rawDetails[type]];
+    const { type, details } = await this.typeAndDetails(id);
     const rawProposal = await this.rawProposalById(id);
     const proposer = (await this.membersT.memberProfile(rawProposal.proposerId)).toJSON() as ParsedMember;
     const proposal = rawProposal.toJSON() as {
@@ -102,7 +139,7 @@ export default class ProposalsTransport extends BaseTransport {
   }
 
   async activeProposals () {
-    const activeProposalIds = await this.proposalsEngine.activeProposalIds<ProposalId[]>();
+    const activeProposalIds = (await this.proposalsEngine.activeProposalIds()) as Vec<ProposalId>;
 
     return Promise.all(activeProposalIds.map(id => this.proposalById(id)));
   }
@@ -112,13 +149,9 @@ export default class ProposalsTransport extends BaseTransport {
     return proposals.filter(({ proposerId }) => member.eq(proposerId));
   }
 
-  async proposalDetails (id: ProposalId) {
-    return this.proposalsCodex.proposalDetailsByProposalId(id);
-  }
-
   async voteByProposalAndMember (proposalId: ProposalId, voterId: MemberId): Promise<VoteKind | null> {
-    const vote = await this.proposalsEngine.voteExistsByProposalByVoter<VoteKind>(proposalId, voterId);
-    const hasVoted = (await this.proposalsEngine.voteExistsByProposalByVoter.size(proposalId, voterId)).toNumber();
+    const vote = (await this.proposalsEngine.voteExistsByProposalByVoter(proposalId, voterId)) as VoteKind;
+    const hasVoted = (await this.api.query.proposalsEngine.voteExistsByProposalByVoter.size(proposalId, voterId)).toNumber();
     return hasVoted ? vote : null;
   }
 
@@ -154,15 +187,14 @@ export default class ProposalsTransport extends BaseTransport {
   }
 
   async parametersFromProposalType (type: ProposalType) {
-    const { votingPeriod: votingPeriodMethod, gracePeriod: gracePeriodMethod } = proposalsApiMethods[type];
-    // TODO: Remove the fallback after outdated proposals are removed
-    const votingPeriod = this.proposalsCodex[votingPeriodMethod]
-      ? ((await this.proposalsCodex[votingPeriodMethod]()) as u32).toNumber()
-      : 0;
-    const gracePeriod = this.proposalsCodex[gracePeriodMethod]
-      ? ((await this.proposalsCodex[gracePeriodMethod]()) as u32).toNumber()
-      : 0;
-    // Currently it's same for all types, but this will change soon
+    const methods = proposalsApiMethods[type];
+    let votingPeriod = 0;
+    let gracePeriod = 0;
+    if (methods) {
+      votingPeriod = ((await this.proposalsCodex[methods.votingPeriod]()) as u32).toNumber();
+      gracePeriod = ((await this.proposalsCodex[methods.gracePeriod]()) as u32).toNumber();
+    }
+    // Currently it's same for all types, but this will change soon (?)
     const cancellationFee = this.cancellationFee();
     return {
       type,
@@ -178,7 +210,7 @@ export default class ProposalsTransport extends BaseTransport {
   }
 
   async subscribeProposal (id: number|ProposalId, callback: () => void) {
-    return this.proposalsEngine.proposals(id, callback);
+    return this.api.query.proposalsEngine.proposals(id, callback);
   }
 
   async discussion (id: number|ProposalId): Promise<ParsedDiscussion | null> {

+ 144 - 18
pioneer/packages/joy-utils/src/transport/workingGroups.ts

@@ -1,47 +1,173 @@
 import { Option } from '@polkadot/types/';
+import { Balance } from '@polkadot/types/interfaces';
 import BaseTransport from './base';
 import { ApiPromise } from '@polkadot/api';
 import MembersTransport from './members';
 import { SingleLinkedMapEntry } from '../index';
-import { Worker, WorkerId } from '@joystream/types/working-group';
+import { Worker, WorkerId, Opening as WGOpening, Application as WGApplication, OpeningTypeKey } from '@joystream/types/working-group';
 import { apiModuleByGroup } from '../consts/workingGroups';
-import { WorkingGroupKeys } from '@joystream/types/common';
-import { LeadWithProfile } from '../types/workingGroups';
+import { WorkingGroupKey } from '@joystream/types/common';
+import { WorkerData, OpeningData, ParsedApplication } from '../types/workingGroups';
+import { OpeningId, ApplicationId, Opening, Application, ActiveOpeningStageKey } from '@joystream/types/hiring';
+import { MultipleLinkedMapEntry } from '../LinkedMapEntry';
+import { Stake, StakeId } from '@joystream/types/stake';
+import { RewardRelationshipId, RewardRelationship } from '@joystream/types/recurring-rewards';
+import { APIQueryCache } from '../APIQueryCache';
 
 export default class WorkingGroupsTransport extends BaseTransport {
   private membersT: MembersTransport;
 
-  constructor (api: ApiPromise, membersTransport: MembersTransport) {
-    super(api);
+  constructor (api: ApiPromise, cacheApi: APIQueryCache, membersTransport: MembersTransport) {
+    super(api, cacheApi);
     this.membersT = membersTransport;
   }
 
-  protected queryByGroup (group: WorkingGroupKeys) {
+  protected queryByGroup (group: WorkingGroupKey) {
     const module = apiModuleByGroup[group];
-    return this.api.query[module];
+    return this.cacheApi.query[module];
   }
 
-  public async currentLead (group: WorkingGroupKeys): Promise <LeadWithProfile | null> {
+  public async groupMemberById (group: WorkingGroupKey, workerId: number): Promise<WorkerData | null> {
+    const workerLink = new SingleLinkedMapEntry(
+      Worker,
+      await this.queryByGroup(group).workerById(workerId)
+    );
+    const worker = workerLink.value;
+
+    if (!worker.is_active) {
+      return null;
+    }
+
+    const stake = worker.role_stake_profile.isSome
+      ? (await this.stakeValue(worker.role_stake_profile.unwrap().stake_id)).toNumber()
+      : undefined;
+
+    const reward = worker.reward_relationship.isSome
+      ? (await this.rewardRelationship(worker.reward_relationship.unwrap()))
+      : undefined;
+
+    const profile = await this.membersT.expectedMemberProfile(worker.member_id);
+
+    return { group, workerId, worker, profile, stake, reward };
+  }
+
+  public async currentLead (group: WorkingGroupKey): Promise<WorkerData | null> {
     const optLeadId = (await this.queryByGroup(group).currentLead()) as Option<WorkerId>;
 
     if (!optLeadId.isSome) {
       return null;
     }
 
-    const leadWorkerId = optLeadId.unwrap();
-    const leadWorkerLink = new SingleLinkedMapEntry(
-      Worker,
-      await this.queryByGroup(group).workerById(leadWorkerId)
-    );
-    const leadWorker = leadWorkerLink.value;
+    const leadWorkerId = optLeadId.unwrap().toNumber();
 
-    if (!leadWorker.is_active) {
-      return null;
+    return this.groupMemberById(group, leadWorkerId);
+  }
+
+  public async allOpenings (group: WorkingGroupKey, type?: OpeningTypeKey): Promise<OpeningData[]> {
+    const nextId = (await this.queryByGroup(group).nextOpeningId()) as OpeningId;
+
+    if (nextId.eq(0)) {
+      return [];
+    }
+
+    const query = this.queryByGroup(group).openingById();
+    const result = new MultipleLinkedMapEntry(OpeningId, WGOpening, await query);
+
+    const { linked_keys: openingIds, linked_values: openings } = result;
+    return (await Promise.all(openings.map(opening => this.hiring.openingById(opening.hiring_opening_id))))
+      .map((hiringOpeningRes, index) => {
+        const id = openingIds[index];
+        const opening = openings[index];
+        const hiringOpening = (new SingleLinkedMapEntry(Opening, hiringOpeningRes)).value;
+        return { id, opening, hiringOpening };
+      })
+      .filter(openingData => !type || openingData.opening.opening_type.isOfType(type));
+  }
+
+  public async activeOpenings (group: WorkingGroupKey, substage?: ActiveOpeningStageKey, type?: OpeningTypeKey) {
+    return (await this.allOpenings(group, type))
+      .filter(od =>
+        od.hiringOpening.stage.isOfType('Active') &&
+        (!substage || od.hiringOpening.stage.asType('Active').stage.isOfType(substage))
+      );
+  }
+
+  async wgApplicationById (group: WorkingGroupKey, wgApplicationId: number | ApplicationId): Promise<WGApplication> {
+    const nextAppId = await this.queryByGroup(group).nextApplicationId() as ApplicationId;
+
+    if (wgApplicationId < 0 || wgApplicationId >= nextAppId.toNumber()) {
+      throw new Error(`Invalid working group application ID (${wgApplicationId})!`);
     }
 
+    return new SingleLinkedMapEntry(
+      WGApplication,
+      await this.queryByGroup(group).applicationById(wgApplicationId)
+    ).value;
+  }
+
+  protected async hiringApplicationById (id: number | ApplicationId): Promise<Application> {
+    return new SingleLinkedMapEntry(
+      Application,
+      await this.hiring.applicationById(id)
+    ).value;
+  }
+
+  protected async stakeValue (stakeId: StakeId): Promise<Balance> {
+    return new SingleLinkedMapEntry(
+      Stake,
+      await this.stake.stakes(stakeId)
+    ).value.value;
+  }
+
+  protected async rewardRelationship (relationshipId: RewardRelationshipId): Promise<RewardRelationship> {
+    return new SingleLinkedMapEntry(
+      RewardRelationship,
+      await this.recurringRewards.rewardRelationships(relationshipId)
+    ).value;
+  }
+
+  protected async parseApplication (wgApplicationId: number, wgApplication: WGApplication): Promise<ParsedApplication> {
+    const appId = wgApplication.application_id;
+    const application = await this.hiringApplicationById(appId);
+
+    const { active_role_staking_id: roleStakingId, active_application_staking_id: appStakingId } = application;
+
     return {
-      worker: leadWorker,
-      profile: await this.membersT.expectedMemberProfile(leadWorker.member_id)
+      wgApplicationId,
+      applicationId: appId.toNumber(),
+      member: await this.membersT.expectedMemberProfile(wgApplication.member_id),
+      roleAccout: wgApplication.role_account_id,
+      stakes: {
+        application: appStakingId.isSome ? (await this.stakeValue(appStakingId.unwrap())).toNumber() : 0,
+        role: roleStakingId.isSome ? (await this.stakeValue(roleStakingId.unwrap())).toNumber() : 0
+      },
+      humanReadableText: application.human_readable_text.toString(),
+      stage: application.stage
     };
   }
+
+  async parsedApplicationById (group: WorkingGroupKey, wgApplicationId: number): Promise<ParsedApplication> {
+    const wgApplication = await this.wgApplicationById(group, wgApplicationId);
+    return this.parseApplication(wgApplicationId, wgApplication);
+  }
+
+  async openingApplications (group: WorkingGroupKey, wgOpeningId: number): Promise<ParsedApplication[]> {
+    const applications: ParsedApplication[] = [];
+
+    const nextAppId = await this.queryByGroup(group).nextApplicationId() as ApplicationId;
+    for (let i = 0; i < nextAppId.toNumber(); i++) {
+      const wgApplication = await this.wgApplicationById(group, i);
+      if (wgApplication.opening_id.toNumber() !== wgOpeningId) {
+        continue;
+      }
+      applications.push(await this.parseApplication(i, wgApplication));
+    }
+
+    return applications;
+  }
+
+  async openingActiveApplications (group: WorkingGroupKey, wgOpeningId: number): Promise<ParsedApplication[]> {
+    return (await this.openingApplications(group, wgOpeningId))
+      .filter(a => a.stage.isOfType('Active'));
+  }
 }

+ 10 - 2
pioneer/packages/joy-utils/src/types/proposals.ts

@@ -13,7 +13,14 @@ export const ProposalTypes = [
   'EvictStorageProvider',
   'SetValidatorCount',
   'SetStorageRoleParameters',
-  'AddWorkingGroupLeaderOpening'
+  'AddWorkingGroupLeaderOpening',
+  'SetWorkingGroupMintCapacity',
+  'BeginReviewWorkingGroupLeaderApplication',
+  'FillWorkingGroupLeaderOpening',
+  'SlashWorkingGroupLeaderStake',
+  'DecreaseWorkingGroupLeaderStake',
+  'SetWorkingGroupLeaderReward',
+  'TerminateWorkingGroupLeaderRole'
 ] as const;
 
 export type ProposalType = typeof ProposalTypes[number];
@@ -53,10 +60,10 @@ export type ProposalVotes = {
 };
 
 export const Categories = {
-  storage: 'Storage',
   council: 'Council',
   validators: 'Validators',
   cwg: 'Content Working Group',
+  wg: 'Working Groups',
   other: 'Other'
 } as const;
 
@@ -70,6 +77,7 @@ export type ProposalMeta = {
   approvalThreshold: number;
   slashingQuorum: number;
   slashingThreshold: number;
+  outdated?: boolean;
 }
 
 export type ParsedPost = {

+ 29 - 2
pioneer/packages/joy-utils/src/types/workingGroups.ts

@@ -1,7 +1,34 @@
-import { Worker } from '@joystream/types/working-group';
+import { Worker, Opening as WGOpening } from '@joystream/types/working-group';
 import { Profile } from '@joystream/types/members';
+import { OpeningId, Opening, ApplicationStage } from '@joystream/types/hiring';
+import { AccountId } from '@polkadot/types/interfaces';
+import { WorkingGroupKey } from '@joystream/types/common';
+import { RewardRelationship } from '@joystream/types/recurring-rewards';
 
-export type LeadWithProfile = {
+export type WorkerData = {
+  workerId: number;
   worker: Worker;
   profile: Profile;
+  stake?: number;
+  reward?: RewardRelationship;
+  group: WorkingGroupKey;
 };
+
+export type OpeningData = {
+  id: OpeningId;
+  opening: WGOpening;
+  hiringOpening: Opening;
+}
+
+export type ParsedApplication = {
+  wgApplicationId: number;
+  applicationId: number;
+  member: Profile;
+  roleAccout: AccountId;
+  stakes: {
+    application: number;
+    role: number;
+  };
+  humanReadableText: string;
+  stage: ApplicationStage;
+}

+ 2 - 2
runtime-modules/hiring/Cargo.toml

@@ -15,7 +15,7 @@ srml-support-procedural = { package = 'srml-support-procedural', git = 'https://
 system = { package = 'srml-system', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'}
 balances = { package = 'srml-balances', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'}
 codec = { package = 'parity-scale-codec', version = '1.0.0', default-features = false, features = ['derive'] }
-mockall = {version = "0.6.0", optional = true}
+mockall = {version = "0.7.1", optional = true}
 # https://users.rust-lang.org/t/failure-derive-compilation-error/39062
 quote = '<=1.0.2'
 
@@ -39,7 +39,7 @@ rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'
 [dev-dependencies]
 runtime-io = { package = 'sr-io', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'}
 primitives = { package = 'substrate-primitives', git = 'https://github.com/paritytech/substrate.git', rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'}
-mockall = "0.6.0"
+mockall = "0.7.1"
 
 
 [features]

+ 2 - 4
runtime-modules/proposals/codex/src/lib.rs

@@ -1053,11 +1053,9 @@ impl<T: Trait> Module<T> {
         Ok(())
     }
 
-    /// Sets default config values for the proposals.
+    /// Sets config values for the proposals.
     /// Should be called on the migration to the new runtime version.
-    pub fn set_default_config_values() {
-        let p = ProposalsConfigParameters::default();
-
+    pub fn set_config_values(p: ProposalsConfigParameters) {
         <SetValidatorCountProposalVotingPeriod<T>>::put(T::BlockNumber::from(
             p.set_validator_count_proposal_voting_period,
         ));

+ 41 - 0
runtime-modules/proposals/codex/src/proposal_types/mod.rs

@@ -220,6 +220,7 @@ pub struct RoleParameters<Balance, BlockNumber> {
 }
 
 /// Contains proposal config parameters. Default values are used by migration and genesis config.
+#[derive(Copy, Clone)]
 pub struct ProposalsConfigParameters {
     /// 'Set validator count' proposal voting period
     pub set_validator_count_proposal_voting_period: u32,
@@ -348,3 +349,43 @@ impl Default for ProposalsConfigParameters {
         }
     }
 }
+
+impl ProposalsConfigParameters {
+    /// Set same voting_period for all proposals. For proposals
+    /// that by default have 0 grace period remain with 0 grace period.
+    /// All remaining proposals get assigned grace_period.
+    pub fn with_grace_and_voting_periods(grace_period: u32, voting_period: u32) -> Self {
+        ProposalsConfigParameters {
+            set_validator_count_proposal_voting_period: voting_period,
+            set_validator_count_proposal_grace_period: 0,
+            runtime_upgrade_proposal_voting_period: voting_period,
+            runtime_upgrade_proposal_grace_period: grace_period,
+            text_proposal_voting_period: voting_period,
+            text_proposal_grace_period: 0,
+            set_election_parameters_proposal_voting_period: voting_period,
+            set_election_parameters_proposal_grace_period: grace_period,
+            set_content_working_group_mint_capacity_proposal_voting_period: voting_period,
+            set_content_working_group_mint_capacity_proposal_grace_period: 0,
+            set_lead_proposal_voting_period: voting_period,
+            set_lead_proposal_grace_period: 0,
+            spending_proposal_voting_period: voting_period,
+            spending_proposal_grace_period: grace_period,
+            add_working_group_opening_proposal_voting_period: voting_period,
+            add_working_group_opening_proposal_grace_period: 0,
+            begin_review_working_group_leader_applications_proposal_voting_period: voting_period,
+            begin_review_working_group_leader_applications_proposal_grace_period: grace_period,
+            fill_working_group_leader_opening_proposal_voting_period: voting_period,
+            fill_working_group_leader_opening_proposal_grace_period: 0,
+            set_working_group_mint_capacity_proposal_voting_period: voting_period,
+            set_working_group_mint_capacity_proposal_grace_period: 0,
+            decrease_working_group_leader_stake_proposal_voting_period: voting_period,
+            decrease_working_group_leader_stake_proposal_grace_period: 0,
+            slash_working_group_leader_stake_proposal_voting_period: voting_period,
+            slash_working_group_leader_stake_proposal_grace_period: 0,
+            set_working_group_leader_reward_proposal_voting_period: voting_period,
+            set_working_group_leader_reward_proposal_grace_period: 0,
+            terminate_working_group_leader_role_proposal_voting_period: voting_period,
+            terminate_working_group_leader_role_proposal_grace_period: 0,
+        }
+    }
+}

+ 65 - 1
runtime-modules/proposals/codex/src/tests/mod.rs

@@ -802,7 +802,7 @@ fn set_default_proposal_parameters_succeeded() {
         // nothing is set
         assert_eq!(<SetValidatorCountProposalVotingPeriod<Test>>::get(), 0);
 
-        ProposalCodex::set_default_config_values();
+        ProposalCodex::set_config_values(p);
 
         assert_eq!(
             <SetValidatorCountProposalVotingPeriod<Test>>::get(),
@@ -860,6 +860,70 @@ fn set_default_proposal_parameters_succeeded() {
             <SpendingProposalGracePeriod<Test>>::get(),
             p.spending_proposal_grace_period as u64
         );
+        assert_eq!(
+            <AddWorkingGroupOpeningProposalVotingPeriod<Test>>::get(),
+            p.add_working_group_opening_proposal_voting_period as u64
+        );
+        assert_eq!(
+            <AddWorkingGroupOpeningProposalGracePeriod<Test>>::get(),
+            p.add_working_group_opening_proposal_grace_period as u64
+        );
+        assert_eq!(
+            <BeginReviewWorkingGroupLeaderApplicationsProposalVotingPeriod<Test>>::get(),
+            p.begin_review_working_group_leader_applications_proposal_voting_period as u64
+        );
+        assert_eq!(
+            <BeginReviewWorkingGroupLeaderApplicationsProposalGracePeriod<Test>>::get(),
+            p.begin_review_working_group_leader_applications_proposal_grace_period as u64
+        );
+        assert_eq!(
+            <FillWorkingGroupLeaderOpeningProposalVotingPeriod<Test>>::get(),
+            p.fill_working_group_leader_opening_proposal_voting_period as u64
+        );
+        assert_eq!(
+            <FillWorkingGroupLeaderOpeningProposalGracePeriod<Test>>::get(),
+            p.fill_working_group_leader_opening_proposal_grace_period as u64
+        );
+        assert_eq!(
+            <SetWorkingGroupMintCapacityProposalVotingPeriod<Test>>::get(),
+            p.set_working_group_mint_capacity_proposal_voting_period as u64
+        );
+        assert_eq!(
+            <SetWorkingGroupMintCapacityProposalGracePeriod<Test>>::get(),
+            p.set_working_group_mint_capacity_proposal_grace_period as u64
+        );
+        assert_eq!(
+            <DecreaseWorkingGroupLeaderStakeProposalVotingPeriod<Test>>::get(),
+            p.decrease_working_group_leader_stake_proposal_voting_period as u64
+        );
+        assert_eq!(
+            <DecreaseWorkingGroupLeaderStakeProposalGracePeriod<Test>>::get(),
+            p.decrease_working_group_leader_stake_proposal_grace_period as u64
+        );
+        assert_eq!(
+            <SlashWorkingGroupLeaderStakeProposalVotingPeriod<Test>>::get(),
+            p.slash_working_group_leader_stake_proposal_voting_period as u64
+        );
+        assert_eq!(
+            <SlashWorkingGroupLeaderStakeProposalGracePeriod<Test>>::get(),
+            p.slash_working_group_leader_stake_proposal_grace_period as u64
+        );
+        assert_eq!(
+            <SetWorkingGroupLeaderRewardProposalVotingPeriod<Test>>::get(),
+            p.set_working_group_leader_reward_proposal_voting_period as u64
+        );
+        assert_eq!(
+            <SetWorkingGroupLeaderRewardProposalGracePeriod<Test>>::get(),
+            p.set_working_group_leader_reward_proposal_grace_period as u64
+        );
+        assert_eq!(
+            <TerminateWorkingGroupLeaderRoleProposalVotingPeriod<Test>>::get(),
+            p.terminate_working_group_leader_role_proposal_voting_period as u64
+        );
+        assert_eq!(
+            <TerminateWorkingGroupLeaderRoleProposalGracePeriod<Test>>::get(),
+            p.terminate_working_group_leader_role_proposal_grace_period as u64
+        );
     });
 }
 

+ 1 - 1
runtime-modules/proposals/engine/Cargo.toml

@@ -96,7 +96,7 @@ package = 'substrate-common-module'
 path = '../../common'
 
 [dev-dependencies]
-mockall = "0.6.0"
+mockall = "0.7.1"
 
 [dev-dependencies.runtime-io]
 default_features = false

+ 1 - 1
runtime/Cargo.toml

@@ -4,7 +4,7 @@ edition = '2018'
 name = 'joystream-node-runtime'
 # Follow convention: https://github.com/Joystream/substrate-runtime-joystream/issues/1
 # {Authoring}.{Spec}.{Impl} of the RuntimeVersion
-version = '6.20.0'
+version = '6.21.0'
 
 [features]
 default = ['std']

+ 26 - 0
runtime/README.md

@@ -0,0 +1,26 @@
+## Joystream Runtime
+
+![Joystream Runtime](./runtime-banner.svg)
+
+
+The runtime is the code that defines the consensus rules of the Joystream protocol.
+It is compiled to WASM and lives on chain.
+Joystream node execute the code's logic to validate transactions and blocks on the blockchain.
+
+When building joystream-node as described in [../node/README.md](../node/README.md) with `cargo build --release`, in addition to the joystream-node binary being built the WASM blob artifact is produced in:
+
+`target/release/wbuild/joystream-node-runtime/joystream_node_runtime.compact.wasm`
+
+
+### Deployment
+
+Deploying the compiled runtime on a live system can be done in one of two ways:
+
+1. By creating a proposal for upgrading the Joystream runtime, which will then be voted on by the council. If the proposal is approved, the upgrade will go through after a grace period. When the Joystream platform is live, this will be the only way to upgrade the chain's runtime code.
+
+2. By creating  an extrinsic (transaction) signed with the sudo key invoking `system::setCode()`. This can be done either from the [Pioneer](/pioneer) extrinsics tab, or directly with an admin script. This way of upgrading the runtime code is intended for development and testnet phases only.
+
+### Versioning the runtime
+
+Versioning of the runtime is set in `runtime/src/lib.rs`
+For detailed information about how to set correct version numbers when developing a new runtime, [see this](https://github.com/Joystream/joystream/issues/1)

+ 1 - 1
runtime/src/lib.rs

@@ -160,7 +160,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
     spec_name: create_runtime_str!("joystream-node"),
     impl_name: create_runtime_str!("joystream-node"),
     authoring_version: 6,
-    spec_version: 20,
+    spec_version: 21,
     impl_version: 0,
     apis: RUNTIME_API_VERSIONS,
 };

+ 2 - 1
runtime/src/migration.rs

@@ -2,6 +2,7 @@
 #![allow(clippy::redundant_closure_call)] // disable it because of the substrate lib design
 
 use crate::VERSION;
+use proposals_codex::ProposalsConfigParameters;
 use rstd::prelude::*;
 use sr_primitives::{
     print,
@@ -26,7 +27,7 @@ impl<T: Trait> Module<T> {
         Self::initialize_storage_working_group_text_constraints();
         Self::clear_storage_data();
 
-        proposals_codex::Module::<T>::set_default_config_values();
+        proposals_codex::Module::<T>::set_config_values(ProposalsConfigParameters::default());
     }
 }
 

+ 2 - 1
scripts/create-test-chainspec.sh

@@ -9,4 +9,5 @@ perl -i -pe's/"setContentWorkingGroupMintCapacityProposalGracePeriod":.*/"setCon
 perl -i -pe's/"setLeadProposalGracePeriod":.*/"setLeadProposalGracePeriod": 0,/' .tmp/chainspec.json
 perl -i -pe's/"spendingProposalGracePeriod":.*/"spendingProposalGracePeriod": 0,/' .tmp/chainspec.json
 perl -i -pe's/"evictStorageProviderProposalGracePeriod":.*/"evictStorageProviderProposalGracePeriod": 0,/' .tmp/chainspec.json
-perl -i -pe's/"setStorageRoleParametersProposalGracePeriod":.*/"setStorageRoleParametersProposalGracePeriod": 0/' .tmp/chainspec.json
+perl -i -pe's/"beginReviewWorkingGroupLeaderApplicationsProposalGracePeriod":.*/"beginReviewWorkingGroupLeaderApplicationsProposalGracePeriod": 0,/' .tmp/chainspec.json
+perl -i -pe's/"setStorageRoleParametersProposalGracePeriod":.*/"setStorageRoleParametersProposalGracePeriod": 0,/' .tmp/chainspec.json

+ 1 - 0
storage-node/.eslintrc.js

@@ -13,6 +13,7 @@ module.exports = {
     'no-console': 'off', // we use console in the project
     '@typescript-eslint/no-var-requires': 'warn',
     '@typescript-eslint/camelcase': 'warn',
+    '@typescript-eslint/naming-convention': 'off',
   },
   overrides: [
     {

+ 3 - 3
storage-node/package.json

@@ -3,8 +3,8 @@
   "name": "storage-node",
   "version": "1.0.0",
   "engines": {
-    "node": ">=10.15.3",
-    "yarn": "^1.15.2"
+    "node": ">=12.18.0",
+    "yarn": "^1.22.0"
   },
   "homepage": "https://github.com/Joystream/joystream/",
   "bugs": {
@@ -32,7 +32,7 @@
   ],
   "scripts": {
     "test": "wsrun --serial test",
-    "lint": "eslint --ignore-path .gitignore .",
+    "lint": "eslint --ext .js,.ts --ignore-path .gitignore .",
     "build": "yarn workspace @joystream/storage-cli run build",
     "checks": "yarn lint && prettier . --check",
     "format": "prettier . --write"

+ 3 - 3
storage-node/packages/cli/package.json

@@ -24,11 +24,11 @@
     "linux"
   ],
   "engines": {
-    "node": ">=10.15.3"
+    "node": ">=12.18.0"
   },
   "scripts": {
     "test": "mocha 'dist/test/**/*.js'",
-    "lint": "eslint --ext .ts,.tsx . && tsc --noEmit --pretty",
+    "lint": "eslint --ext .js,.ts . && tsc --noEmit --pretty",
     "build": "tsc --build"
   },
   "bin": {
@@ -44,7 +44,7 @@
     "@joystream/storage-runtime-api": "^0.1.0",
     "@joystream/service-discovery": "^0.1.0",
     "@joystream/storage-utils": "^0.1.0",
-    "@joystream/types": "^0.11.0",
+    "@joystream/types": "^0.12.0",
     "axios": "^0.19.2",
     "chalk": "^2.4.2",
     "lodash": "^4.17.11",

+ 6 - 1
storage-node/packages/cli/src/cli.ts

@@ -121,7 +121,12 @@ export async function main() {
   if (Object.prototype.hasOwnProperty.call(commands, command)) {
     // Command recognized
     const args = _.clone(cli.input).slice(1)
-    await commands[command](api, ...args)
+    try {
+      await commands[command](api, ...args)
+    } catch (err) {
+      console.error('Command Failed:', err)
+      process.exit(-1)
+    }
   } else {
     showUsageAndExit(`Command "${command}" not recognized.`)
   }

+ 4 - 4
storage-node/packages/cli/src/commands/dev.ts

@@ -45,14 +45,14 @@ const batchDispatchCalls = async (
 
   debug(`dispatching ${rawCalls.length} transactions.`)
 
-  await rawCalls
-    .map((call) => {
+  // promise.all to avoid unhandled promise rejection
+  return Promise.all(
+    rawCalls.map((call) => {
       const { methodName, sectionName, args } = call
       const tx = api.tx[sectionName][methodName](...args)
       return runtimeApi.signAndSend(senderAddress, tx)
     })
-    .reverse()
-    .shift()
+  )
 }
 
 // Dispatch pre-prepared calls to runtime to initialize the versioned store

+ 35 - 10
storage-node/packages/colossus/bin/cli.js

@@ -29,15 +29,19 @@ const FLAG_DEFINITIONS = {
   },
   keyFile: {
     type: 'string',
-    isRequired: (flags) => {
-      return !flags.dev
+    isRequired: (flags, input) => {
+      // Only required if running server command and not in dev mode
+      const serverCmd = input[0] === 'server'
+      return !flags.dev && serverCmd
     },
   },
   publicUrl: {
     type: 'string',
     alias: 'u',
-    isRequired: (flags) => {
-      return !flags.dev
+    isRequired: (flags, input) => {
+      // Only required if running server command and not in dev mode
+      const serverCmd = input[0] === 'server'
+      return !flags.dev && serverCmd
     },
   },
   passphrase: {
@@ -50,8 +54,10 @@ const FLAG_DEFINITIONS = {
   providerId: {
     type: 'number',
     alias: 'i',
-    isRequired: (flags) => {
-      return !flags.dev
+    isRequired: (flags, input) => {
+      // Only required if running server command and not in dev mode
+      const serverCmd = input[0] === 'server'
+      return !flags.dev && serverCmd
     },
   },
 }
@@ -105,13 +111,13 @@ function startExpressApp(app, port) {
 
 // Start app
 function startAllServices({ store, api, port }) {
-  const app = require('../lib/app')(PROJECT_ROOT, store, api) // reduce falgs to only needed values
+  const app = require('../lib/app')(PROJECT_ROOT, store, api)
   return startExpressApp(app, port)
 }
 
 // Start discovery service app only
 function startDiscoveryService({ api, port }) {
-  const app = require('../lib/discovery')(PROJECT_ROOT, api) // reduce flags to only needed values
+  const app = require('../lib/discovery')(PROJECT_ROOT, api)
   return startExpressApp(app, port)
 }
 
@@ -136,6 +142,21 @@ function getStorage(runtimeApi) {
   return Storage.create(options)
 }
 
+async function untilChainIsSynched(api) {
+  while (true) {
+    const health = await api.api.rpc.system.health()
+
+    if (health.isSyncing.isTrue) {
+      debug('Waiting for chain to be synced...')
+      await new Promise((resolve) => {
+        setTimeout(resolve, 1 * 30 * 1000)
+      })
+    } else {
+      return
+    }
+  }
+}
+
 async function initApiProduction({ wsProvider, providerId, keyFile, passphrase }) {
   // Load key information
   const { RuntimeApi } = require('@joystream/storage-runtime-api')
@@ -159,6 +180,8 @@ async function initApiProduction({ wsProvider, providerId, keyFile, passphrase }
     throw new Error('Failed to unlock storage provider account')
   }
 
+  await untilChainIsSynched(api)
+
   if (!(await api.workers.isRoleAccountOfStorageProvider(api.storageProviderId, api.identities.key.address))) {
     throw new Error('storage provider role account and storageProviderId are not associated with a worker')
   }
@@ -199,6 +222,8 @@ function getServiceInformation(publicUrl) {
   }
 }
 
+// TODO: instead of recursion use while/async-await and use promise/setTimout based sleep
+// or cleaner code with generators?
 async function announcePublicUrl(api, publicUrl) {
   // re-announce in future
   const reannounce = function (timeoutMs) {
@@ -238,14 +263,14 @@ if (!command) {
   command = 'server'
 }
 
-async function startColossus({ api, publicUrl, port, flags }) {
+async function startColossus({ api, publicUrl, port }) {
   // TODO: check valid url, and valid port number
   const store = getStorage(api)
   banner()
   const { startSyncing } = require('../lib/sync')
   startSyncing(api, { syncPeriod: SYNC_PERIOD_MS }, store)
   announcePublicUrl(api, publicUrl)
-  return startAllServices({ store, api, port, flags }) // dont pass all flags only required values
+  return startAllServices({ store, api, port })
 }
 
 const commands = {

+ 1 - 1
storage-node/packages/colossus/lib/sync.js

@@ -66,7 +66,7 @@ async function syncCallback(api, storage) {
       // create relationship
       debug(`Creating new storage relationship for ${contentId.encode()}`)
       try {
-        relationshipId = await api.assets.createAndReturnStorageRelationship(roleAddress, providerId, contentId)
+        relationshipId = await api.assets.createStorageRelationship(roleAddress, providerId, contentId)
         await api.assets.toggleStorageRelationshipReady(roleAddress, providerId, relationshipId, true)
       } catch (err) {
         debug(`Error creating new storage relationship ${contentId.encode()}: ${err.stack}`)

+ 1 - 1
storage-node/packages/colossus/package.json

@@ -29,7 +29,7 @@
     "linux"
   ],
   "engines": {
-    "node": ">=10.15.3"
+    "node": ">=12.18.0"
   },
   "scripts": {
     "test": "mocha 'test/**/*.js'",

+ 1 - 1
storage-node/packages/colossus/paths/asset/v0/{id}.js

@@ -157,7 +157,7 @@ module.exports = function (storage, runtime) {
 
             debug('creating storage relationship for newly uploaded content')
             // Create storage relationship and flip it to ready.
-            const dosrId = await runtime.assets.createAndReturnStorageRelationship(roleAddress, providerId, id)
+            const dosrId = await runtime.assets.createStorageRelationship(roleAddress, providerId, id)
 
             debug('toggling storage relationship for newly uploaded content')
             await runtime.assets.toggleStorageRelationshipReady(roleAddress, providerId, dosrId, true)

+ 1 - 1
storage-node/packages/discovery/package.json

@@ -29,7 +29,7 @@
     "linux"
   ],
   "engines": {
-    "node": ">=10.15.3"
+    "node": ">=12.18.0"
   },
   "main": "./index.js",
   "scripts": {

+ 10 - 25
storage-node/packages/runtime-api/assets.js

@@ -95,17 +95,6 @@ class AssetsApi {
     return this.base.signAndSend(providerAccountId, tx)
   }
 
-  /*
-   * Creates storage relationship for a data object and provider
-   */
-  async createStorageRelationship(providerAccountId, storageProviderId, contentId, callback) {
-    contentId = parseContentId(contentId)
-    const tx = this.base.api.tx.dataObjectStorageRegistry.addRelationship(storageProviderId, contentId)
-
-    const subscribed = [['dataObjectStorageRegistry', 'DataObjectStorageRelationshipAdded']]
-    return this.base.signAndSend(providerAccountId, tx, 3, subscribed, callback)
-  }
-
   /*
    * Gets storage relationship for contentId for the given provider
    */
@@ -126,22 +115,18 @@ class AssetsApi {
   }
 
   /*
-   * Creates storage relationship for a data object and provider and returns the relationship id
+   * Creates storage relationship for a data object and provider and
+   * returns the relationship id
    */
-  async createAndReturnStorageRelationship(providerAccountId, storageProviderId, contentId) {
+  async createStorageRelationship(providerAccountId, storageProviderId, contentId) {
     contentId = parseContentId(contentId)
-    // TODO: rewrite this method to async-await style
-    // eslint-disable-next-line  no-async-promise-executor
-    return new Promise(async (resolve, reject) => {
-      try {
-        await this.createStorageRelationship(providerAccountId, storageProviderId, contentId, (events) => {
-          events.forEach((event) => {
-            resolve(event[1].DataObjectStorageRelationshipId)
-          })
-        })
-      } catch (err) {
-        reject(err)
-      }
+    const tx = this.base.api.tx.dataObjectStorageRegistry.addRelationship(storageProviderId, contentId)
+
+    return this.base.signAndSendThenGetEventResult(providerAccountId, tx, {
+      module: 'dataObjectStorageRegistry',
+      event: 'DataObjectStorageRelationshipAdded',
+      type: 'DataObjectStorageRelationshipId',
+      index: 0,
     })
   }
 

+ 4 - 3
storage-node/packages/runtime-api/identities.js

@@ -186,9 +186,10 @@ class IdentitiesApi {
     const tx = this.base.api.tx.members.buyMembership(0, userInfo)
 
     return this.base.signAndSendThenGetEventResult(accountId, tx, {
-      eventModule: 'members',
-      eventName: 'MemberRegistered',
-      eventProperty: 'MemberId',
+      module: 'members',
+      event: 'MemberRegistered',
+      type: 'MemberId',
+      index: 0,
     })
   }
 

+ 211 - 174
storage-node/packages/runtime-api/index.js

@@ -22,7 +22,6 @@ const debug = require('debug')('joystream:runtime:base')
 
 const { registerJoystreamTypes } = require('@joystream/types')
 const { ApiPromise, WsProvider } = require('@polkadot/api')
-
 const { IdentitiesApi } = require('@joystream/storage-runtime-api/identities')
 const { BalancesApi } = require('@joystream/storage-runtime-api/balances')
 const { WorkersApi } = require('@joystream/storage-runtime-api/workers')
@@ -30,7 +29,13 @@ const { AssetsApi } = require('@joystream/storage-runtime-api/assets')
 const { DiscoveryApi } = require('@joystream/storage-runtime-api/discovery')
 const { SystemApi } = require('@joystream/storage-runtime-api/system')
 const AsyncLock = require('async-lock')
-const { newExternallyControlledPromise } = require('@joystream/storage-utils/externalPromise')
+const Promise = require('bluebird')
+
+Promise.config({
+  cancellation: true,
+})
+
+const TX_TIMEOUT = 20 * 1000
 
 /*
  * Initialize runtime (substrate) API and keyring.
@@ -65,7 +70,7 @@ class RuntimeApi {
 
     // Ok, create individual APIs
     this.identities = await IdentitiesApi.create(this, {
-      account_file: options.account_file,
+      accountFile: options.account_file,
       passphrase: options.passphrase,
       canPromptForPassphrase: options.canPromptForPassphrase,
     })
@@ -84,225 +89,257 @@ class RuntimeApi {
     return this.asyncLock.acquire(`${accountId}`, func)
   }
 
-  /*
-   * Wait for an event. Filters out any events that don't match the module and
-   * event name.
-   *
-   * The result of the Promise is an array containing first the full event
-   * name, and then the event fields as an object.
-   */
-  async waitForEvent(module, name) {
-    return this.waitForEvents([[module, name]])
-  }
-
-  static matchingEvents(subscribed, events) {
-    debug(`Number of events: ${events.length} subscribed to ${subscribed}`)
-
+  static matchingEvents(subscribed = [], events = []) {
     const filtered = events.filter((record) => {
-      const { event, phase } = record
-
-      // Show what we are busy with
-      debug(`\t${event.section}:${event.method}:: (phase=${phase.toString()})`)
-      debug(`\t\t${event.meta.documentation.toString()}`)
+      const { event } = record
 
       // Skip events we're not interested in.
       const matching = subscribed.filter((value) => {
-        return event.section === value[0] && event.method === value[1]
+        if (value[0] === '*' && value[1] === '*') {
+          return true
+        } else if (value[0] === '*') {
+          return event.method === value[1]
+        } else if (value[1] === '*') {
+          return event.section === value[0]
+        } else {
+          return event.section === value[0] && event.method === value[1]
+        }
       })
       return matching.length > 0
     })
-    debug(`Filtered: ${filtered.length}`)
 
-    const mapped = filtered.map((record) => {
+    return filtered.map((record) => {
       const { event } = record
       const types = event.typeDef
+      const payload = new Map()
 
-      // Loop through each of the parameters, displaying the type and data
-      const payload = {}
-      event.data.forEach((data, index) => {
-        debug(`\t\t\t${types[index].type}: ${data.toString()}`)
-        payload[types[index].type] = data
-      })
-
+      // this check may be un-necessary but doing it just incase
+      if (event.data) {
+        event.data.forEach((data, index) => {
+          const type = types[index].type
+          payload.set(index, { type, data })
+        })
+      }
       const fullName = `${event.section}.${event.method}`
+      debug(`matched event: ${fullName} =>`, event.data && event.data.join(', '))
       return [fullName, payload]
     })
-    debug('Mapped', mapped)
+  }
 
-    return mapped
+  // Get cached nonce and use unless system nonce is greater, to avoid stale nonce if
+  // there was a long gap in time between calls to signAndSend during which an external app
+  // submitted a transaction.
+  async selectBestNonce(accountId) {
+    const cachedNonce = this.nonces[accountId]
+    // In future use this rpc method to take the pending tx pool into account when fetching the nonce
+    // const nonce = await this.api.rpc.system.accountNextIndex(accountId)
+    const systemNonce = await this.api.query.system.accountNonce(accountId)
+
+    if (cachedNonce) {
+      // we have it cached.. but lets do a look ahead to see if we need to adjust
+      if (systemNonce.gt(cachedNonce)) {
+        return systemNonce
+      } else {
+        return cachedNonce
+      }
+    } else {
+      return systemNonce
+    }
   }
 
-  /*
-   * Same as waitForEvent, but filter on multiple events. The parameter is an
-   * array of arrays containing module and name. Calling waitForEvent is
-   * identical to calling this with [[module, name]].
-   *
-   * Returns the first matched event *only*.
-   */
-  async waitForEvents(subscribed) {
-    return new Promise((resolve) => {
-      this.api.query.system.events((events) => {
-        const matches = RuntimeApi.matchingEvents(subscribed, events)
-        if (matches && matches.length) {
-          resolve(matches)
-        }
-      })
-    })
+  incrementAndSaveNonce(accountId, nonce) {
+    this.nonces[accountId] = nonce.addn(1)
   }
 
   /*
-   * Nonce-aware signAndSend(). Also allows you to use the accountId instead
-   * of the key, making calls a little simpler. Will lock to prevent concurrent
-   * calls so correct nonce is used.
+   * signAndSend() with nonce tracking, to enable concurrent sending of transacctions
+   * so that they can be included in the same block. Allows you to use the accountId instead
+   * of the key, without requiring an external Signer configured on the underlying ApiPromie
    *
    * If the subscribed events are given, and a callback as well, then the
    * callback is invoked with matching events.
    */
-  async signAndSend(accountId, tx, attempts, subscribed, callback) {
+  async signAndSend(accountId, tx, subscribed) {
+    // Accept both a string or AccountId as argument
     accountId = this.identities.keyring.encodeAddress(accountId)
 
-    // Key must be unlocked
+    // Throws if keyPair is not found
     const fromKey = this.identities.keyring.getPair(accountId)
+
+    // Key must be unlocked to use
     if (fromKey.isLocked) {
       throw new Error('Must unlock key before using it to sign!')
     }
 
-    const finalizedPromise = newExternallyControlledPromise()
+    // Functions to be called when the submitted transaction is finalized. They are initialized
+    // after the transaction is submitted to the resolve and reject function of the final promise
+    // returned by signAndSend
+    // on extrinsic success
+    let onFinalizedSuccess
+    // on extrinsic failure
+    let onFinalizedFailed
 
-    await this.executeWithAccountLock(accountId, async () => {
-      // Try to get the next nonce to use
-      let nonce = this.nonces[accountId]
+    // Function assigned when transaction is successfully submitted. Invoking it ubsubscribes from
+    // listening to tx status updates.
+    let unsubscribe
 
-      let incrementNonce = () => {
-        // only increment once
-        incrementNonce = () => {
-          /* turn it into a no-op */
-        }
-        nonce = nonce.addn(1)
-        this.nonces[accountId] = nonce
-      }
+    let lastTxUpdateResult
 
-      // If the nonce isn't available, get it from chain.
-      if (!nonce) {
-        // current nonce
-        // TODO: possible race condition here found by the linter
-        // eslint-disable-next-line require-atomic-updates
-        nonce = await this.api.query.system.accountNonce(accountId)
-        debug(`Got nonce for ${accountId} from chain: ${nonce}`)
+    const handleTxUpdates = (result) => {
+      const { events = [], status } = result
+
+      if (!result || !status) {
+        return
       }
 
-      return new Promise((resolve, reject) => {
-        debug('Signing and sending tx')
-        // send(statusUpdates) returns a function for unsubscribing from status updates
-        const unsubscribe = tx
-          .sign(fromKey, { nonce })
-          .send(({ events = [], status }) => {
-            debug(`TX status: ${status.type}`)
-
-            // Whatever events we get, process them if there's someone interested.
-            // It is critical that this event handling doesn't prevent
-            try {
-              if (subscribed && callback) {
-                const matched = RuntimeApi.matchingEvents(subscribed, events)
-                debug('Matching events:', matched)
-                if (matched.length) {
-                  callback(matched)
-                }
-              }
-            } catch (err) {
-              debug(`Error handling events ${err.stack}`)
+      lastTxUpdateResult = result
+
+      if (result.isError) {
+        unsubscribe()
+        debug('Tx Error', status.type)
+        onFinalizedFailed &&
+          onFinalizedFailed({ err: status.type, result, tx: status.isUsurped ? status.asUsurped : undefined })
+      } else if (result.isFinalized) {
+        unsubscribe()
+        const mappedEvents = RuntimeApi.matchingEvents(subscribed, events)
+        const failed = result.findRecord('system', 'ExtrinsicFailed')
+        const success = result.findRecord('system', 'ExtrinsicSuccess')
+        const sudid = result.findRecord('sudo', 'Sudid')
+        const sudoAsDone = result.findRecord('sudo', 'SudoAsDone')
+
+        if (failed) {
+          const {
+            event: { data },
+          } = failed
+          const dispatchError = data[0]
+          onFinalizedFailed({
+            err: 'ExtrinsicFailed',
+            mappedEvents,
+            result,
+            block: status.asFinalized,
+            dispatchError, // we get module number/id and index into the Error enum
+          })
+        } else if (success) {
+          // Note: For root origin calls, the dispatch error is logged to the joystream-node
+          // console, we cannot get it in the events
+          if (sudid) {
+            const dispatchSuccess = sudid.event.data[0]
+            if (dispatchSuccess.isTrue) {
+              onFinalizedSuccess({ mappedEvents, result, block: status.asFinalized })
+            } else {
+              onFinalizedFailed({ err: 'SudoFailed', mappedEvents, result, block: status.asFinalized })
             }
-
-            // We want to release lock as early as possible, sometimes Ready status
-            // doesn't occur, so we do it on Broadcast instead
-            if (status.isReady) {
-              debug('TX Ready.')
-              incrementNonce()
-              resolve(unsubscribe) // releases lock
-            } else if (status.isBroadcast) {
-              debug('TX Broadcast.')
-              incrementNonce()
-              resolve(unsubscribe) // releases lock
-            } else if (status.isFinalized) {
-              debug('TX Finalized.')
-              finalizedPromise.resolve(status)
-            } else if (status.isFuture) {
-              // comes before ready.
-              // does that mean it will remain in mempool or in api internal queue?
-              // nonce was set in the future. Treating it as an error for now.
-              debug('TX Future!')
-              // nonce is likely out of sync, delete it so we reload it from chain on next attempt
-              delete this.nonces[accountId]
-              const err = new Error('transaction nonce set in future')
-              finalizedPromise.reject(err)
-              reject(err)
+          } else if (sudoAsDone) {
+            const dispatchSuccess = sudoAsDone.event.data[0]
+            if (dispatchSuccess.isTrue) {
+              onFinalizedSuccess({ mappedEvents, result, block: status.asFinalized })
+            } else {
+              onFinalizedFailed({ err: 'SudoAsFailed', mappedEvents, result, block: status.asFinalized })
             }
+          } else {
+            onFinalizedSuccess({ mappedEvents, result, block: status.asFinalized })
+          }
+        }
+      }
+    }
 
-            /* why don't we see these status updates on local devchain (single node)
-            isUsurped
-            isBroadcast
-            isDropped
-            isInvalid
-            */
-          })
-          .catch((err) => {
-            // 1014 error: Most likely you are sending transaction with the same nonce,
-            // so it assumes you want to replace existing one, but the priority is too low to replace it (priority = fee = len(encoded_transaction) currently)
-            // Remember this can also happen if in the past we sent a tx with a future nonce, and the current nonce
-            // now matches it.
-            if (err) {
-              const errstr = err.toString()
-              // not the best way to check error code.
-              // https://github.com/polkadot-js/api/blob/master/packages/rpc-provider/src/coder/index.ts#L52
-              if (
-                errstr.indexOf('Error: 1014:') < 0 && // low priority
-                errstr.indexOf('Error: 1010:') < 0
-              ) {
-                // bad transaction
-                // Error but not nonce related. (bad arguments maybe)
-                debug('TX error', err)
-              } else {
-                // nonce is likely out of sync, delete it so we reload it from chain on next attempt
-                delete this.nonces[accountId]
-              }
-            }
+    // synchronize access to nonce
+    await this.executeWithAccountLock(accountId, async () => {
+      const nonce = await this.selectBestNonce(accountId)
 
-            finalizedPromise.reject(err)
-            // releases lock
-            reject(err)
-          })
-      })
+      try {
+        unsubscribe = await tx.sign(fromKey, { nonce }).send(handleTxUpdates)
+        debug('TransactionSubmitted')
+        // transaction submitted successfully, increment and save nonce.
+        this.incrementAndSaveNonce(accountId, nonce)
+      } catch (err) {
+        const errstr = err.toString()
+        debug('TransactionRejected:', errstr)
+        // This happens when nonce is already used in finalized transactions, ie. the selected nonce
+        // was less than current account nonce. A few scenarios where this happens (other than incorrect code)
+        // 1. When a past future tx got finalized because we submitted some transactions
+        // using up the nonces upto that point.
+        // 2. Can happen while storage-node is talkig to a joystream-node that is still not fully
+        // synced.
+        // 3. Storage role account holder sent a transaction just ahead of us via another app.
+        if (errstr.indexOf('ExtrinsicStatus:: 1010: Invalid Transaction: Stale') !== -1) {
+          // In case 1 or 3 a quick recovery could work by just incrementing, but since we
+          // cannot detect which case we are in just reset and force re-reading nonce. Even
+          // that may not be sufficient expect after a few more failures..
+          delete this.nonces[accountId]
+        }
+
+        // Technically it means a transaction in the mempool with same
+        // nonce and same fees being paid so we cannot replace it, either we didn't correctly
+        // increment the nonce or someone external to this application sent a transaction
+        // with same nonce ahead of us.
+        if (errstr.indexOf('ExtrinsicStatus:: 1014: Priority is too low') !== -1) {
+          delete this.nonces[accountId]
+        }
+
+        throw err
+      }
     })
 
-    // when does it make sense to manyally unsubscribe?
-    // at this point unsubscribe.then and unsubscribe.catch have been deleted
-    // unsubscribe() // don't unsubscribe if we want to wait for additional status
-    // updates to know when the tx has been finalized
-    return finalizedPromise.promise
+    // We cannot get tx updates for a future tx so return now to avoid blocking caller
+    if (lastTxUpdateResult.status.isFuture) {
+      debug('Warning: Submitted extrinsic with future nonce')
+      return {}
+    }
+
+    // Return a promise that will resolve when the transaction finalizes.
+    // On timeout it will be rejected. Timeout is a workaround for dealing with the
+    // fact that if rpc connection is lost to node we have no way of detecting it or recovering.
+    // Timeout can also occur if a transaction that was part of batch of transactions submitted
+    // gets usurped.
+    return new Promise((resolve, reject) => {
+      onFinalizedSuccess = resolve
+      onFinalizedFailed = reject
+    }).timeout(TX_TIMEOUT)
   }
 
   /*
    * Sign and send a transaction expect event from
    * module and return eventProperty from the event.
    */
-  async signAndSendThenGetEventResult(senderAccountId, tx, { eventModule, eventName, eventProperty }) {
-    // event from a module,
-    const subscribed = [[eventModule, eventName]]
-    // TODO: rewrite this method to async-await style
-    // eslint-disable-next-line  no-async-promise-executor
-    return new Promise(async (resolve, reject) => {
-      try {
-        await this.signAndSend(senderAccountId, tx, 1, subscribed, (events) => {
-          events.forEach((event) => {
-            // fix - we may not necessarily want the first event
-            // if there are multiple events emitted,
-            resolve(event[1][eventProperty])
-          })
-        })
-      } catch (err) {
-        reject(err)
-      }
-    })
+  async signAndSendThenGetEventResult(senderAccountId, tx, { module, event, index, type }) {
+    if (!module || !event || index === undefined || !type) {
+      throw new Error('MissingSubscribeEventDetails')
+    }
+
+    const subscribed = [[module, event]]
+
+    const { mappedEvents } = await this.signAndSend(senderAccountId, tx, subscribed)
+
+    if (!mappedEvents) {
+      // The tx was a future so it was not possible and will not be possible to get events
+      throw new Error('NoEventsWereCaptured')
+    }
+
+    if (!mappedEvents.length) {
+      // our expected event was not emitted
+      throw new Error('ExpectedEventNotFound')
+    }
+
+    // fix - we may not necessarily want the first event
+    // when there are multiple instances of the same event
+    const firstEvent = mappedEvents[0]
+
+    if (firstEvent[0] !== `${module}.${event}`) {
+      throw new Error('WrongEventCaptured')
+    }
+
+    const payload = firstEvent[1]
+    if (!payload.has(index)) {
+      throw new Error('DataIndexOutOfRange')
+    }
+
+    const value = payload.get(index)
+    if (value.type !== type) {
+      throw new Error('DataTypeNotExpectedType')
+    }
+
+    return value.data
   }
 }
 

+ 2 - 2
storage-node/packages/runtime-api/package.json

@@ -30,7 +30,7 @@
     "linux"
   ],
   "engines": {
-    "node": ">=10.15.3"
+    "node": ">=12.18.0"
   },
   "scripts": {
     "test": "mocha 'test/**/*.js' --exit",
@@ -45,7 +45,7 @@
     "temp": "^0.9.0"
   },
   "dependencies": {
-    "@joystream/types": "^0.11.0",
+    "@joystream/types": "^0.12.0",
     "@polkadot/api": "^0.96.1",
     "async-lock": "^1.2.0",
     "lodash": "^4.17.11",

+ 12 - 9
storage-node/packages/runtime-api/workers.js

@@ -206,9 +206,10 @@ class WorkersApi {
    */
   async devSubmitAddOpeningTx(tx, senderAccount) {
     return this.base.signAndSendThenGetEventResult(senderAccount, tx, {
-      eventModule: 'storageWorkingGroup',
-      eventName: 'OpeningAdded',
-      eventProperty: 'OpeningId',
+      module: 'storageWorkingGroup',
+      event: 'OpeningAdded',
+      type: 'OpeningId',
+      index: 0,
     })
   }
 
@@ -226,9 +227,10 @@ class WorkersApi {
     )
 
     return this.base.signAndSendThenGetEventResult(memberAccount, applyTx, {
-      eventModule: 'storageWorkingGroup',
-      eventName: 'AppliedOnOpening',
-      eventProperty: 'ApplicationId',
+      module: 'storageWorkingGroup',
+      event: 'AppliedOnOpening',
+      type: 'ApplicationId',
+      index: 1,
     })
   }
 
@@ -287,9 +289,10 @@ class WorkersApi {
    */
   async devSubmitFillOpeningTx(senderAccount, tx) {
     return this.base.signAndSendThenGetEventResult(senderAccount, tx, {
-      eventModule: 'storageWorkingGroup',
-      eventName: 'OpeningFilled',
-      eventProperty: 'ApplicationIdToWorkerIdMap',
+      module: 'storageWorkingGroup',
+      event: 'OpeningFilled',
+      type: 'ApplicationIdToWorkerIdMap',
+      index: 1,
     })
   }
 }

+ 1 - 1
storage-node/packages/storage/package.json

@@ -30,7 +30,7 @@
     "linux"
   ],
   "engines": {
-    "node": ">=10.15.3"
+    "node": ">=12.18.0"
   },
   "scripts": {
     "test": "mocha --exit 'test/**/*.js'",

+ 1 - 1
storage-node/packages/util/package.json

@@ -30,7 +30,7 @@
     "linux"
   ],
   "engines": {
-    "node": ">=10.15.3"
+    "node": ">=12.18.0"
   },
   "scripts": {
     "test": "mocha 'test/**/*.js'",

Энэ ялгаанд хэт олон файл өөрчлөгдсөн тул зарим файлыг харуулаагүй болно