Browse Source

Merge remote-tracking branch 'shamil/storage-distribution' into distributor-node

Leszek Wiesner 3 years ago
parent
commit
35739b858b
33 changed files with 4100 additions and 461 deletions
  1. 11 4
      node/src/chain_spec/mod.rs
  2. 3 0
      runtime-modules/common/src/working_group.rs
  3. 47 0
      runtime-modules/storage/src/bag_manager.rs
  4. 94 0
      runtime-modules/storage/src/distribution_bucket_picker.rs
  5. 837 48
      runtime-modules/storage/src/lib.rs
  6. 7 23
      runtime-modules/storage/src/storage_bucket_picker.rs
  7. 695 11
      runtime-modules/storage/src/tests/fixtures.rs
  8. 60 15
      runtime-modules/storage/src/tests/mocks.rs
  9. 137 140
      runtime-modules/storage/src/tests/mod.rs
  10. 3 0
      runtime/src/integration/proposals/proposal_encoder.rs
  11. 48 13
      runtime/src/lib.rs
  12. 6 0
      runtime/src/primitives.rs
  13. 61 1
      runtime/src/tests/proposals_integration/working_group_proposals.rs
  14. 2 2
      storage-node-v2/src/services/runtime/extrinsics.ts
  15. 1 2
      types/augment-codec/all.ts
  16. 29 5
      types/augment-codec/augment-api-consts.ts
  17. 466 0
      types/augment-codec/augment-api-errors.ts
  18. 222 2
      types/augment-codec/augment-api-events.ts
  19. 76 1
      types/augment-codec/augment-api-query.ts
  20. 136 3
      types/augment-codec/augment-api-tx.ts
  21. 0 0
      types/augment-codec/augment-types.ts
  22. 52 35
      types/augment/all/defs.json
  23. 62 41
      types/augment/all/types.ts
  24. 29 5
      types/augment/augment-api-consts.ts
  25. 466 0
      types/augment/augment-api-errors.ts
  26. 222 2
      types/augment/augment-api-events.ts
  27. 76 1
      types/augment/augment-api-query.ts
  28. 136 3
      types/augment/augment-api-tx.ts
  29. 0 0
      types/augment/augment-types.ts
  30. 0 3
      types/src/index.ts
  31. 0 83
      types/src/media.ts
  32. 0 2
      types/src/scripts/generateAugmentCodec.ts
  33. 116 16
      types/src/storage.ts

+ 11 - 4
node/src/chain_spec/mod.rs

@@ -33,10 +33,10 @@ use sp_runtime::Perbill;
 use node_runtime::{
     membership, wasm_binary_unwrap, AuthorityDiscoveryConfig, BabeConfig, Balance, BalancesConfig,
     ContentDirectoryConfig, ContentDirectoryWorkingGroupConfig, ContentWorkingGroupConfig,
-    CouncilConfig, CouncilElectionConfig, ElectionParameters, ForumConfig, GrandpaConfig,
-    ImOnlineConfig, MembersConfig, Moment, ProposalsCodexConfig, SessionConfig, SessionKeys,
-    Signature, StakerStatus, StakingConfig, StorageWorkingGroupConfig, SudoConfig, SystemConfig,
-    VersionedStoreConfig, VersionedStorePermissionsConfig, DAYS,
+    CouncilConfig, CouncilElectionConfig, DistributionWorkingGroupConfig, ElectionParameters,
+    ForumConfig, GrandpaConfig, ImOnlineConfig, MembersConfig, Moment, ProposalsCodexConfig,
+    SessionConfig, SessionKeys, Signature, StakerStatus, StakingConfig, StorageWorkingGroupConfig,
+    SudoConfig, SystemConfig, VersionedStoreConfig, VersionedStorePermissionsConfig, DAYS,
 };
 
 // Exported to be used by chain-spec-builder
@@ -319,6 +319,13 @@ pub fn testnet_genesis(
             worker_application_human_readable_text_constraint: default_text_constraint,
             worker_exit_rationale_text_constraint: default_text_constraint,
         }),
+        working_group_Instance4: Some(DistributionWorkingGroupConfig {
+            phantom: Default::default(),
+            working_group_mint_capacity: 0,
+            opening_human_readable_text_constraint: default_text_constraint,
+            worker_application_human_readable_text_constraint: default_text_constraint,
+            worker_exit_rationale_text_constraint: default_text_constraint,
+        }),
         content_directory: Some({
             ContentDirectoryConfig {
                 class_by_id: vec![],

+ 3 - 0
runtime-modules/common/src/working_group.rs

@@ -20,4 +20,7 @@ pub enum WorkingGroup {
 
     /// Storage working group: working_group::Instance3.
     Content = 3isize,
+
+    /// Distribution working group: working_group::Instance4.
+    Distribution = 4isize,
 }

+ 47 - 0
runtime-modules/storage/src/bag_manager.rs

@@ -204,6 +204,17 @@ impl<T: Trait> BagManager<T> {
         )
     }
 
+    // Gets distribution bucket ID set from the bag container.
+    pub(crate) fn get_distribution_bucket_ids(
+        bag_id: &BagId<T>,
+    ) -> BTreeSet<T::DistributionBucketId> {
+        Self::query(
+            bag_id,
+            |bag| bag.distributed_by.clone(),
+            |bag| bag.distributed_by.clone(),
+        )
+    }
+
     // Gets storage bucket ID set from the bag container.
     pub(crate) fn get_storage_bucket_ids(bag_id: &BagId<T>) -> BTreeSet<T::StorageBucketId> {
         Self::query(
@@ -213,6 +224,42 @@ impl<T: Trait> BagManager<T> {
         )
     }
 
+    // Add distribution buckets to a bag.
+    pub(crate) fn add_distribution_buckets(
+        bag_id: &BagId<T>,
+        buckets: BTreeSet<T::DistributionBucketId>,
+    ) {
+        Self::mutate(
+            &bag_id,
+            |bag| {
+                bag.distributed_by.append(&mut buckets.clone());
+            },
+            |bag| {
+                bag.distributed_by.append(&mut buckets.clone());
+            },
+        );
+    }
+
+    // Remove distribution buckets from a bag.
+    pub(crate) fn remove_distribution_buckets(
+        bag_id: &BagId<T>,
+        buckets: BTreeSet<T::DistributionBucketId>,
+    ) {
+        Self::mutate(
+            &bag_id,
+            |bag| {
+                for bucket_id in buckets.iter() {
+                    bag.distributed_by.remove(bucket_id);
+                }
+            },
+            |bag| {
+                for bucket_id in buckets.iter() {
+                    bag.distributed_by.remove(bucket_id);
+                }
+            },
+        );
+    }
+
     // Abstract bag query function. Accepts two closures that should have similar result type.
     fn query<
         Res,

+ 94 - 0
runtime-modules/storage/src/distribution_bucket_picker.rs

@@ -0,0 +1,94 @@
+#![warn(missing_docs)]
+
+use frame_support::traits::Randomness;
+use sp_arithmetic::traits::Zero;
+use sp_runtime::SaturatedConversion;
+use sp_std::cell::RefCell;
+use sp_std::collections::btree_set::BTreeSet;
+use sp_std::marker::PhantomData;
+use sp_std::rc::Rc;
+use sp_std::vec::Vec;
+
+use crate::{DynamicBagType, Module, Trait};
+
+// Generates distribution bucket IDs to assign to a new dynamic bag.
+pub(crate) struct DistributionBucketPicker<T> {
+    trait_marker: PhantomData<T>,
+}
+
+impl<T: Trait> DistributionBucketPicker<T> {
+    // Get random distribution buckets from distribution bucket families using the dynamic bag
+    // creation policy.
+    pub(crate) fn pick_distribution_buckets(
+        bag_type: DynamicBagType,
+    ) -> BTreeSet<T::DistributionBucketId> {
+        let creation_policy = Module::<T>::get_dynamic_bag_creation_policy(bag_type);
+
+        if creation_policy.no_distribution_buckets_required() {
+            return BTreeSet::new();
+        }
+
+        // Randomness for all bucket family.
+        // let random_seed = RefCell::new(Module::<T>::get_initial_random_seed());
+        let random_seed = Rc::new(RefCell::new(Module::<T>::get_initial_random_seed()));
+
+        creation_policy
+            .families
+            .iter()
+            .filter_map(|(family_id, bucket_num)| {
+                Module::<T>::ensure_distribution_bucket_family_exists(family_id)
+                    .ok()
+                    .map(|fam| (fam, bucket_num))
+            })
+            .map(|(family, bucket_num)| {
+                let filtered_ids = family
+                    .distribution_buckets
+                    .iter()
+                    .filter_map(|(id, bucket)| bucket.accepting_new_bags.then(|| *id))
+                    .collect::<Vec<_>>();
+
+                (filtered_ids, bucket_num)
+            })
+            .map(|(bucket_ids, bucket_num)| {
+                Self::get_random_distribution_buckets(bucket_ids, *bucket_num, random_seed.clone())
+            })
+            .flatten()
+            .collect::<BTreeSet<_>>()
+    }
+
+    // Get random bucket IDs from the ID collection.
+    pub fn get_random_distribution_buckets(
+        ids: Vec<T::DistributionBucketId>,
+        bucket_number: u32,
+        seed: Rc<RefCell<T::Hash>>, //     seed: RefCell<T::Hash>
+    ) -> BTreeSet<T::DistributionBucketId> {
+        let mut working_ids = ids;
+        let mut result_ids = BTreeSet::default();
+
+        for _ in 0..bucket_number {
+            if working_ids.is_empty() {
+                break;
+            }
+
+            let current_seed = Self::advance_random_seed(seed.clone());
+
+            let upper_bound = working_ids.len() as u64 - 1;
+            let index =
+                Module::<T>::random_index(current_seed.as_ref(), upper_bound).saturated_into();
+            result_ids.insert(working_ids.remove(index));
+        }
+
+        result_ids
+    }
+
+    // Changes the internal seed value of the container and returns new random seed.
+    fn advance_random_seed(seed: Rc<RefCell<T::Hash>>) -> T::Hash {
+        // Cannot create randomness in the initial block (Substrate error).
+        if <frame_system::Module<T>>::block_number() == Zero::zero() {
+            return Module::<T>::get_initial_random_seed();
+        }
+
+        let current_seed = *seed.borrow();
+        seed.replace(T::Randomness::random(current_seed.as_ref()))
+    }
+}

File diff suppressed because it is too large
+ 837 - 48
runtime-modules/storage/src/lib.rs


+ 7 - 23
runtime-modules/storage/src/storage_bucket_picker.rs

@@ -30,7 +30,7 @@ impl<T: Trait> StorageBucketPicker<T> {
 
         let required_bucket_num = creation_policy.number_of_storage_buckets as usize;
 
-        // Storage IDs accumulator.
+        // Storage bucket IDs accumulator.
         let bucket_ids_cell = RefCell::new(BTreeSet::new());
 
         RandomStorageBucketIdIterator::<T>::new()
@@ -109,34 +109,18 @@ impl<T: Trait> RandomStorageBucketIdIterator<T> {
     fn random_storage_bucket_id(&self) -> T::StorageBucketId {
         let total_buckets_number = Module::<T>::next_storage_bucket_id();
 
-        let random_bucket_id: T::StorageBucketId = self
-            .random_index(total_buckets_number.saturated_into())
-            .saturated_into();
+        let random_bucket_id: T::StorageBucketId = Module::<T>::random_index(
+            self.current_seed.as_ref(),
+            total_buckets_number.saturated_into(),
+        )
+        .saturated_into();
 
         random_bucket_id
     }
 
-    // Generate random number from zero to upper_bound (excluding).
-    fn random_index(&self, upper_bound: u64) -> u64 {
-        if upper_bound == 0 {
-            return upper_bound;
-        }
-
-        let mut rand: u64 = 0;
-        for offset in 0..8 {
-            rand += (self.current_seed.as_ref()[offset] as u64) << offset;
-        }
-        rand % upper_bound
-    }
-
     // Creates new iterator.
     pub(crate) fn new() -> Self {
-        // Cannot create randomness in the initial block (Substrate error).
-        let seed = if <frame_system::Module<T>>::block_number() == Zero::zero() {
-            Default::default()
-        } else {
-            T::Randomness::random_seed()
-        };
+        let seed = Module::<T>::get_initial_random_seed();
 
         Self {
             current_iteration: 0,

+ 695 - 11
runtime-modules/storage/src/tests/fixtures.rs

@@ -2,16 +2,21 @@ use frame_support::dispatch::DispatchResult;
 use frame_support::storage::StorageMap;
 use frame_support::traits::{Currency, OnFinalize, OnInitialize};
 use frame_system::{EventRecord, Phase, RawOrigin};
+use sp_std::collections::btree_map::BTreeMap;
 use sp_std::collections::btree_set::BTreeSet;
 
 use super::mocks::{
     Balances, CollectiveFlip, Storage, System, Test, TestEvent, DEFAULT_MEMBER_ACCOUNT_ID,
-    DEFAULT_STORAGE_PROVIDER_ACCOUNT_ID, WG_LEADER_ACCOUNT_ID,
+    DEFAULT_STORAGE_PROVIDER_ACCOUNT_ID, STORAGE_WG_LEADER_ACCOUNT_ID,
 };
 
+use crate::tests::mocks::{
+    DEFAULT_DISTRIBUTION_PROVIDER_ACCOUNT_ID, DISTRIBUTION_WG_LEADER_ACCOUNT_ID,
+};
 use crate::{
-    BagId, ContentId, DataObjectCreationParameters, DataObjectStorage, DynamicBagId,
-    DynamicBagType, RawEvent, StaticBagId, StorageBucketOperatorStatus, UploadParameters,
+    BagId, ContentId, DataObjectCreationParameters, DataObjectStorage, DistributionBucketFamily,
+    DynamicBagId, DynamicBagType, RawEvent, StaticBagId, StorageBucketOperatorStatus,
+    UploadParameters,
 };
 
 // Recommendation from Parity on testing on_finalize
@@ -44,6 +49,8 @@ impl EventFixture {
             DynamicBagId<Test>,
             u64,
             u64,
+            u64,
+            u64,
         >,
     ) {
         let converted_event = TestEvent::storage(expected_raw_event);
@@ -61,6 +68,8 @@ impl EventFixture {
             DynamicBagId<Test>,
             u64,
             u64,
+            u64,
+            u64,
         >,
     ) {
         let converted_event = TestEvent::storage(expected_raw_event);
@@ -454,7 +463,7 @@ pub struct CancelStorageBucketInvitationFixture {
 impl CancelStorageBucketInvitationFixture {
     pub fn default() -> Self {
         Self {
-            origin: RawOrigin::Signed(WG_LEADER_ACCOUNT_ID),
+            origin: RawOrigin::Signed(STORAGE_WG_LEADER_ACCOUNT_ID),
             storage_bucket_id: Default::default(),
         }
     }
@@ -556,7 +565,7 @@ pub struct UpdateUploadingBlockedStatusFixture {
 impl UpdateUploadingBlockedStatusFixture {
     pub fn default() -> Self {
         Self {
-            origin: RawOrigin::Signed(WG_LEADER_ACCOUNT_ID),
+            origin: RawOrigin::Signed(STORAGE_WG_LEADER_ACCOUNT_ID),
             new_status: false,
         }
     }
@@ -736,7 +745,7 @@ pub struct UpdateBlacklistFixture {
 impl UpdateBlacklistFixture {
     pub fn default() -> Self {
         Self {
-            origin: RawOrigin::Signed(WG_LEADER_ACCOUNT_ID),
+            origin: RawOrigin::Signed(STORAGE_WG_LEADER_ACCOUNT_ID),
             remove_hashes: BTreeSet::new(),
             add_hashes: BTreeSet::new(),
         }
@@ -846,7 +855,7 @@ pub struct RemoveStorageBucketOperatorFixture {
 impl RemoveStorageBucketOperatorFixture {
     pub fn default() -> Self {
         Self {
-            origin: RawOrigin::Signed(WG_LEADER_ACCOUNT_ID),
+            origin: RawOrigin::Signed(STORAGE_WG_LEADER_ACCOUNT_ID),
             storage_bucket_id: Default::default(),
         }
     }
@@ -892,7 +901,7 @@ pub struct UpdateDataObjectPerMegabyteFeeFixture {
 impl UpdateDataObjectPerMegabyteFeeFixture {
     pub fn default() -> Self {
         Self {
-            origin: RawOrigin::Signed(WG_LEADER_ACCOUNT_ID),
+            origin: RawOrigin::Signed(STORAGE_WG_LEADER_ACCOUNT_ID),
             new_fee: 0,
         }
     }
@@ -928,7 +937,7 @@ pub struct UpdateStorageBucketsPerBagLimitFixture {
 impl UpdateStorageBucketsPerBagLimitFixture {
     pub fn default() -> Self {
         Self {
-            origin: RawOrigin::Signed(WG_LEADER_ACCOUNT_ID),
+            origin: RawOrigin::Signed(STORAGE_WG_LEADER_ACCOUNT_ID),
             new_limit: 0,
         }
     }
@@ -1038,7 +1047,7 @@ pub struct UpdateStorageBucketsVoucherMaxLimitsFixture {
 impl UpdateStorageBucketsVoucherMaxLimitsFixture {
     pub fn default() -> Self {
         Self {
-            origin: RawOrigin::Signed(WG_LEADER_ACCOUNT_ID),
+            origin: RawOrigin::Signed(STORAGE_WG_LEADER_ACCOUNT_ID),
             new_objects_size_limit: 0,
             new_objects_number_limit: 0,
         }
@@ -1128,7 +1137,7 @@ pub struct UpdateNumberOfStorageBucketsInDynamicBagCreationPolicyFixture {
 impl UpdateNumberOfStorageBucketsInDynamicBagCreationPolicyFixture {
     pub fn default() -> Self {
         Self {
-            origin: RawOrigin::Signed(WG_LEADER_ACCOUNT_ID),
+            origin: RawOrigin::Signed(STORAGE_WG_LEADER_ACCOUNT_ID),
             new_storage_buckets_number: 0,
             dynamic_bag_type: Default::default(),
         }
@@ -1175,3 +1184,678 @@ impl UpdateNumberOfStorageBucketsInDynamicBagCreationPolicyFixture {
         }
     }
 }
+
+pub struct CreateDistributionBucketFamilyFixture {
+    origin: RawOrigin<u64>,
+}
+
+impl CreateDistributionBucketFamilyFixture {
+    pub fn default() -> Self {
+        Self {
+            origin: RawOrigin::Signed(DEFAULT_ACCOUNT_ID),
+        }
+    }
+
+    pub fn with_origin(self, origin: RawOrigin<u64>) -> Self {
+        Self { origin, ..self }
+    }
+
+    pub fn call_and_assert(&self, expected_result: DispatchResult) -> Option<u64> {
+        let next_family_id = Storage::next_distribution_bucket_family_id();
+        let family_number = Storage::distribution_bucket_family_number();
+        let actual_result = Storage::create_distribution_bucket_family(self.origin.clone().into());
+
+        assert_eq!(actual_result, expected_result);
+
+        if actual_result.is_ok() {
+            assert_eq!(
+                next_family_id + 1,
+                Storage::next_distribution_bucket_family_id()
+            );
+            assert_eq!(
+                family_number + 1,
+                Storage::distribution_bucket_family_number()
+            );
+            assert!(<crate::DistributionBucketFamilyById<Test>>::contains_key(
+                next_family_id
+            ));
+
+            Some(next_family_id)
+        } else {
+            assert_eq!(
+                next_family_id,
+                Storage::next_distribution_bucket_family_id()
+            );
+            assert_eq!(family_number, Storage::distribution_bucket_family_number());
+            assert!(!<crate::DistributionBucketFamilyById<Test>>::contains_key(
+                next_family_id
+            ));
+
+            None
+        }
+    }
+}
+
+pub struct DeleteDistributionBucketFamilyFixture {
+    origin: RawOrigin<u64>,
+    family_id: u64,
+}
+
+impl DeleteDistributionBucketFamilyFixture {
+    pub fn default() -> Self {
+        Self {
+            origin: RawOrigin::Signed(DEFAULT_ACCOUNT_ID),
+            family_id: Default::default(),
+        }
+    }
+
+    pub fn with_family_id(self, family_id: u64) -> Self {
+        Self { family_id, ..self }
+    }
+
+    pub fn with_origin(self, origin: RawOrigin<u64>) -> Self {
+        Self { origin, ..self }
+    }
+
+    pub fn call_and_assert(&self, expected_result: DispatchResult) {
+        let family_number = Storage::distribution_bucket_family_number();
+        let actual_result =
+            Storage::delete_distribution_bucket_family(self.origin.clone().into(), self.family_id);
+
+        assert_eq!(actual_result, expected_result);
+
+        if actual_result.is_ok() {
+            assert_eq!(
+                family_number - 1,
+                Storage::distribution_bucket_family_number()
+            );
+            assert!(!<crate::DistributionBucketFamilyById<Test>>::contains_key(
+                self.family_id
+            ));
+        } else {
+            assert_eq!(family_number, Storage::distribution_bucket_family_number());
+        }
+    }
+}
+
+pub struct CreateDistributionBucketFixture {
+    origin: RawOrigin<u64>,
+    family_id: u64,
+    accept_new_bags: bool,
+}
+
+impl CreateDistributionBucketFixture {
+    pub fn default() -> Self {
+        Self {
+            origin: RawOrigin::Signed(DEFAULT_ACCOUNT_ID),
+            family_id: Default::default(),
+            accept_new_bags: false,
+        }
+    }
+
+    pub fn with_family_id(self, family_id: u64) -> Self {
+        Self { family_id, ..self }
+    }
+
+    pub fn with_origin(self, origin: RawOrigin<u64>) -> Self {
+        Self { origin, ..self }
+    }
+
+    pub fn with_accept_new_bags(self, accept_new_bags: bool) -> Self {
+        Self {
+            accept_new_bags,
+            ..self
+        }
+    }
+
+    pub fn call_and_assert(&self, expected_result: DispatchResult) -> Option<u64> {
+        let next_bucket_id = Storage::next_distribution_bucket_id();
+        let actual_result = Storage::create_distribution_bucket(
+            self.origin.clone().into(),
+            self.family_id,
+            self.accept_new_bags,
+        );
+
+        assert_eq!(actual_result, expected_result);
+
+        if actual_result.is_ok() {
+            assert_eq!(next_bucket_id + 1, Storage::next_distribution_bucket_id());
+
+            let family: DistributionBucketFamily<Test> =
+                Storage::distribution_bucket_family_by_id(self.family_id);
+
+            assert!(family.distribution_buckets.contains_key(&next_bucket_id));
+            assert_eq!(
+                family
+                    .distribution_buckets
+                    .get(&next_bucket_id)
+                    .unwrap()
+                    .accepting_new_bags,
+                self.accept_new_bags
+            );
+
+            Some(next_bucket_id)
+        } else {
+            assert_eq!(next_bucket_id, Storage::next_distribution_bucket_id());
+
+            None
+        }
+    }
+}
+
+pub struct UpdateDistributionBucketStatusFixture {
+    origin: RawOrigin<u64>,
+    family_id: u64,
+    distribution_bucket_id: u64,
+    new_status: bool,
+}
+
+impl UpdateDistributionBucketStatusFixture {
+    pub fn default() -> Self {
+        Self {
+            origin: RawOrigin::Signed(DEFAULT_MEMBER_ACCOUNT_ID),
+            family_id: Default::default(),
+            distribution_bucket_id: Default::default(),
+            new_status: false,
+        }
+    }
+    pub fn with_bucket_id(self, bucket_id: u64) -> Self {
+        Self {
+            distribution_bucket_id: bucket_id,
+            ..self
+        }
+    }
+
+    pub fn with_family_id(self, family_id: u64) -> Self {
+        Self { family_id, ..self }
+    }
+
+    pub fn with_origin(self, origin: RawOrigin<u64>) -> Self {
+        Self { origin, ..self }
+    }
+
+    pub fn with_new_status(self, new_status: bool) -> Self {
+        Self { new_status, ..self }
+    }
+
+    pub fn call_and_assert(&self, expected_result: DispatchResult) {
+        let actual_result = Storage::update_distribution_bucket_status(
+            self.origin.clone().into(),
+            self.family_id,
+            self.distribution_bucket_id,
+            self.new_status,
+        );
+
+        assert_eq!(actual_result, expected_result);
+    }
+}
+
+pub struct DeleteDistributionBucketFixture {
+    origin: RawOrigin<u64>,
+    family_id: u64,
+    distribution_bucket_id: u64,
+}
+
+impl DeleteDistributionBucketFixture {
+    pub fn default() -> Self {
+        Self {
+            origin: RawOrigin::Signed(DEFAULT_MEMBER_ACCOUNT_ID),
+            family_id: Default::default(),
+            distribution_bucket_id: Default::default(),
+        }
+    }
+
+    pub fn with_bucket_id(self, bucket_id: u64) -> Self {
+        Self {
+            distribution_bucket_id: bucket_id,
+            ..self
+        }
+    }
+
+    pub fn with_family_id(self, family_id: u64) -> Self {
+        Self { family_id, ..self }
+    }
+
+    pub fn with_origin(self, origin: RawOrigin<u64>) -> Self {
+        Self { origin, ..self }
+    }
+
+    pub fn call_and_assert(&self, expected_result: DispatchResult) {
+        let actual_result = Storage::delete_distribution_bucket(
+            self.origin.clone().into(),
+            self.family_id,
+            self.distribution_bucket_id,
+        );
+
+        assert_eq!(actual_result, expected_result);
+    }
+}
+
+pub struct UpdateDistributionBucketForBagsFixture {
+    origin: RawOrigin<u64>,
+    bag_id: BagId<Test>,
+    family_id: u64,
+    add_bucket_ids: BTreeSet<u64>,
+    remove_bucket_ids: BTreeSet<u64>,
+}
+
+impl UpdateDistributionBucketForBagsFixture {
+    pub fn default() -> Self {
+        Self {
+            origin: RawOrigin::Signed(DEFAULT_ACCOUNT_ID),
+            bag_id: Default::default(),
+            family_id: Default::default(),
+            add_bucket_ids: Default::default(),
+            remove_bucket_ids: Default::default(),
+        }
+    }
+
+    pub fn with_origin(self, origin: RawOrigin<u64>) -> Self {
+        Self { origin, ..self }
+    }
+
+    pub fn with_add_bucket_ids(self, add_bucket_ids: BTreeSet<u64>) -> Self {
+        Self {
+            add_bucket_ids,
+            ..self
+        }
+    }
+
+    pub fn with_remove_bucket_ids(self, remove_bucket_ids: BTreeSet<u64>) -> Self {
+        Self {
+            remove_bucket_ids,
+            ..self
+        }
+    }
+
+    pub fn with_bag_id(self, bag_id: BagId<Test>) -> Self {
+        Self { bag_id, ..self }
+    }
+
+    pub fn with_family_id(self, family_id: u64) -> Self {
+        Self { family_id, ..self }
+    }
+
+    pub fn call_and_assert(&self, expected_result: DispatchResult) {
+        let actual_result = Storage::update_distribution_buckets_for_bag(
+            self.origin.clone().into(),
+            self.bag_id.clone(),
+            self.family_id,
+            self.add_bucket_ids.clone(),
+            self.remove_bucket_ids.clone(),
+        );
+
+        assert_eq!(actual_result, expected_result);
+    }
+}
+
+pub struct UpdateDistributionBucketsPerBagLimitFixture {
+    origin: RawOrigin<u64>,
+    new_limit: u64,
+}
+
+impl UpdateDistributionBucketsPerBagLimitFixture {
+    pub fn default() -> Self {
+        Self {
+            origin: RawOrigin::Signed(DISTRIBUTION_WG_LEADER_ACCOUNT_ID),
+            new_limit: 0,
+        }
+    }
+
+    pub fn with_origin(self, origin: RawOrigin<u64>) -> Self {
+        Self { origin, ..self }
+    }
+
+    pub fn with_new_limit(self, new_limit: u64) -> Self {
+        Self { new_limit, ..self }
+    }
+
+    pub fn call_and_assert(&self, expected_result: DispatchResult) {
+        let old_limit = Storage::distribution_buckets_per_bag_limit();
+
+        let actual_result = Storage::update_distribution_buckets_per_bag_limit(
+            self.origin.clone().into(),
+            self.new_limit,
+        );
+
+        assert_eq!(actual_result, expected_result);
+
+        if actual_result.is_ok() {
+            assert_eq!(
+                Storage::distribution_buckets_per_bag_limit(),
+                self.new_limit
+            );
+        } else {
+            assert_eq!(old_limit, Storage::distribution_buckets_per_bag_limit());
+        }
+    }
+}
+
+pub struct UpdateDistributionBucketModeFixture {
+    origin: RawOrigin<u64>,
+    family_id: u64,
+    distribution_bucket_id: u64,
+    distributing: bool,
+}
+
+impl UpdateDistributionBucketModeFixture {
+    pub fn default() -> Self {
+        Self {
+            origin: RawOrigin::Signed(DEFAULT_MEMBER_ACCOUNT_ID),
+            family_id: Default::default(),
+            distribution_bucket_id: Default::default(),
+            distributing: true,
+        }
+    }
+    pub fn with_bucket_id(self, bucket_id: u64) -> Self {
+        Self {
+            distribution_bucket_id: bucket_id,
+            ..self
+        }
+    }
+
+    pub fn with_family_id(self, family_id: u64) -> Self {
+        Self { family_id, ..self }
+    }
+
+    pub fn with_origin(self, origin: RawOrigin<u64>) -> Self {
+        Self { origin, ..self }
+    }
+
+    pub fn with_distributing(self, distributing: bool) -> Self {
+        Self {
+            distributing,
+            ..self
+        }
+    }
+
+    pub fn call_and_assert(&self, expected_result: DispatchResult) {
+        let actual_result = Storage::update_distribution_bucket_mode(
+            self.origin.clone().into(),
+            self.family_id,
+            self.distribution_bucket_id,
+            self.distributing,
+        );
+
+        assert_eq!(actual_result, expected_result);
+    }
+}
+
+pub struct UpdateFamiliesInDynamicBagCreationPolicyFixture {
+    origin: RawOrigin<u64>,
+    dynamic_bag_type: DynamicBagType,
+    families: BTreeMap<u64, u32>,
+}
+
+impl UpdateFamiliesInDynamicBagCreationPolicyFixture {
+    pub fn default() -> Self {
+        Self {
+            origin: RawOrigin::Signed(STORAGE_WG_LEADER_ACCOUNT_ID),
+            dynamic_bag_type: Default::default(),
+            families: Default::default(),
+        }
+    }
+
+    pub fn with_origin(self, origin: RawOrigin<u64>) -> Self {
+        Self { origin, ..self }
+    }
+
+    pub fn with_families(self, families: BTreeMap<u64, u32>) -> Self {
+        Self { families, ..self }
+    }
+
+    pub fn with_dynamic_bag_type(self, dynamic_bag_type: DynamicBagType) -> Self {
+        Self {
+            dynamic_bag_type,
+            ..self
+        }
+    }
+
+    pub fn call_and_assert(&self, expected_result: DispatchResult) {
+        let old_policy = Storage::get_dynamic_bag_creation_policy(self.dynamic_bag_type);
+
+        let actual_result = Storage::update_families_in_dynamic_bag_creation_policy(
+            self.origin.clone().into(),
+            self.dynamic_bag_type,
+            self.families.clone(),
+        );
+
+        assert_eq!(actual_result, expected_result);
+
+        let new_policy = Storage::get_dynamic_bag_creation_policy(self.dynamic_bag_type);
+        if actual_result.is_ok() {
+            assert_eq!(new_policy.families, self.families);
+        } else {
+            assert_eq!(old_policy, new_policy);
+        }
+    }
+}
+
+pub struct InviteDistributionBucketOperatorFixture {
+    origin: RawOrigin<u64>,
+    operator_worker_id: u64,
+    family_id: u64,
+    bucket_id: u64,
+}
+
+impl InviteDistributionBucketOperatorFixture {
+    pub fn default() -> Self {
+        Self {
+            origin: RawOrigin::Signed(DEFAULT_ACCOUNT_ID),
+            operator_worker_id: DEFAULT_WORKER_ID,
+            bucket_id: Default::default(),
+            family_id: Default::default(),
+        }
+    }
+
+    pub fn with_origin(self, origin: RawOrigin<u64>) -> Self {
+        Self { origin, ..self }
+    }
+
+    pub fn with_operator_worker_id(self, operator_worker_id: u64) -> Self {
+        Self {
+            operator_worker_id,
+            ..self
+        }
+    }
+
+    pub fn with_bucket_id(self, bucket_id: u64) -> Self {
+        Self { bucket_id, ..self }
+    }
+
+    pub fn with_family_id(self, family_id: u64) -> Self {
+        Self { family_id, ..self }
+    }
+
+    pub fn call_and_assert(&self, expected_result: DispatchResult) {
+        let actual_result = Storage::invite_distribution_bucket_operator(
+            self.origin.clone().into(),
+            self.family_id,
+            self.bucket_id,
+            self.operator_worker_id,
+        );
+
+        assert_eq!(actual_result, expected_result);
+
+        if actual_result.is_ok() {
+            let new_family = Storage::distribution_bucket_family_by_id(self.family_id);
+            let new_bucket = new_family
+                .distribution_buckets
+                .get(&self.bucket_id)
+                .unwrap();
+
+            assert!(new_bucket
+                .pending_invitations
+                .contains(&self.operator_worker_id),);
+        }
+    }
+}
+
+pub struct CancelDistributionBucketInvitationFixture {
+    origin: RawOrigin<u64>,
+    bucket_id: u64,
+    family_id: u64,
+    operator_worker_id: u64,
+}
+
+impl CancelDistributionBucketInvitationFixture {
+    pub fn default() -> Self {
+        Self {
+            origin: RawOrigin::Signed(DEFAULT_DISTRIBUTION_PROVIDER_ACCOUNT_ID),
+            bucket_id: Default::default(),
+            family_id: Default::default(),
+            operator_worker_id: Default::default(),
+        }
+    }
+
+    pub fn with_origin(self, origin: RawOrigin<u64>) -> Self {
+        Self { origin, ..self }
+    }
+
+    pub fn with_bucket_id(self, bucket_id: u64) -> Self {
+        Self { bucket_id, ..self }
+    }
+
+    pub fn with_family_id(self, family_id: u64) -> Self {
+        Self { family_id, ..self }
+    }
+
+    pub fn with_operator_worker_id(self, operator_worker_id: u64) -> Self {
+        Self {
+            operator_worker_id,
+            ..self
+        }
+    }
+
+    pub fn call_and_assert(&self, expected_result: DispatchResult) {
+        let actual_result = Storage::cancel_distribution_bucket_operator_invite(
+            self.origin.clone().into(),
+            self.family_id,
+            self.bucket_id,
+            self.operator_worker_id,
+        );
+
+        assert_eq!(actual_result, expected_result);
+
+        if actual_result.is_ok() {
+            let new_family = Storage::distribution_bucket_family_by_id(self.family_id);
+            let new_bucket = new_family
+                .distribution_buckets
+                .get(&self.bucket_id)
+                .unwrap();
+
+            assert!(!new_bucket
+                .pending_invitations
+                .contains(&self.operator_worker_id));
+        }
+    }
+}
+
+pub struct AcceptDistributionBucketInvitationFixture {
+    origin: RawOrigin<u64>,
+    bucket_id: u64,
+    family_id: u64,
+    worker_id: u64,
+}
+
+impl AcceptDistributionBucketInvitationFixture {
+    pub fn default() -> Self {
+        Self {
+            origin: RawOrigin::Signed(DEFAULT_DISTRIBUTION_PROVIDER_ACCOUNT_ID),
+            bucket_id: Default::default(),
+            family_id: Default::default(),
+            worker_id: Default::default(),
+        }
+    }
+
+    pub fn with_origin(self, origin: RawOrigin<u64>) -> Self {
+        Self { origin, ..self }
+    }
+
+    pub fn with_bucket_id(self, bucket_id: u64) -> Self {
+        Self { bucket_id, ..self }
+    }
+
+    pub fn with_family_id(self, family_id: u64) -> Self {
+        Self { family_id, ..self }
+    }
+
+    pub fn with_worker_id(self, worker_id: u64) -> Self {
+        Self { worker_id, ..self }
+    }
+
+    pub fn call_and_assert(&self, expected_result: DispatchResult) {
+        let actual_result = Storage::accept_distribution_bucket_invitation(
+            self.origin.clone().into(),
+            self.worker_id,
+            self.family_id,
+            self.bucket_id,
+        );
+
+        assert_eq!(actual_result, expected_result);
+
+        if actual_result.is_ok() {
+            let new_family = Storage::distribution_bucket_family_by_id(self.family_id);
+            let new_bucket = new_family
+                .distribution_buckets
+                .get(&self.bucket_id)
+                .unwrap();
+
+            assert!(!new_bucket.pending_invitations.contains(&self.worker_id));
+
+            assert!(new_bucket.operators.contains(&self.worker_id));
+        }
+    }
+}
+
+pub struct SetDistributionBucketMetadataFixture {
+    origin: RawOrigin<u64>,
+    bucket_id: u64,
+    family_id: u64,
+    worker_id: u64,
+    metadata: Vec<u8>,
+}
+
+impl SetDistributionBucketMetadataFixture {
+    pub fn default() -> Self {
+        Self {
+            origin: RawOrigin::Signed(DEFAULT_DISTRIBUTION_PROVIDER_ACCOUNT_ID),
+            bucket_id: Default::default(),
+            family_id: Default::default(),
+            worker_id: Default::default(),
+            metadata: Default::default(),
+        }
+    }
+
+    pub fn with_metadata(self, metadata: Vec<u8>) -> Self {
+        Self { metadata, ..self }
+    }
+
+    pub fn with_origin(self, origin: RawOrigin<u64>) -> Self {
+        Self { origin, ..self }
+    }
+
+    pub fn with_bucket_id(self, bucket_id: u64) -> Self {
+        Self { bucket_id, ..self }
+    }
+
+    pub fn with_family_id(self, family_id: u64) -> Self {
+        Self { family_id, ..self }
+    }
+
+    pub fn with_worker_id(self, worker_id: u64) -> Self {
+        Self { worker_id, ..self }
+    }
+
+    pub fn call_and_assert(&self, expected_result: DispatchResult) {
+        let actual_result = Storage::set_distribution_operator_metadata(
+            self.origin.clone().into(),
+            self.worker_id,
+            self.family_id,
+            self.bucket_id,
+            self.metadata.clone(),
+        );
+
+        assert_eq!(actual_result, expected_result);
+    }
+}

+ 60 - 15
runtime-modules/storage/src/tests/mocks.rs

@@ -10,8 +10,6 @@ use sp_runtime::{
     ModuleId, Perbill,
 };
 
-use crate::DynamicBagCreationPolicy;
-
 // Workaround for https://github.com/rust-lang/rust/issues/26925 . Remove when sorted.
 #[derive(Clone, PartialEq, Eq, Debug)]
 pub struct Test;
@@ -54,31 +52,38 @@ impl balances::Trait for Test {
 parameter_types! {
     pub const MaxStorageBucketNumber: u64 = 1000;
     pub const MaxNumberOfDataObjectsPerBag: u64 = 4;
+    pub const MaxDistributionBucketFamilyNumber: u64 = 4;
+    pub const MaxDistributionBucketNumberPerFamily: u64 = 10;
     pub const DataObjectDeletionPrize: u64 = 10;
     pub const StorageModuleId: ModuleId = ModuleId(*b"mstorage"); // module storage
     pub const BlacklistSizeLimit: u64 = 1;
+    pub const MaxNumberOfPendingInvitationsPerDistributionBucket: u64 = 1;
     pub const StorageBucketsPerBagValueConstraint: crate::StorageBucketsPerBagValueConstraint =
         crate::StorageBucketsPerBagValueConstraint {min: 3, max_min_diff: 7};
     pub const InitialStorageBucketsNumberForDynamicBag: u64 = 3;
     pub const MaxRandomIterationNumber: u64 = 3;
-        pub const DefaultMemberDynamicBagCreationPolicy: DynamicBagCreationPolicy = DynamicBagCreationPolicy{
-        number_of_storage_buckets: 3
-    };
-    pub const DefaultChannelDynamicBagCreationPolicy: DynamicBagCreationPolicy = DynamicBagCreationPolicy{
-        number_of_storage_buckets: 4
-    };
+    pub const DefaultMemberDynamicBagNumberOfStorageBuckets: u64 = 3;
+    pub const DefaultChannelDynamicBagNumberOfStorageBuckets: u64 = 4;
+    pub const DistributionBucketsPerBagValueConstraint: crate::DistributionBucketsPerBagValueConstraint =
+        crate::StorageBucketsPerBagValueConstraint {min: 3, max_min_diff: 7};
 }
 
-pub const WG_LEADER_ACCOUNT_ID: u64 = 100001;
+pub const STORAGE_WG_LEADER_ACCOUNT_ID: u64 = 100001;
 pub const DEFAULT_STORAGE_PROVIDER_ACCOUNT_ID: u64 = 100002;
+pub const DEFAULT_DISTRIBUTION_PROVIDER_ACCOUNT_ID: u64 = 100003;
+pub const DISTRIBUTION_WG_LEADER_ACCOUNT_ID: u64 = 100004;
 pub const DEFAULT_STORAGE_PROVIDER_ID: u64 = 10;
 pub const ANOTHER_STORAGE_PROVIDER_ID: u64 = 11;
+pub const DEFAULT_DISTRIBUTION_PROVIDER_ID: u64 = 12;
+pub const ANOTHER_DISTRIBUTION_PROVIDER_ID: u64 = 13;
 
 impl crate::Trait for Test {
     type Event = TestEvent;
     type DataObjectId = u64;
     type StorageBucketId = u64;
     type DistributionBucketId = u64;
+    type DistributionBucketFamilyId = u64;
+    type DistributionBucketOperatorId = u64;
     type ChannelId = u64;
     type MaxStorageBucketNumber = MaxStorageBucketNumber;
     type MaxNumberOfDataObjectsPerBag = MaxNumberOfDataObjectsPerBag;
@@ -87,22 +92,29 @@ impl crate::Trait for Test {
     type ModuleId = StorageModuleId;
     type MemberOriginValidator = ();
     type StorageBucketsPerBagValueConstraint = StorageBucketsPerBagValueConstraint;
-    type DefaultMemberDynamicBagCreationPolicy = DefaultMemberDynamicBagCreationPolicy;
-    type DefaultChannelDynamicBagCreationPolicy = DefaultChannelDynamicBagCreationPolicy;
+    type DefaultMemberDynamicBagNumberOfStorageBuckets =
+        DefaultMemberDynamicBagNumberOfStorageBuckets;
+    type DefaultChannelDynamicBagNumberOfStorageBuckets =
+        DefaultChannelDynamicBagNumberOfStorageBuckets;
     type Randomness = CollectiveFlip;
     type MaxRandomIterationNumber = MaxRandomIterationNumber;
+    type MaxDistributionBucketFamilyNumber = MaxDistributionBucketFamilyNumber;
+    type MaxDistributionBucketNumberPerFamily = MaxDistributionBucketNumberPerFamily;
+    type DistributionBucketsPerBagValueConstraint = DistributionBucketsPerBagValueConstraint;
+    type MaxNumberOfPendingInvitationsPerDistributionBucket =
+        MaxNumberOfPendingInvitationsPerDistributionBucket;
 
-    fn ensure_working_group_leader_origin(origin: Self::Origin) -> DispatchResult {
+    fn ensure_storage_working_group_leader_origin(origin: Self::Origin) -> DispatchResult {
         let account_id = ensure_signed(origin)?;
 
-        if account_id != WG_LEADER_ACCOUNT_ID {
+        if account_id != STORAGE_WG_LEADER_ACCOUNT_ID {
             Err(DispatchError::BadOrigin)
         } else {
             Ok(())
         }
     }
 
-    fn ensure_worker_origin(origin: Self::Origin, _: u64) -> DispatchResult {
+    fn ensure_storage_worker_origin(origin: Self::Origin, _: u64) -> DispatchResult {
         let account_id = ensure_signed(origin)?;
 
         if account_id != DEFAULT_STORAGE_PROVIDER_ACCOUNT_ID {
@@ -112,7 +124,7 @@ impl crate::Trait for Test {
         }
     }
 
-    fn ensure_worker_exists(worker_id: &u64) -> DispatchResult {
+    fn ensure_storage_worker_exists(worker_id: &u64) -> DispatchResult {
         let allowed_storage_providers =
             vec![DEFAULT_STORAGE_PROVIDER_ID, ANOTHER_STORAGE_PROVIDER_ID];
 
@@ -122,6 +134,39 @@ impl crate::Trait for Test {
             Ok(())
         }
     }
+
+    fn ensure_distribution_working_group_leader_origin(origin: Self::Origin) -> DispatchResult {
+        let account_id = ensure_signed(origin)?;
+
+        if account_id != DISTRIBUTION_WG_LEADER_ACCOUNT_ID {
+            Err(DispatchError::BadOrigin)
+        } else {
+            Ok(())
+        }
+    }
+
+    fn ensure_distribution_worker_origin(origin: Self::Origin, _: u64) -> DispatchResult {
+        let account_id = ensure_signed(origin)?;
+
+        if account_id != DEFAULT_DISTRIBUTION_PROVIDER_ACCOUNT_ID {
+            Err(DispatchError::BadOrigin)
+        } else {
+            Ok(())
+        }
+    }
+
+    fn ensure_distribution_worker_exists(worker_id: &u64) -> DispatchResult {
+        let allowed_providers = vec![
+            DEFAULT_DISTRIBUTION_PROVIDER_ID,
+            ANOTHER_DISTRIBUTION_PROVIDER_ID,
+        ];
+
+        if !allowed_providers.contains(worker_id) {
+            Err(DispatchError::Other("Invalid worker"))
+        } else {
+            Ok(())
+        }
+    }
 }
 
 pub const DEFAULT_MEMBER_ID: u64 = 100;

File diff suppressed because it is too large
+ 137 - 140
runtime-modules/storage/src/tests/mod.rs


+ 3 - 0
runtime/src/integration/proposals/proposal_encoder.rs

@@ -22,6 +22,9 @@ macro_rules! wrap_working_group_call {
                 Call::ContentDirectoryWorkingGroup($working_group_instance_call)
             }
             WorkingGroup::Storage => Call::StorageWorkingGroup($working_group_instance_call),
+            WorkingGroup::Distribution => {
+                Call::DistributionWorkingGroup($working_group_instance_call)
+            }
         }
     }};
 }

+ 48 - 13
runtime/src/lib.rs

@@ -63,7 +63,6 @@ pub use runtime_api::*;
 use integration::proposals::{CouncilManager, ExtrinsicProposalEncoder, MembershipOriginValidator};
 
 use governance::{council, election};
-use storage::DynamicBagCreationPolicy;
 
 // Node dependencies
 pub use common;
@@ -565,6 +564,9 @@ pub type StorageWorkingGroupInstance = working_group::Instance2;
 // The content directory working group instance alias.
 pub type ContentDirectoryWorkingGroupInstance = working_group::Instance3;
 
+// The distribution working group instance alias.
+pub type DistributionWorkingGroupInstance = working_group::Instance4;
+
 parameter_types! {
     pub const MaxWorkerNumberLimit: u32 = 100;
 }
@@ -579,6 +581,11 @@ impl working_group::Trait<ContentDirectoryWorkingGroupInstance> for Runtime {
     type MaxWorkerNumberLimit = MaxWorkerNumberLimit;
 }
 
+impl working_group::Trait<DistributionWorkingGroupInstance> for Runtime {
+    type Event = Event;
+    type MaxWorkerNumberLimit = MaxWorkerNumberLimit;
+}
+
 parameter_types! {
     pub const ProposalCancellationFee: u64 = 10000;
     pub const ProposalRejectionFee: u64 = 5000;
@@ -645,20 +652,21 @@ parameter_types! {
 }
 
 parameter_types! {
+    pub const MaxDistributionBucketNumberPerFamily: u64 = 20; //TODO: adjust value
+    pub const MaxDistributionBucketFamilyNumber: u64 = 20; //TODO: adjust value
     pub const MaxStorageBucketNumber: u64 = 20; //TODO: adjust value
     pub const MaxNumberOfDataObjectsPerBag: u64 = 1000; //TODO: adjust value
     pub const DataObjectDeletionPrize: Balance = 10; //TODO: adjust value
     pub const BlacklistSizeLimit: u64 = 10000; //TODO: adjust value
     pub const MaxRandomIterationNumber: u64 = 30; //TODO: adjust value
+    pub const MaxNumberOfPendingInvitationsPerDistributionBucket: u64 = 30; //TODO: adjust value
     pub const StorageModuleId: ModuleId = ModuleId(*b"mstorage"); // module storage
     pub const StorageBucketsPerBagValueConstraint: storage::StorageBucketsPerBagValueConstraint =
         storage::StorageBucketsPerBagValueConstraint {min: 3, max_min_diff: 7}; //TODO: adjust value
-    pub const DefaultMemberDynamicBagCreationPolicy: DynamicBagCreationPolicy = DynamicBagCreationPolicy{
-        number_of_storage_buckets: 4
-    }; //TODO: adjust value
-    pub const DefaultChannelDynamicBagCreationPolicy: DynamicBagCreationPolicy = DynamicBagCreationPolicy{
-        number_of_storage_buckets: 4
-    }; //TODO: adjust value
+    pub const DefaultMemberDynamicBagNumberOfStorageBuckets: u64 = 4; //TODO: adjust value
+    pub const DefaultChannelDynamicBagNumberOfStorageBuckets: u64 = 4; //TODO: adjust value
+    pub const DistributionBucketsPerBagValueConstraint: storage::DistributionBucketsPerBagValueConstraint =
+        storage::DistributionBucketsPerBagValueConstraint {min: 3, max_min_diff: 7}; //TODO: adjust value
 }
 
 impl storage::Trait for Runtime {
@@ -666,6 +674,7 @@ impl storage::Trait for Runtime {
     type DataObjectId = DataObjectId;
     type StorageBucketId = StorageBucketId;
     type DistributionBucketId = DistributionBucketId;
+    type DistributionBucketFamilyId = DistributionBucketFamilyId;
     type ChannelId = ChannelId;
     type MaxStorageBucketNumber = MaxStorageBucketNumber;
     type MaxNumberOfDataObjectsPerBag = MaxNumberOfDataObjectsPerBag;
@@ -674,24 +683,49 @@ impl storage::Trait for Runtime {
     type ModuleId = StorageModuleId;
     type MemberOriginValidator = MembershipOriginValidator<Self>;
     type StorageBucketsPerBagValueConstraint = StorageBucketsPerBagValueConstraint;
-    type DefaultMemberDynamicBagCreationPolicy = DefaultMemberDynamicBagCreationPolicy;
-    type DefaultChannelDynamicBagCreationPolicy = DefaultChannelDynamicBagCreationPolicy;
+    type DefaultMemberDynamicBagNumberOfStorageBuckets =
+        DefaultMemberDynamicBagNumberOfStorageBuckets;
+    type DefaultChannelDynamicBagNumberOfStorageBuckets =
+        DefaultChannelDynamicBagNumberOfStorageBuckets;
     type Randomness = RandomnessCollectiveFlip;
     type MaxRandomIterationNumber = MaxRandomIterationNumber;
-
-    fn ensure_working_group_leader_origin(origin: Self::Origin) -> DispatchResult {
+    type MaxDistributionBucketFamilyNumber = MaxDistributionBucketFamilyNumber;
+    type MaxDistributionBucketNumberPerFamily = MaxDistributionBucketNumberPerFamily;
+    type DistributionBucketsPerBagValueConstraint = DistributionBucketsPerBagValueConstraint;
+    type DistributionBucketOperatorId = DistributionBucketOperatorId;
+    type MaxNumberOfPendingInvitationsPerDistributionBucket =
+        MaxNumberOfPendingInvitationsPerDistributionBucket;
+
+    fn ensure_storage_working_group_leader_origin(origin: Self::Origin) -> DispatchResult {
         StorageWorkingGroup::ensure_origin_is_active_leader(origin)
     }
 
-    fn ensure_worker_origin(origin: Self::Origin, worker_id: ActorId) -> DispatchResult {
+    fn ensure_storage_worker_origin(origin: Self::Origin, worker_id: ActorId) -> DispatchResult {
         StorageWorkingGroup::ensure_worker_signed(origin, &worker_id).map(|_| ())
     }
 
-    fn ensure_worker_exists(worker_id: &ActorId) -> DispatchResult {
+    fn ensure_storage_worker_exists(worker_id: &ActorId) -> DispatchResult {
         StorageWorkingGroup::ensure_worker_exists(&worker_id)
             .map(|_| ())
             .map_err(|err| err.into())
     }
+
+    fn ensure_distribution_working_group_leader_origin(origin: Self::Origin) -> DispatchResult {
+        DistributionWorkingGroup::ensure_origin_is_active_leader(origin)
+    }
+
+    fn ensure_distribution_worker_origin(
+        origin: Self::Origin,
+        worker_id: ActorId,
+    ) -> DispatchResult {
+        DistributionWorkingGroup::ensure_worker_signed(origin, &worker_id).map(|_| ())
+    }
+
+    fn ensure_distribution_worker_exists(worker_id: &ActorId) -> DispatchResult {
+        DistributionWorkingGroup::ensure_worker_exists(&worker_id)
+            .map(|_| ())
+            .map_err(|err| err.into())
+    }
 }
 
 /// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
@@ -757,6 +791,7 @@ construct_runtime!(
         // reserved for the future use: ForumWorkingGroup: working_group::<Instance1>::{Module, Call, Storage, Event<T>},
         StorageWorkingGroup: working_group::<Instance2>::{Module, Call, Storage, Config<T>, Event<T>},
         ContentDirectoryWorkingGroup: working_group::<Instance3>::{Module, Call, Storage, Config<T>, Event<T>},
+        DistributionWorkingGroup: working_group::<Instance4>::{Module, Call, Storage, Config<T>, Event<T>},
         //
         Storage: storage::{Module, Call, Storage, Event<T>},
     }

+ 6 - 0
runtime/src/primitives.rs

@@ -74,9 +74,15 @@ pub type StorageBucketId = u64;
 /// Represent a distribution bucket from the storage pallet.
 pub type DistributionBucketId = u64;
 
+/// Represent a distribution bucket family from the storage pallet.
+pub type DistributionBucketFamilyId = u64;
+
 /// Represent a media channel.
 pub type ChannelId = u64;
 
+/// Represent relationships between distribution buckets and distribution working group workers.
+pub type DistributionBucketOperatorId = u64;
+
 /// App-specific crypto used for reporting equivocation/misbehavior in BABE and
 /// GRANDPA. Any rewards for misbehavior reporting will be paid out to this
 /// account.

+ 61 - 1
runtime/src/tests/proposals_integration/working_group_proposals.rs

@@ -12,7 +12,8 @@ use working_group::{OpeningPolicyCommitment, RewardPolicy};
 
 use crate::{
     Balance, BlockNumber, ContentDirectoryWorkingGroup, ContentDirectoryWorkingGroupInstance,
-    StorageWorkingGroup, StorageWorkingGroupInstance,
+    DistributionWorkingGroup, DistributionWorkingGroupInstance, StorageWorkingGroup,
+    StorageWorkingGroupInstance,
 };
 use sp_std::collections::btree_set::BTreeSet;
 
@@ -52,6 +53,14 @@ fn add_opening(
             >>::contains_key(opening_id));
             opening_id
         }
+        WorkingGroup::Distribution => {
+            let opening_id = DistributionWorkingGroup::next_opening_id();
+            assert!(!<working_group::OpeningById<
+                Runtime,
+                DistributionWorkingGroupInstance,
+            >>::contains_key(opening_id));
+            opening_id
+        }
     };
 
     let codex_extrinsic_test_fixture = CodexProposalTestFixture::default_for_call(|| {
@@ -330,6 +339,12 @@ fn create_add_working_group_leader_opening_proposal_execution_succeeds() {
                     StorageWorkingGroupInstance,
                 >(group);
             }
+            WorkingGroup::Distribution => {
+                run_create_add_working_group_leader_opening_proposal_execution_succeeds::<
+                    Runtime,
+                    DistributionWorkingGroupInstance,
+                >(group);
+            }
         }
     }
 }
@@ -388,6 +403,12 @@ fn create_begin_review_working_group_leader_applications_proposal_execution_succ
                 StorageWorkingGroupInstance,
             >(group);
             }
+            WorkingGroup::Distribution => {
+                run_create_begin_review_working_group_leader_applications_proposal_execution_succeeds::<
+                Runtime,
+                    DistributionWorkingGroupInstance,
+            >(group);
+            }
         }
     }
 }
@@ -468,6 +489,12 @@ fn create_fill_working_group_leader_opening_proposal_execution_succeeds() {
                     StorageWorkingGroupInstance,
                 >(group);
             }
+            WorkingGroup::Distribution => {
+                run_create_fill_working_group_leader_opening_proposal_execution_succeeds::<
+                    Runtime,
+                    DistributionWorkingGroupInstance,
+                >(group);
+            }
         }
     }
 
@@ -545,6 +572,12 @@ fn create_fill_working_group_leader_opening_proposal_execution_succeeds() {
                         StorageWorkingGroupInstance,
                     >(group);
                 }
+                WorkingGroup::Distribution => {
+                    run_create_decrease_group_leader_stake_proposal_execution_succeeds::<
+                        Runtime,
+                        DistributionWorkingGroupInstance,
+                    >(group);
+                }
             }
         }
     }
@@ -662,6 +695,12 @@ fn create_fill_working_group_leader_opening_proposal_execution_succeeds() {
                         StorageWorkingGroupInstance,
                     >(group)
                 }
+                WorkingGroup::Distribution => {
+                    run_create_slash_group_leader_stake_proposal_execution_succeeds::<
+                        Runtime,
+                        DistributionWorkingGroupInstance,
+                    >(group)
+                }
             }
         }
     }
@@ -780,6 +819,12 @@ fn create_fill_working_group_leader_opening_proposal_execution_succeeds() {
                         StorageWorkingGroupInstance,
                     >(group);
                 }
+                WorkingGroup::Distribution => {
+                    run_create_set_working_group_mint_capacity_proposal_execution_succeeds::<
+                        Runtime,
+                        DistributionWorkingGroupInstance,
+                    >(group);
+                }
             }
         }
 
@@ -836,6 +881,12 @@ fn create_fill_working_group_leader_opening_proposal_execution_succeeds() {
                             StorageWorkingGroupInstance,
                         >(group);
                     }
+                    WorkingGroup::Distribution => {
+                        run_create_set_working_group_mint_capacity_proposal_execution_succeeds::<
+                            Runtime,
+                            DistributionWorkingGroupInstance,
+                        >(group);
+                    }
                 }
             }
         }
@@ -959,6 +1010,12 @@ fn create_fill_working_group_leader_opening_proposal_execution_succeeds() {
                             StorageWorkingGroupInstance,
                         >(group);
                     }
+                    WorkingGroup::Distribution => {
+                        run_create_terminate_group_leader_role_proposal_execution_succeeds::<
+                            Runtime,
+                            DistributionWorkingGroupInstance,
+                        >(group);
+                    }
                 }
             }
         }
@@ -1078,6 +1135,9 @@ fn create_fill_working_group_leader_opening_proposal_execution_succeeds() {
                     WorkingGroup::Storage => {
                         run_create_terminate_group_leader_role_proposal_with_slashing_execution_succeeds::<Runtime, StorageWorkingGroupInstance>(group);
                     }
+                    WorkingGroup::Distribution => {
+                        run_create_terminate_group_leader_role_proposal_with_slashing_execution_succeeds::<Runtime, DistributionWorkingGroupInstance>(group);
+                    }
                 }
             }
         }

+ 2 - 2
storage-node-v2/src/services/runtime/extrinsics.ts

@@ -11,8 +11,8 @@ export async function createStorageBucket(
   account: KeyringPair,
   invitedWorker: number | null = null,
   allowedNewBags = true,
-  sizeLimit = 0,
-  objectsLimit = 0
+  sizeLimit: number = 0,
+  objectsLimit: number = 0
 ): Promise<boolean> {
   return await extrinsicWrapper(() => {
     const invitedWorkerValue = api.createType('Option<WorkerId>', invitedWorker)

File diff suppressed because it is too large
+ 1 - 2
types/augment-codec/all.ts


+ 29 - 5
types/augment-codec/augment-api-consts.ts

@@ -2,7 +2,7 @@
 /* eslint-disable */
 
 import type { Vec, u32, u64 } from '@polkadot/types';
-import type { DynamicBagCreationPolicy, StorageBucketsPerBagValueConstraint } from './all';
+import type { StorageBucketsPerBagValueConstraint } from './all';
 import type { Balance, BalanceOf, BlockNumber, Moment, Perbill, RuntimeDbWeight, Weight } from '@polkadot/types/interfaces/runtime';
 import type { SessionIndex } from '@polkadot/types/interfaces/session';
 import type { EraIndex } from '@polkadot/types/interfaces/staking';
@@ -38,6 +38,12 @@ declare module '@polkadot/api/types/consts' {
        **/
       maxWorkerNumberLimit: u32 & AugmentedConst<ApiType>;
     };
+    distributionWorkingGroup: {
+      /**
+       * Exports const -  max simultaneous active worker number.
+       **/
+      maxWorkerNumberLimit: u32 & AugmentedConst<ApiType>;
+    };
     finalityTracker: {
       /**
        * The delay after which point things become suspicious. Default is 1000.
@@ -153,17 +159,35 @@ declare module '@polkadot/api/types/consts' {
        **/
       dataObjectDeletionPrize: BalanceOf & AugmentedConst<ApiType>;
       /**
-       * Exports const - the default dynamic bag creation policy for channels.
+       * Exports const - the default dynamic bag creation policy for channels (storage bucket
+       * number).
+       **/
+      defaultChannelDynamicBagNumberOfStorageBuckets: u64 & AugmentedConst<ApiType>;
+      /**
+       * Exports const - the default dynamic bag creation policy for members (storage bucket
+       * number).
        **/
-      defaultChannelDynamicBagCreationPolicy: DynamicBagCreationPolicy & AugmentedConst<ApiType>;
+      defaultMemberDynamicBagNumberOfStorageBuckets: u64 & AugmentedConst<ApiType>;
       /**
-       * Exports const - the default dynamic bag creation policy for members.
+       * Exports const - "Distribution buckets per bag" value constraint.
        **/
-      defaultMemberDynamicBagCreationPolicy: DynamicBagCreationPolicy & AugmentedConst<ApiType>;
+      distributionBucketsPerBagValueConstraint: StorageBucketsPerBagValueConstraint & AugmentedConst<ApiType>;
+      /**
+       * Exports const - max allowed distribution bucket family number.
+       **/
+      maxDistributionBucketFamilyNumber: u64 & AugmentedConst<ApiType>;
+      /**
+       * Exports const - max allowed distribution bucket number per family.
+       **/
+      maxDistributionBucketNumberPerFamily: u64 & AugmentedConst<ApiType>;
       /**
        * Exports const - max number of data objects per bag.
        **/
       maxNumberOfDataObjectsPerBag: u64 & AugmentedConst<ApiType>;
+      /**
+       * Exports const - max number of pending invitations per distribution bucket.
+       **/
+      maxNumberOfPendingInvitationsPerDistributionBucket: u64 & AugmentedConst<ApiType>;
       /**
        * Exports const - max allowed storage bucket number.
        **/

+ 466 - 0
types/augment-codec/augment-api-errors.ts

@@ -763,6 +763,400 @@ declare module '@polkadot/api/types/errors' {
        **/
       WorkerHasNoReward: AugmentedError<ApiType>;
     };
+    distributionWorkingGroup: {
+      /**
+       * Opening does not exist.
+       **/
+      AcceptWorkerApplicationsOpeningDoesNotExist: AugmentedError<ApiType>;
+      /**
+       * Opening Is Not in Waiting to begin.
+       **/
+      AcceptWorkerApplicationsOpeningIsNotWaitingToBegin: AugmentedError<ApiType>;
+      /**
+       * Opening does not activate in the future.
+       **/
+      AddWorkerOpeningActivatesInThePast: AugmentedError<ApiType>;
+      /**
+       * Add worker opening application stake cannot be zero.
+       **/
+      AddWorkerOpeningApplicationStakeCannotBeZero: AugmentedError<ApiType>;
+      /**
+       * Application stake amount less than minimum currency balance.
+       **/
+      AddWorkerOpeningAppliicationStakeLessThanMinimum: AugmentedError<ApiType>;
+      /**
+       * New application was crowded out.
+       **/
+      AddWorkerOpeningNewApplicationWasCrowdedOut: AugmentedError<ApiType>;
+      /**
+       * Opening does not exist.
+       **/
+      AddWorkerOpeningOpeningDoesNotExist: AugmentedError<ApiType>;
+      /**
+       * Opening is not in accepting applications stage.
+       **/
+      AddWorkerOpeningOpeningNotInAcceptingApplicationStage: AugmentedError<ApiType>;
+      /**
+       * Add worker opening role stake cannot be zero.
+       **/
+      AddWorkerOpeningRoleStakeCannotBeZero: AugmentedError<ApiType>;
+      /**
+       * Role stake amount less than minimum currency balance.
+       **/
+      AddWorkerOpeningRoleStakeLessThanMinimum: AugmentedError<ApiType>;
+      /**
+       * Stake amount too low.
+       **/
+      AddWorkerOpeningStakeAmountTooLow: AugmentedError<ApiType>;
+      /**
+       * Stake missing when required.
+       **/
+      AddWorkerOpeningStakeMissingWhenRequired: AugmentedError<ApiType>;
+      /**
+       * Stake provided when redundant.
+       **/
+      AddWorkerOpeningStakeProvidedWhenRedundant: AugmentedError<ApiType>;
+      /**
+       * Application rationing has zero max active applicants.
+       **/
+      AddWorkerOpeningZeroMaxApplicantCount: AugmentedError<ApiType>;
+      /**
+       * Invalid OpeningPolicyCommitment parameter (application_rationing_policy):
+       * max_active_applicants should be non-zero.
+       **/
+      ApplicationRationingPolicyMaxActiveApplicantsIsZero: AugmentedError<ApiType>;
+      /**
+       * Invalid OpeningPolicyCommitment parameter (application_staking_policy):
+       * crowded_out_unstaking_period_length should be non-zero.
+       **/
+      ApplicationStakingPolicyCrowdedOutUnstakingPeriodIsZero: AugmentedError<ApiType>;
+      /**
+       * Invalid OpeningPolicyCommitment parameter (application_staking_policy):
+       * review_period_expired_unstaking_period_length should be non-zero.
+       **/
+      ApplicationStakingPolicyReviewPeriodUnstakingPeriodIsZero: AugmentedError<ApiType>;
+      /**
+       * Signer does not match controller account.
+       **/
+      ApplyOnWorkerOpeningSignerNotControllerAccount: AugmentedError<ApiType>;
+      /**
+       * Opening does not exist.
+       **/
+      BeginWorkerApplicantReviewOpeningDoesNotExist: AugmentedError<ApiType>;
+      /**
+       * Opening Is Not in Waiting.
+       **/
+      BeginWorkerApplicantReviewOpeningOpeningIsNotWaitingToBegin: AugmentedError<ApiType>;
+      /**
+       * Cannot find mint in the minting module.
+       **/
+      CannotFindMint: AugmentedError<ApiType>;
+      /**
+       * There is leader already, cannot hire another one.
+       **/
+      CannotHireLeaderWhenLeaderExists: AugmentedError<ApiType>;
+      /**
+       * Cannot fill opening with multiple applications.
+       **/
+      CannotHireMultipleLeaders: AugmentedError<ApiType>;
+      /**
+       * Current lead is not set.
+       **/
+      CurrentLeadNotSet: AugmentedError<ApiType>;
+      /**
+       * Invalid OpeningPolicyCommitment parameter:
+       * exit_role_application_stake_unstaking_period should be non-zero.
+       **/
+      ExitRoleApplicationStakeUnstakingPeriodIsZero: AugmentedError<ApiType>;
+      /**
+       * Invalid OpeningPolicyCommitment parameter:
+       * exit_role_stake_unstaking_period should be non-zero.
+       **/
+      ExitRoleStakeUnstakingPeriodIsZero: AugmentedError<ApiType>;
+      /**
+       * Invalid OpeningPolicyCommitment parameter:
+       * fill_opening_failed_applicant_application_stake_unstaking_period should be non-zero.
+       **/
+      FillOpeningFailedApplicantApplicationStakeUnstakingPeriodIsZero: AugmentedError<ApiType>;
+      /**
+       * Invalid OpeningPolicyCommitment parameter:
+       * fill_opening_failed_applicant_role_stake_unstaking_period should be non-zero.
+       **/
+      FillOpeningFailedApplicantRoleStakeUnstakingPeriodIsZero: AugmentedError<ApiType>;
+      /**
+       * Reward policy has invalid next payment block number.
+       **/
+      FillOpeningInvalidNextPaymentBlock: AugmentedError<ApiType>;
+      /**
+       * Working group mint does not exist.
+       **/
+      FillOpeningMintDoesNotExist: AugmentedError<ApiType>;
+      /**
+       * Invalid OpeningPolicyCommitment parameter:
+       * fill_opening_successful_applicant_application_stake_unstaking_period should be non-zero.
+       **/
+      FillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriodIsZero: AugmentedError<ApiType>;
+      /**
+       * Applications not for opening.
+       **/
+      FillWorkerOpeningApplicationForWrongOpening: AugmentedError<ApiType>;
+      /**
+       * Application does not exist.
+       **/
+      FullWorkerOpeningApplicationDoesNotExist: AugmentedError<ApiType>;
+      /**
+       * Application not in active stage.
+       **/
+      FullWorkerOpeningApplicationNotActive: AugmentedError<ApiType>;
+      /**
+       * OpeningDoesNotExist.
+       **/
+      FullWorkerOpeningOpeningDoesNotExist: AugmentedError<ApiType>;
+      /**
+       * Opening not in review period stage.
+       **/
+      FullWorkerOpeningOpeningNotInReviewPeriodStage: AugmentedError<ApiType>;
+      /**
+       * Application stake unstaking period for successful applicants redundant.
+       **/
+      FullWorkerOpeningSuccessfulApplicationStakeUnstakingPeriodRedundant: AugmentedError<ApiType>;
+      /**
+       * Application stake unstaking period for failed applicants too short.
+       **/
+      FullWorkerOpeningSuccessfulApplicationStakeUnstakingPeriodTooShort: AugmentedError<ApiType>;
+      /**
+       * Role stake unstaking period for successful applicants redundant.
+       **/
+      FullWorkerOpeningSuccessfulRoleStakeUnstakingPeriodRedundant: AugmentedError<ApiType>;
+      /**
+       * Role stake unstaking period for successful applicants too short.
+       **/
+      FullWorkerOpeningSuccessfulRoleStakeUnstakingPeriodTooShort: AugmentedError<ApiType>;
+      /**
+       * Application stake unstaking period for failed applicants redundant.
+       **/
+      FullWorkerOpeningUnsuccessfulApplicationStakeUnstakingPeriodRedundant: AugmentedError<ApiType>;
+      /**
+       * Application stake unstaking period for successful applicants too short.
+       **/
+      FullWorkerOpeningUnsuccessfulApplicationStakeUnstakingPeriodTooShort: AugmentedError<ApiType>;
+      /**
+       * Role stake unstaking period for failed applicants redundant.
+       **/
+      FullWorkerOpeningUnsuccessfulRoleStakeUnstakingPeriodRedundant: AugmentedError<ApiType>;
+      /**
+       * Role stake unstaking period for failed applicants too short.
+       **/
+      FullWorkerOpeningUnsuccessfulRoleStakeUnstakingPeriodTooShort: AugmentedError<ApiType>;
+      /**
+       * Insufficient balance to apply.
+       **/
+      InsufficientBalanceToApply: AugmentedError<ApiType>;
+      /**
+       * Insufficient balance to cover stake.
+       **/
+      InsufficientBalanceToCoverStake: AugmentedError<ApiType>;
+      /**
+       * Not a lead account.
+       **/
+      IsNotLeadAccount: AugmentedError<ApiType>;
+      /**
+       * Working group size limit exceeded.
+       **/
+      MaxActiveWorkerNumberExceeded: AugmentedError<ApiType>;
+      /**
+       * Member already has an active application on the opening.
+       **/
+      MemberHasActiveApplicationOnOpening: AugmentedError<ApiType>;
+      /**
+       * Member id is invalid.
+       **/
+      MembershipInvalidMemberId: AugmentedError<ApiType>;
+      /**
+       * Unsigned origin.
+       **/
+      MembershipUnsignedOrigin: AugmentedError<ApiType>;
+      /**
+       * Minting error: NextAdjustmentInPast
+       **/
+      MintingErrorNextAdjustmentInPast: AugmentedError<ApiType>;
+      /**
+       * Cannot get the worker stake profile.
+       **/
+      NoWorkerStakeProfile: AugmentedError<ApiType>;
+      /**
+       * Opening does not exist.
+       **/
+      OpeningDoesNotExist: AugmentedError<ApiType>;
+      /**
+       * Opening text too long.
+       **/
+      OpeningTextTooLong: AugmentedError<ApiType>;
+      /**
+       * Opening text too short.
+       **/
+      OpeningTextTooShort: AugmentedError<ApiType>;
+      /**
+       * Origin must be controller or root account of member.
+       **/
+      OriginIsNeitherMemberControllerOrRoot: AugmentedError<ApiType>;
+      /**
+       * Origin is not applicant.
+       **/
+      OriginIsNotApplicant: AugmentedError<ApiType>;
+      /**
+       * Next payment is not in the future.
+       **/
+      RecurringRewardsNextPaymentNotInFuture: AugmentedError<ApiType>;
+      /**
+       * Recipient not found.
+       **/
+      RecurringRewardsRecipientNotFound: AugmentedError<ApiType>;
+      /**
+       * Reward relationship not found.
+       **/
+      RecurringRewardsRewardRelationshipNotFound: AugmentedError<ApiType>;
+      /**
+       * Recipient reward source not found.
+       **/
+      RecurringRewardsRewardSourceNotFound: AugmentedError<ApiType>;
+      /**
+       * Relationship must exist.
+       **/
+      RelationshipMustExist: AugmentedError<ApiType>;
+      /**
+       * Require root origin in extrinsics.
+       **/
+      RequireRootOrigin: AugmentedError<ApiType>;
+      /**
+       * Require signed origin in extrinsics.
+       **/
+      RequireSignedOrigin: AugmentedError<ApiType>;
+      /**
+       * Invalid OpeningPolicyCommitment parameter (role_staking_policy):
+       * crowded_out_unstaking_period_length should be non-zero.
+       **/
+      RoleStakingPolicyCrowdedOutUnstakingPeriodIsZero: AugmentedError<ApiType>;
+      /**
+       * Invalid OpeningPolicyCommitment parameter (role_staking_policy):
+       * review_period_expired_unstaking_period_length should be non-zero.
+       **/
+      RoleStakingPolicyReviewPeriodUnstakingPeriodIsZero: AugmentedError<ApiType>;
+      /**
+       * Signer is not worker role account.
+       **/
+      SignerIsNotWorkerRoleAccount: AugmentedError<ApiType>;
+      /**
+       * Provided stake balance cannot be zero.
+       **/
+      StakeBalanceCannotBeZero: AugmentedError<ApiType>;
+      /**
+       * Already unstaking.
+       **/
+      StakingErrorAlreadyUnstaking: AugmentedError<ApiType>;
+      /**
+       * Cannot change stake by zero.
+       **/
+      StakingErrorCannotChangeStakeByZero: AugmentedError<ApiType>;
+      /**
+       * Cannot decrease stake while slashes ongoing.
+       **/
+      StakingErrorCannotDecreaseWhileSlashesOngoing: AugmentedError<ApiType>;
+      /**
+       * Cannot increase stake while unstaking.
+       **/
+      StakingErrorCannotIncreaseStakeWhileUnstaking: AugmentedError<ApiType>;
+      /**
+       * Cannot unstake while slashes ongoing.
+       **/
+      StakingErrorCannotUnstakeWhileSlashesOngoing: AugmentedError<ApiType>;
+      /**
+       * Insufficient balance in source account.
+       **/
+      StakingErrorInsufficientBalanceInSourceAccount: AugmentedError<ApiType>;
+      /**
+       * Insufficient stake to decrease.
+       **/
+      StakingErrorInsufficientStake: AugmentedError<ApiType>;
+      /**
+       * Not staked.
+       **/
+      StakingErrorNotStaked: AugmentedError<ApiType>;
+      /**
+       * Slash amount should be greater than zero.
+       **/
+      StakingErrorSlashAmountShouldBeGreaterThanZero: AugmentedError<ApiType>;
+      /**
+       * Stake not found.
+       **/
+      StakingErrorStakeNotFound: AugmentedError<ApiType>;
+      /**
+       * Unstaking period should be greater than zero.
+       **/
+      StakingErrorUnstakingPeriodShouldBeGreaterThanZero: AugmentedError<ApiType>;
+      /**
+       * Successful worker application does not exist.
+       **/
+      SuccessfulWorkerApplicationDoesNotExist: AugmentedError<ApiType>;
+      /**
+       * Invalid OpeningPolicyCommitment parameter:
+       * terminate_application_stake_unstaking_period should be non-zero.
+       **/
+      TerminateApplicationStakeUnstakingPeriodIsZero: AugmentedError<ApiType>;
+      /**
+       * Invalid OpeningPolicyCommitment parameter:
+       * terminate_role_stake_unstaking_period should be non-zero.
+       **/
+      TerminateRoleStakeUnstakingPeriodIsZero: AugmentedError<ApiType>;
+      /**
+       * Application does not exist.
+       **/
+      WithdrawWorkerApplicationApplicationDoesNotExist: AugmentedError<ApiType>;
+      /**
+       * Application is not active.
+       **/
+      WithdrawWorkerApplicationApplicationNotActive: AugmentedError<ApiType>;
+      /**
+       * Opening not accepting applications.
+       **/
+      WithdrawWorkerApplicationOpeningNotAcceptingApplications: AugmentedError<ApiType>;
+      /**
+       * Redundant unstaking period provided
+       **/
+      WithdrawWorkerApplicationRedundantUnstakingPeriod: AugmentedError<ApiType>;
+      /**
+       * UnstakingPeriodTooShort .... // <== SHOULD REALLY BE TWO SEPARATE, ONE FOR EACH STAKING PURPOSE
+       **/
+      WithdrawWorkerApplicationUnstakingPeriodTooShort: AugmentedError<ApiType>;
+      /**
+       * Worker application does not exist.
+       **/
+      WorkerApplicationDoesNotExist: AugmentedError<ApiType>;
+      /**
+       * Worker application text too long.
+       **/
+      WorkerApplicationTextTooLong: AugmentedError<ApiType>;
+      /**
+       * Worker application text too short.
+       **/
+      WorkerApplicationTextTooShort: AugmentedError<ApiType>;
+      /**
+       * Worker does not exist.
+       **/
+      WorkerDoesNotExist: AugmentedError<ApiType>;
+      /**
+       * Worker exit rationale text is too long.
+       **/
+      WorkerExitRationaleTextTooLong: AugmentedError<ApiType>;
+      /**
+       * Worker exit rationale text is too short.
+       **/
+      WorkerExitRationaleTextTooShort: AugmentedError<ApiType>;
+      /**
+       * Worker has no recurring reward.
+       **/
+      WorkerHasNoReward: AugmentedError<ApiType>;
+    };
     finalityTracker: {
       /**
        * Final hint must be updated only once in the block
@@ -1181,6 +1575,54 @@ declare module '@polkadot/api/types/errors' {
        * Invalid operation with invites: another storage provider was invited.
        **/
       DifferentStorageProviderInvited: AugmentedError<ApiType>;
+      /**
+       * Distribution bucket doesn't accept new bags.
+       **/
+      DistributionBucketDoesntAcceptNewBags: AugmentedError<ApiType>;
+      /**
+       * Distribution bucket doesn't exist.
+       **/
+      DistributionBucketDoesntExist: AugmentedError<ApiType>;
+      /**
+       * Distribution bucket family doesn't exist.
+       **/
+      DistributionBucketFamilyDoesntExist: AugmentedError<ApiType>;
+      /**
+       * Distribution bucket id collections are empty.
+       **/
+      DistributionBucketIdCollectionsAreEmpty: AugmentedError<ApiType>;
+      /**
+       * Distribution bucket is bound to a bag.
+       **/
+      DistributionBucketIsBoundToBag: AugmentedError<ApiType>;
+      /**
+       * Distribution bucket is not bound to a bag.
+       **/
+      DistributionBucketIsNotBoundToBag: AugmentedError<ApiType>;
+      /**
+       * The new `DistributionBucketsPerBagLimit` number is too high.
+       **/
+      DistributionBucketsPerBagLimitTooHigh: AugmentedError<ApiType>;
+      /**
+       * The new `DistributionBucketsPerBagLimit` number is too low.
+       **/
+      DistributionBucketsPerBagLimitTooLow: AugmentedError<ApiType>;
+      /**
+       * Distribution family bound to a bag creation policy.
+       **/
+      DistributionFamilyBoundToBagCreationPolicy: AugmentedError<ApiType>;
+      /**
+       * Distribution provider operator already invited.
+       **/
+      DistributionProviderOperatorAlreadyInvited: AugmentedError<ApiType>;
+      /**
+       * Distribution provider operator doesn't exist.
+       **/
+      DistributionProviderOperatorDoesntExist: AugmentedError<ApiType>;
+      /**
+       * Distribution provider operator already set.
+       **/
+      DistributionProviderOperatorSet: AugmentedError<ApiType>;
       /**
        * Dynamic bag doesn't exist.
        **/
@@ -1213,10 +1655,34 @@ declare module '@polkadot/api/types/errors' {
        * Invalid operation with invites: storage provider was already invited.
        **/
       InvitedStorageProvider: AugmentedError<ApiType>;
+      /**
+       * Max distribution bucket family number limit exceeded.
+       **/
+      MaxDistributionBucketFamilyNumberLimitExceeded: AugmentedError<ApiType>;
+      /**
+       * Max distribution bucket number per bag limit exceeded.
+       **/
+      MaxDistributionBucketNumberPerBagLimitExceeded: AugmentedError<ApiType>;
+      /**
+       * Max distribution bucket number per family limit exceeded.
+       **/
+      MaxDistributionBucketNumberPerFamilyLimitExceeded: AugmentedError<ApiType>;
+      /**
+       * Max number of pending invitations limit for a distribution bucket reached.
+       **/
+      MaxNumberOfPendingInvitationsLimitForDistributionBucketReached: AugmentedError<ApiType>;
       /**
        * Max storage bucket number limit exceeded.
        **/
       MaxStorageBucketNumberLimitExceeded: AugmentedError<ApiType>;
+      /**
+       * Invalid operations: must be a distribution provider operator for a bucket.
+       **/
+      MustBeDistributionProviderOperatorForBucket: AugmentedError<ApiType>;
+      /**
+       * No distribution bucket invitation.
+       **/
+      NoDistributionBucketInvitation: AugmentedError<ApiType>;
       /**
        * Empty "data object creation" collection.
        **/

+ 222 - 2
types/augment-codec/augment-api-events.ts

@@ -1,8 +1,8 @@
 // Auto-generated via `yarn polkadot-types-from-chain`, do not edit
 /* eslint-disable */
 
-import type { BTreeSet, Bytes, Option, Vec, bool, u16, u32, u64 } from '@polkadot/types';
-import type { Actor, ApplicationId, ApplicationIdToWorkerIdMap, BagId, CategoryId, ChannelId, ClassId, ContentId, CuratorApplicationId, CuratorApplicationIdToCuratorIdMap, CuratorGroupId, CuratorId, CuratorOpeningId, DataObjectId, DynamicBagId, DynamicBagType, EntityController, EntityCreationVoucher, EntityId, FailedAt, LeadId, MemberId, MintBalanceOf, MintId, Nonce, OpeningId, PostId, PropertyId, ProposalId, ProposalStatus, RationaleText, SchemaId, SideEffect, SideEffects, Status, StorageBucketId, ThreadId, UploadParameters, VecMaxLength, VoteKind, Voucher, WorkerId } from './all';
+import type { BTreeMap, BTreeSet, Bytes, Option, Vec, bool, u16, u32, u64 } from '@polkadot/types';
+import type { Actor, ApplicationId, ApplicationIdToWorkerIdMap, BagId, CategoryId, ChannelId, ClassId, ContentId, CuratorApplicationId, CuratorApplicationIdToCuratorIdMap, CuratorGroupId, CuratorId, CuratorOpeningId, DataObjectId, DistributionBucketFamilyId, DistributionBucketId, DynamicBagId, DynamicBagType, EntityController, EntityCreationVoucher, EntityId, FailedAt, LeadId, MemberId, MintBalanceOf, MintId, Nonce, OpeningId, PostId, PropertyId, ProposalId, ProposalStatus, RationaleText, SchemaId, SideEffect, SideEffects, Status, StorageBucketId, ThreadId, UploadParameters, VecMaxLength, VoteKind, Voucher, WorkerId } from './all';
 import type { BalanceStatus } from '@polkadot/types/interfaces/balances';
 import type { AuthorityId } from '@polkadot/types/interfaces/consensus';
 import type { AuthorityList } from '@polkadot/types/interfaces/grandpa';
@@ -243,6 +243,129 @@ declare module '@polkadot/api/types/events' {
       VotingEnded: AugmentedEvent<ApiType, []>;
       VotingStarted: AugmentedEvent<ApiType, []>;
     };
+    distributionWorkingGroup: {
+      /**
+       * Emits on accepting application for the worker opening.
+       * Params:
+       * - Opening id
+       **/
+      AcceptedApplications: AugmentedEvent<ApiType, [OpeningId]>;
+      /**
+       * Emits on terminating the application for the worker/lead opening.
+       * Params:
+       * - Worker application id
+       **/
+      ApplicationTerminated: AugmentedEvent<ApiType, [ApplicationId]>;
+      /**
+       * Emits on withdrawing the application for the worker/lead opening.
+       * Params:
+       * - Worker application id
+       **/
+      ApplicationWithdrawn: AugmentedEvent<ApiType, [ApplicationId]>;
+      /**
+       * Emits on adding the application for the worker opening.
+       * Params:
+       * - Opening id
+       * - Application id
+       **/
+      AppliedOnOpening: AugmentedEvent<ApiType, [OpeningId, ApplicationId]>;
+      /**
+       * Emits on beginning the application review for the worker/lead opening.
+       * Params:
+       * - Opening id
+       **/
+      BeganApplicationReview: AugmentedEvent<ApiType, [OpeningId]>;
+      /**
+       * Emits on setting the leader.
+       * Params:
+       * - Worker id.
+       **/
+      LeaderSet: AugmentedEvent<ApiType, [WorkerId]>;
+      /**
+       * Emits on un-setting the leader.
+       * Params:
+       **/
+      LeaderUnset: AugmentedEvent<ApiType, []>;
+      /**
+       * Emits on changing working group mint capacity.
+       * Params:
+       * - mint id.
+       * - new mint balance.
+       **/
+      MintCapacityChanged: AugmentedEvent<ApiType, [MintId, MintBalanceOf]>;
+      /**
+       * Emits on adding new worker opening.
+       * Params:
+       * - Opening id
+       **/
+      OpeningAdded: AugmentedEvent<ApiType, [OpeningId]>;
+      /**
+       * Emits on filling the worker opening.
+       * Params:
+       * - Worker opening id
+       * - Worker application id to the worker id dictionary
+       **/
+      OpeningFilled: AugmentedEvent<ApiType, [OpeningId, ApplicationIdToWorkerIdMap]>;
+      /**
+       * Emits on decreasing the worker/lead stake.
+       * Params:
+       * - worker/lead id.
+       **/
+      StakeDecreased: AugmentedEvent<ApiType, [WorkerId]>;
+      /**
+       * Emits on increasing the worker/lead stake.
+       * Params:
+       * - worker/lead id.
+       **/
+      StakeIncreased: AugmentedEvent<ApiType, [WorkerId]>;
+      /**
+       * Emits on slashing the worker/lead stake.
+       * Params:
+       * - worker/lead id.
+       **/
+      StakeSlashed: AugmentedEvent<ApiType, [WorkerId]>;
+      /**
+       * Emits on terminating the leader.
+       * Params:
+       * - leader worker id.
+       * - termination rationale text
+       **/
+      TerminatedLeader: AugmentedEvent<ApiType, [WorkerId, RationaleText]>;
+      /**
+       * Emits on terminating the worker.
+       * Params:
+       * - worker id.
+       * - termination rationale text
+       **/
+      TerminatedWorker: AugmentedEvent<ApiType, [WorkerId, RationaleText]>;
+      /**
+       * Emits on exiting the worker.
+       * Params:
+       * - worker id.
+       * - exit rationale text
+       **/
+      WorkerExited: AugmentedEvent<ApiType, [WorkerId, RationaleText]>;
+      /**
+       * Emits on updating the reward account of the worker.
+       * Params:
+       * - Member id of the worker.
+       * - Reward account id of the worker.
+       **/
+      WorkerRewardAccountUpdated: AugmentedEvent<ApiType, [WorkerId, AccountId]>;
+      /**
+       * Emits on updating the reward amount of the worker.
+       * Params:
+       * - Id of the worker.
+       **/
+      WorkerRewardAmountUpdated: AugmentedEvent<ApiType, [WorkerId]>;
+      /**
+       * Emits on updating the role account of the worker.
+       * Params:
+       * - Id of the worker.
+       * - Role account id of the worker.
+       **/
+      WorkerRoleAccountUpdated: AugmentedEvent<ApiType, [WorkerId, AccountId]>;
+    };
     forum: {
       /**
        * A category was introduced
@@ -456,6 +579,96 @@ declare module '@polkadot/api/types/events' {
        * - new deletion prize
        **/
       DeletionPrizeChanged: AugmentedEvent<ApiType, [DynamicBagId, Balance]>;
+      /**
+       * Emits on creating distribution bucket.
+       * Params
+       * - distribution bucket family ID
+       * - accepting new bags
+       * - distribution bucket ID
+       **/
+      DistributionBucketCreated: AugmentedEvent<ApiType, [DistributionBucketFamilyId, bool, DistributionBucketId]>;
+      /**
+       * Emits on deleting distribution bucket.
+       * Params
+       * - distribution bucket family ID
+       * - distribution bucket ID
+       **/
+      DistributionBucketDeleted: AugmentedEvent<ApiType, [DistributionBucketFamilyId, DistributionBucketId]>;
+      /**
+       * Emits on creating distribution bucket family.
+       * Params
+       * - distribution family bucket ID
+       **/
+      DistributionBucketFamilyCreated: AugmentedEvent<ApiType, [DistributionBucketFamilyId]>;
+      /**
+       * Emits on deleting distribution bucket family.
+       * Params
+       * - distribution family bucket ID
+       **/
+      DistributionBucketFamilyDeleted: AugmentedEvent<ApiType, [DistributionBucketFamilyId]>;
+      /**
+       * Emits on accepting a distribution bucket invitation for the operator.
+       * Params
+       * - worker ID
+       * - distribution bucket family ID
+       * - distribution bucket ID
+       **/
+      DistributionBucketInvitationAccepted: AugmentedEvent<ApiType, [WorkerId, DistributionBucketFamilyId, DistributionBucketId]>;
+      /**
+       * Emits on canceling a distribution bucket invitation for the operator.
+       * Params
+       * - distribution bucket family ID
+       * - distribution bucket ID
+       * - operator worker ID
+       **/
+      DistributionBucketInvitationCancelled: AugmentedEvent<ApiType, [DistributionBucketFamilyId, DistributionBucketId, WorkerId]>;
+      /**
+       * Emits on setting the metadata by a distribution bucket operator.
+       * Params
+       * - worker ID
+       * - distribution bucket family ID
+       * - distribution bucket ID
+       * - metadata
+       **/
+      DistributionBucketMetadataSet: AugmentedEvent<ApiType, [WorkerId, DistributionBucketFamilyId, DistributionBucketId, Bytes]>;
+      /**
+       * Emits on storage bucket mode update (distributing flag).
+       * Params
+       * - distribution bucket family ID
+       * - distribution bucket ID
+       * - distributing
+       **/
+      DistributionBucketModeUpdated: AugmentedEvent<ApiType, [DistributionBucketFamilyId, DistributionBucketId, bool]>;
+      /**
+       * Emits on creating a distribution bucket invitation for the operator.
+       * Params
+       * - distribution bucket family ID
+       * - distribution bucket ID
+       * - worker ID
+       **/
+      DistributionBucketOperatorInvited: AugmentedEvent<ApiType, [DistributionBucketFamilyId, DistributionBucketId, WorkerId]>;
+      /**
+       * Emits on changing the "Distribution buckets per bag" number limit.
+       * Params
+       * - new limit
+       **/
+      DistributionBucketsPerBagLimitUpdated: AugmentedEvent<ApiType, [u64]>;
+      /**
+       * Emits on storage bucket status update (accepting new bags).
+       * Params
+       * - distribution bucket family ID
+       * - distribution bucket ID
+       * - new status (accepting new bags)
+       **/
+      DistributionBucketStatusUpdated: AugmentedEvent<ApiType, [DistributionBucketFamilyId, DistributionBucketId, bool]>;
+      /**
+       * Emits on updating distribution buckets for bag.
+       * Params
+       * - bag ID
+       * - storage buckets to add ID collection
+       * - storage buckets to remove ID collection
+       **/
+      DistributionBucketsUpdatedForBag: AugmentedEvent<ApiType, [BagId, DistributionBucketFamilyId, BTreeSet<DistributionBucketId>, BTreeSet<DistributionBucketId>]>;
       /**
        * Emits on creating a dynamic bag.
        * Params
@@ -469,6 +682,13 @@ declare module '@polkadot/api/types/events' {
        * - dynamic bag ID
        **/
       DynamicBagDeleted: AugmentedEvent<ApiType, [AccountId, DynamicBagId]>;
+      /**
+       * Emits on dynamic bag creation policy update (distribution bucket families).
+       * Params
+       * - dynamic bag type
+       * - families and bucket numbers
+       **/
+      FamiliesInDynamicBagCreationPolicyUpdated: AugmentedEvent<ApiType, [DynamicBagType, BTreeMap<DistributionBucketFamilyId, u32>]>;
       /**
        * Emits on updating the number of storage buckets in dynamic bag creation policy.
        * Params

+ 76 - 1
types/augment-codec/augment-api-query.ts

@@ -3,7 +3,7 @@
 
 import type { Bytes, Option, Vec, bool, u32, u64 } from '@polkadot/types';
 import type { AnyNumber, ITuple, Observable } from '@polkadot/types/types';
-import type { Application, ApplicationId, ApplicationOf, Category, CategoryId, Channel, ChannelId, Class, ClassId, ClassOf, ClassPermissionsType, ContentId, Credential, Curator, CuratorApplication, CuratorApplicationId, CuratorGroup, CuratorGroupId, CuratorId, CuratorOpening, CuratorOpeningId, DataObjectId, DiscussionPost, DiscussionThread, DynamicBag, DynamicBagCreationPolicy, DynamicBagId, DynamicBagType, ElectionStage, ElectionStake, Entity, EntityController, EntityCreationVoucher, EntityId, EntityOf, HiringApplicationId, InputValidationLengthConstraint, Lead, LeadId, MemberId, Membership, MemoText, Mint, MintId, Opening, OpeningId, OpeningOf, PaidMembershipTerms, PaidTermId, Post, PostId, Principal, PrincipalId, PropertyId, ProposalDetailsOf, ProposalId, ProposalOf, Recipient, RecipientId, RewardRelationship, RewardRelationshipId, SealedVote, Seats, Stake, StakeId, StaticBag, StaticBagId, StorageBucket, StorageBucketId, Thread, ThreadCounter, ThreadId, TransferableStake, VoteKind, WorkerId, WorkerOf, WorkingGroupUnstaker } from './all';
+import type { Application, ApplicationId, ApplicationOf, Category, CategoryId, Channel, ChannelId, Class, ClassId, ClassOf, ClassPermissionsType, ContentId, Credential, Curator, CuratorApplication, CuratorApplicationId, CuratorGroup, CuratorGroupId, CuratorId, CuratorOpening, CuratorOpeningId, DataObjectId, DiscussionPost, DiscussionThread, DistributionBucketFamily, DistributionBucketFamilyId, DistributionBucketId, DynamicBag, DynamicBagCreationPolicy, DynamicBagId, DynamicBagType, ElectionStage, ElectionStake, Entity, EntityController, EntityCreationVoucher, EntityId, EntityOf, HiringApplicationId, InputValidationLengthConstraint, Lead, LeadId, MemberId, Membership, MemoText, Mint, MintId, Opening, OpeningId, OpeningOf, PaidMembershipTerms, PaidTermId, Post, PostId, Principal, PrincipalId, PropertyId, ProposalDetailsOf, ProposalId, ProposalOf, Recipient, RecipientId, RewardRelationship, RewardRelationshipId, SealedVote, Seats, Stake, StakeId, StaticBag, StaticBagId, StorageBucket, StorageBucketId, Thread, ThreadCounter, ThreadId, TransferableStake, VoteKind, WorkerId, WorkerOf, WorkingGroupUnstaker } from './all';
 import type { UncleEntryItem } from '@polkadot/types/interfaces/authorship';
 import type { BabeAuthorityWeight, MaybeRandomness, NextConfigDescriptor, Randomness } from '@polkadot/types/interfaces/babe';
 import type { AccountData, BalanceLock } from '@polkadot/types/interfaces/balances';
@@ -331,6 +331,61 @@ declare module '@polkadot/api/types/storage' {
       votes: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<SealedVote>, [Hash]>;
       votingPeriod: AugmentedQuery<ApiType, () => Observable<BlockNumber>, []>;
     };
+    distributionWorkingGroup: {
+      /**
+       * Count of active workers.
+       **/
+      activeWorkerCount: AugmentedQuery<ApiType, () => Observable<u32>, []>;
+      /**
+       * Maps identifier to worker application on opening.
+       **/
+      applicationById: AugmentedQuery<ApiType, (arg: ApplicationId | AnyNumber | Uint8Array) => Observable<ApplicationOf>, [ApplicationId]>;
+      /**
+       * The current lead.
+       **/
+      currentLead: AugmentedQuery<ApiType, () => Observable<Option<WorkerId>>, []>;
+      /**
+       * Map member id by hiring application id.
+       * Required by StakingEventsHandler callback call to refund the balance on unstaking.
+       **/
+      memberIdByHiringApplicationId: AugmentedQuery<ApiType, (arg: HiringApplicationId | AnyNumber | Uint8Array) => Observable<MemberId>, [HiringApplicationId]>;
+      /**
+       * The mint currently funding the rewards for this module.
+       **/
+      mint: AugmentedQuery<ApiType, () => Observable<MintId>, []>;
+      /**
+       * Next identifier value for new worker application.
+       **/
+      nextApplicationId: AugmentedQuery<ApiType, () => Observable<ApplicationId>, []>;
+      /**
+       * Next identifier value for new worker opening.
+       **/
+      nextOpeningId: AugmentedQuery<ApiType, () => Observable<OpeningId>, []>;
+      /**
+       * Next identifier for new worker.
+       **/
+      nextWorkerId: AugmentedQuery<ApiType, () => Observable<WorkerId>, []>;
+      /**
+       * Maps identifier to worker opening.
+       **/
+      openingById: AugmentedQuery<ApiType, (arg: OpeningId | AnyNumber | Uint8Array) => Observable<OpeningOf>, [OpeningId]>;
+      /**
+       * Opening human readable text length limits
+       **/
+      openingHumanReadableText: AugmentedQuery<ApiType, () => Observable<InputValidationLengthConstraint>, []>;
+      /**
+       * Worker application human readable text length limits
+       **/
+      workerApplicationHumanReadableText: AugmentedQuery<ApiType, () => Observable<InputValidationLengthConstraint>, []>;
+      /**
+       * Maps identifier to corresponding worker.
+       **/
+      workerById: AugmentedQuery<ApiType, (arg: WorkerId | AnyNumber | Uint8Array) => Observable<WorkerOf>, [WorkerId]>;
+      /**
+       * Worker exit rationale text length limits.
+       **/
+      workerExitRationaleText: AugmentedQuery<ApiType, () => Observable<InputValidationLengthConstraint>, []>;
+    };
     forum: {
       /**
        * Map category identifier to corresponding category.
@@ -969,6 +1024,18 @@ declare module '@polkadot/api/types/storage' {
        * Size based pricing of new objects uploaded.
        **/
       dataObjectPerMegabyteFee: AugmentedQuery<ApiType, () => Observable<BalanceOf>, []>;
+      /**
+       * Distribution bucket families.
+       **/
+      distributionBucketFamilyById: AugmentedQuery<ApiType, (arg: DistributionBucketFamilyId | AnyNumber | Uint8Array) => Observable<DistributionBucketFamily>, [DistributionBucketFamilyId]>;
+      /**
+       * Total number of distribution bucket families in the system.
+       **/
+      distributionBucketFamilyNumber: AugmentedQuery<ApiType, () => Observable<u64>, []>;
+      /**
+       * "Distribution buckets per bag" number limit.
+       **/
+      distributionBucketsPerBagLimit: AugmentedQuery<ApiType, () => Observable<u64>, []>;
       /**
        * DynamicBagCreationPolicy by bag type storage map.
        **/
@@ -981,6 +1048,14 @@ declare module '@polkadot/api/types/storage' {
        * Data object id counter. Starts at zero.
        **/
       nextDataObjectId: AugmentedQuery<ApiType, () => Observable<DataObjectId>, []>;
+      /**
+       * Distribution bucket family id counter. Starts at zero.
+       **/
+      nextDistributionBucketFamilyId: AugmentedQuery<ApiType, () => Observable<DistributionBucketFamilyId>, []>;
+      /**
+       * Distribution bucket id counter. Starts at zero.
+       **/
+      nextDistributionBucketId: AugmentedQuery<ApiType, () => Observable<DistributionBucketId>, []>;
       /**
        * Storage bucket id counter. Starts at zero.
        **/

+ 136 - 3
types/augment-codec/augment-api-tx.ts

@@ -3,7 +3,7 @@
 
 import type { BTreeMap, BTreeSet, Bytes, Compact, Option, Vec, bool, u16, u32, u64 } from '@polkadot/types';
 import type { AnyNumber, ITuple } from '@polkadot/types/types';
-import type { ActivateOpeningAt, Actor, AddOpeningParameters, ApplicationId, ApplicationIdSet, BagId, BalanceOfMint, CategoryId, ChannelContentType, ChannelCurationStatus, ChannelId, ChannelPublicationStatus, ClassId, ClassPermissions, ClassPermissionsType, ClassPropertyValue, ContentId, Credential, CredentialSet, CurationActor, CuratorApplicationId, CuratorApplicationIdSet, CuratorGroupId, CuratorId, CuratorOpeningId, DataObjectId, DynamicBagType, ElectionParameters, EntityController, EntityId, EntityPermissions, FillOpeningParameters, InputPropertyValue, InputValue, MemberId, MemoText, Nonce, OpeningId, OpeningPolicyCommitment, OpeningType, Operation, OperationType, OptionalText, PaidTermId, PostId, Property, PropertyId, ProposalId, ReferenceConstraint, RewardPolicy, SchemaId, StorageBucketId, TerminateRoleParameters, ThreadId, UploadParameters, VecMaxLength, VoteKind, WorkerId, WorkingGroup } from './all';
+import type { ActivateOpeningAt, Actor, AddOpeningParameters, ApplicationId, ApplicationIdSet, BagId, BalanceOfMint, CategoryId, ChannelContentType, ChannelCurationStatus, ChannelId, ChannelPublicationStatus, ClassId, ClassPermissions, ClassPermissionsType, ClassPropertyValue, ContentId, Credential, CredentialSet, CurationActor, CuratorApplicationId, CuratorApplicationIdSet, CuratorGroupId, CuratorId, CuratorOpeningId, DataObjectId, DistributionBucketFamilyId, DistributionBucketId, DynamicBagId, DynamicBagType, ElectionParameters, EntityController, EntityId, EntityPermissions, FillOpeningParameters, InputPropertyValue, InputValue, MemberId, MemoText, Nonce, OpeningId, OpeningPolicyCommitment, OpeningType, Operation, OperationType, OptionalText, PaidTermId, PostId, Property, PropertyId, ProposalId, ReferenceConstraint, RewardPolicy, SchemaId, StorageBucketId, TerminateRoleParameters, ThreadId, UploadParameters, VecMaxLength, VoteKind, WorkerId, WorkingGroup } from './all';
 import type { BabeEquivocationProof } from '@polkadot/types/interfaces/babe';
 import type { Extrinsic, Signature } from '@polkadot/types/interfaces/extrinsics';
 import type { GrandpaEquivocationProof, KeyOwnerProof } from '@polkadot/types/interfaces/grandpa';
@@ -430,6 +430,83 @@ declare module '@polkadot/api/types/submittable' {
       setStageVoting: AugmentedSubmittable<(endsAt: BlockNumber | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [BlockNumber]>;
       vote: AugmentedSubmittable<(commitment: Hash | string | Uint8Array, stake: BalanceOf | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Hash, BalanceOf]>;
     };
+    distributionWorkingGroup: {
+      /**
+       * Begin accepting worker applications to an opening that is active.
+       * Require signed leader origin or the root (to accept applications for the leader position).
+       **/
+      acceptApplications: AugmentedSubmittable<(openingId: OpeningId | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [OpeningId]>;
+      /**
+       * Add an opening for a worker role.
+       * Require signed leader origin or the root (to add opening for the leader position).
+       **/
+      addOpening: AugmentedSubmittable<(activateAt: ActivateOpeningAt | { CurrentBlock: any } | { ExactBlock: any } | string | Uint8Array, commitment: OpeningPolicyCommitment | { application_rationing_policy?: any; max_review_period_length?: any; application_staking_policy?: any; role_staking_policy?: any; role_slashing_terms?: any; fill_opening_successful_applicant_application_stake_unstaking_period?: any; fill_opening_failed_applicant_application_stake_unstaking_period?: any; fill_opening_failed_applicant_role_stake_unstaking_period?: any; terminate_curator_application_stake_unstaking_period?: any; terminate_curator_role_stake_unstaking_period?: any; exit_curator_role_application_stake_unstaking_period?: any; exit_curator_role_stake_unstaking_period?: any } | string | Uint8Array, humanReadableText: Bytes | string | Uint8Array, openingType: OpeningType | 'Leader' | 'Worker' | number | Uint8Array) => SubmittableExtrinsic<ApiType>, [ActivateOpeningAt, OpeningPolicyCommitment, Bytes, OpeningType]>;
+      /**
+       * Apply on a worker opening.
+       **/
+      applyOnOpening: AugmentedSubmittable<(memberId: MemberId | AnyNumber | Uint8Array, openingId: OpeningId | AnyNumber | Uint8Array, roleAccountId: AccountId | string | Uint8Array, optRoleStakeBalance: Option<BalanceOf> | null | object | string | Uint8Array, optApplicationStakeBalance: Option<BalanceOf> | null | object | string | Uint8Array, humanReadableText: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [MemberId, OpeningId, AccountId, Option<BalanceOf>, Option<BalanceOf>, Bytes]>;
+      /**
+       * Begin reviewing, and therefore not accepting new applications.
+       * Require signed leader origin or the root (to begin review applications for the leader position).
+       **/
+      beginApplicantReview: AugmentedSubmittable<(openingId: OpeningId | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [OpeningId]>;
+      /**
+       * Decreases the worker/lead stake and returns the remainder to the worker role_account_id.
+       * Can be decreased to zero, no actions on zero stake.
+       * Require signed leader origin or the root (to decrease the leader stake).
+       **/
+      decreaseStake: AugmentedSubmittable<(workerId: WorkerId | AnyNumber | Uint8Array, balance: BalanceOf | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [WorkerId, BalanceOf]>;
+      /**
+       * Fill opening for worker/lead.
+       * Require signed leader origin or the root (to fill opening for the leader position).
+       **/
+      fillOpening: AugmentedSubmittable<(openingId: OpeningId | AnyNumber | Uint8Array, successfulApplicationIds: ApplicationIdSet, rewardPolicy: Option<RewardPolicy> | null | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [OpeningId, ApplicationIdSet, Option<RewardPolicy>]>;
+      /**
+       * Increases the worker/lead stake, demands a worker origin. Transfers tokens from the worker
+       * role_account_id to the stake. No limits on the stake.
+       **/
+      increaseStake: AugmentedSubmittable<(workerId: WorkerId | AnyNumber | Uint8Array, balance: BalanceOf | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [WorkerId, BalanceOf]>;
+      /**
+       * Leave the role by the active worker.
+       **/
+      leaveRole: AugmentedSubmittable<(workerId: WorkerId | AnyNumber | Uint8Array, rationaleText: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [WorkerId, Bytes]>;
+      /**
+       * Sets the capacity to enable working group budget. Requires root origin.
+       **/
+      setMintCapacity: AugmentedSubmittable<(newCapacity: BalanceOf | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [BalanceOf]>;
+      /**
+       * Slashes the worker stake, demands a leader origin. No limits, no actions on zero stake.
+       * If slashing balance greater than the existing stake - stake is slashed to zero.
+       * Require signed leader origin or the root (to slash the leader stake).
+       **/
+      slashStake: AugmentedSubmittable<(workerId: WorkerId | AnyNumber | Uint8Array, balance: BalanceOf | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [WorkerId, BalanceOf]>;
+      /**
+       * Terminate the worker application. Can be done by the lead only.
+       **/
+      terminateApplication: AugmentedSubmittable<(applicationId: ApplicationId | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [ApplicationId]>;
+      /**
+       * Terminate the active worker by the lead.
+       * Require signed leader origin or the root (to terminate the leader role).
+       **/
+      terminateRole: AugmentedSubmittable<(workerId: WorkerId | AnyNumber | Uint8Array, rationaleText: Bytes | string | Uint8Array, slashStake: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [WorkerId, Bytes, bool]>;
+      /**
+       * Update the reward account associated with a set reward relationship for the active worker.
+       **/
+      updateRewardAccount: AugmentedSubmittable<(workerId: WorkerId | AnyNumber | Uint8Array, newRewardAccountId: AccountId | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [WorkerId, AccountId]>;
+      /**
+       * Update the reward amount associated with a set reward relationship for the active worker.
+       * Require signed leader origin or the root (to update leader reward amount).
+       **/
+      updateRewardAmount: AugmentedSubmittable<(workerId: WorkerId | AnyNumber | Uint8Array, newAmount: BalanceOfMint | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [WorkerId, BalanceOfMint]>;
+      /**
+       * Update the associated role account of the active worker/lead.
+       **/
+      updateRoleAccount: AugmentedSubmittable<(workerId: WorkerId | AnyNumber | Uint8Array, newRoleAccountId: AccountId | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [WorkerId, AccountId]>;
+      /**
+       * Withdraw the worker application. Can be done by the worker itself only.
+       **/
+      withdrawApplication: AugmentedSubmittable<(applicationId: ApplicationId | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [ApplicationId]>;
+    };
     finalityTracker: {
       /**
        * Hint that the author of this block thinks the best finalized
@@ -1161,6 +1238,10 @@ declare module '@polkadot/api/types/submittable' {
       withdrawUnbonded: AugmentedSubmittable<(numSlashingSpans: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32]>;
     };
     storage: {
+      /**
+       * Accept pending invite.
+       **/
+      acceptDistributionBucketInvitation: AugmentedSubmittable<(workerId: WorkerId | AnyNumber | Uint8Array, distributionBucketFamilyId: DistributionBucketFamilyId | AnyNumber | Uint8Array, distributionBucketId: DistributionBucketId | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [WorkerId, DistributionBucketFamilyId, DistributionBucketId]>;
       /**
        * A storage provider signals that the data object was successfully uploaded to its storage.
        **/
@@ -1169,18 +1250,42 @@ declare module '@polkadot/api/types/submittable' {
        * Accept the storage bucket invitation. An invitation must match the worker_id parameter.
        **/
       acceptStorageBucketInvitation: AugmentedSubmittable<(workerId: WorkerId | AnyNumber | Uint8Array, storageBucketId: StorageBucketId | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [WorkerId, StorageBucketId]>;
+      /**
+       * Cancel pending invite. Must be pending.
+       **/
+      cancelDistributionBucketOperatorInvite: AugmentedSubmittable<(distributionBucketFamilyId: DistributionBucketFamilyId | AnyNumber | Uint8Array, distributionBucketId: DistributionBucketId | AnyNumber | Uint8Array, operatorWorkerId: WorkerId | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [DistributionBucketFamilyId, DistributionBucketId, WorkerId]>;
       /**
        * Cancel pending storage bucket invite. An invitation must be pending.
        **/
       cancelStorageBucketOperatorInvite: AugmentedSubmittable<(storageBucketId: StorageBucketId | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [StorageBucketId]>;
+      /**
+       * Create a distribution bucket.
+       **/
+      createDistributionBucket: AugmentedSubmittable<(familyId: DistributionBucketFamilyId | AnyNumber | Uint8Array, acceptingNewBags: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [DistributionBucketFamilyId, bool]>;
+      /**
+       * Create a distribution bucket family.
+       **/
+      createDistributionBucketFamily: AugmentedSubmittable<() => SubmittableExtrinsic<ApiType>, []>;
       /**
        * Create storage bucket.
        **/
       createStorageBucket: AugmentedSubmittable<(inviteWorker: Option<WorkerId> | null | object | string | Uint8Array, acceptingNewBags: bool | boolean | Uint8Array, sizeLimit: u64 | AnyNumber | Uint8Array, objectsLimit: u64 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Option<WorkerId>, bool, u64, u64]>;
+      /**
+       * Delete distribution bucket. Must be empty.
+       **/
+      deleteDistributionBucket: AugmentedSubmittable<(familyId: DistributionBucketFamilyId | AnyNumber | Uint8Array, distributionBucketId: DistributionBucketId | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [DistributionBucketFamilyId, DistributionBucketId]>;
+      /**
+       * Deletes a distribution bucket family.
+       **/
+      deleteDistributionBucketFamily: AugmentedSubmittable<(familyId: DistributionBucketFamilyId | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [DistributionBucketFamilyId]>;
       /**
        * Delete storage bucket. Must be empty. Storage operator must be missing.
        **/
       deleteStorageBucket: AugmentedSubmittable<(storageBucketId: StorageBucketId | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [StorageBucketId]>;
+      /**
+       * Invite an operator. Must be missing.
+       **/
+      inviteDistributionBucketOperator: AugmentedSubmittable<(distributionBucketFamilyId: DistributionBucketFamilyId | AnyNumber | Uint8Array, distributionBucketId: DistributionBucketId | AnyNumber | Uint8Array, operatorWorkerId: WorkerId | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [DistributionBucketFamilyId, DistributionBucketId, WorkerId]>;
       /**
        * Invite storage bucket operator. Must be missing.
        **/
@@ -1189,6 +1294,10 @@ declare module '@polkadot/api/types/submittable' {
        * Removes storage bucket operator. Must be invited.
        **/
       removeStorageBucketOperator: AugmentedSubmittable<(storageBucketId: StorageBucketId | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [StorageBucketId]>;
+      /**
+       * Set distribution operator metadata for the distribution bucket.
+       **/
+      setDistributionOperatorMetadata: AugmentedSubmittable<(workerId: WorkerId | AnyNumber | Uint8Array, distributionBucketFamilyId: DistributionBucketFamilyId | AnyNumber | Uint8Array, distributionBucketId: DistributionBucketId | AnyNumber | Uint8Array, metadata: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [WorkerId, DistributionBucketFamilyId, DistributionBucketId, Bytes]>;
       /**
        * Sets storage bucket voucher limits.
        **/
@@ -1197,6 +1306,10 @@ declare module '@polkadot/api/types/submittable' {
        * Sets storage operator metadata (eg.: storage node URL).
        **/
       setStorageOperatorMetadata: AugmentedSubmittable<(workerId: WorkerId | AnyNumber | Uint8Array, storageBucketId: StorageBucketId | AnyNumber | Uint8Array, metadata: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [WorkerId, StorageBucketId, Bytes]>;
+      /**
+       * Create a dynamic bag. Development mode.
+       **/
+      sudoCreateDynamicBag: AugmentedSubmittable<(bagId: DynamicBagId | { Member: any } | { Channel: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [DynamicBagId]>;
       /**
        * Upload new data objects. Development mode.
        **/
@@ -1209,12 +1322,32 @@ declare module '@polkadot/api/types/submittable' {
        * Updates size-based pricing of new objects uploaded.
        **/
       updateDataSizeFee: AugmentedSubmittable<(newDataSizeFee: BalanceOf | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [BalanceOf]>;
+      /**
+       * Updates 'distributing' flag for the distributing flag.
+       **/
+      updateDistributionBucketMode: AugmentedSubmittable<(familyId: DistributionBucketFamilyId | AnyNumber | Uint8Array, distributionBucketId: DistributionBucketId | AnyNumber | Uint8Array, distributing: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [DistributionBucketFamilyId, DistributionBucketId, bool]>;
+      /**
+       * Updates a distribution bucket 'accepts new bags' flag.
+       **/
+      updateDistributionBucketStatus: AugmentedSubmittable<(familyId: DistributionBucketFamilyId | AnyNumber | Uint8Array, distributionBucketId: DistributionBucketId | AnyNumber | Uint8Array, acceptingNewBags: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [DistributionBucketFamilyId, DistributionBucketId, bool]>;
+      /**
+       * Updates distribution buckets for a bag.
+       **/
+      updateDistributionBucketsForBag: AugmentedSubmittable<(bagId: BagId | { Static: any } | { Dynamic: any } | string | Uint8Array, familyId: DistributionBucketFamilyId | AnyNumber | Uint8Array, addBuckets: BTreeSet<DistributionBucketId>, removeBuckets: BTreeSet<DistributionBucketId>) => SubmittableExtrinsic<ApiType>, [BagId, DistributionBucketFamilyId, BTreeSet<DistributionBucketId>, BTreeSet<DistributionBucketId>]>;
+      /**
+       * Updates "Distribution buckets per bag" number limit.
+       **/
+      updateDistributionBucketsPerBagLimit: AugmentedSubmittable<(newLimit: u64 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u64]>;
+      /**
+       * Update number of distributed buckets used in given dynamic bag creation policy.
+       **/
+      updateFamiliesInDynamicBagCreationPolicy: AugmentedSubmittable<(dynamicBagType: DynamicBagType | 'Member' | 'Channel' | number | Uint8Array, families: BTreeMap<DistributionBucketFamilyId, u32>) => SubmittableExtrinsic<ApiType>, [DynamicBagType, BTreeMap<DistributionBucketFamilyId, u32>]>;
       /**
        * Update number of storage buckets used in given dynamic bag creation policy.
        **/
       updateNumberOfStorageBucketsInDynamicBagCreationPolicy: AugmentedSubmittable<(dynamicBagType: DynamicBagType | 'Member' | 'Channel' | number | Uint8Array, numberOfStorageBuckets: u64 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [DynamicBagType, u64]>;
       /**
-       * Update whether new bags are being accepted for storage.
+       * Updates a storage bucket 'accepts new bags' flag.
        **/
       updateStorageBucketStatus: AugmentedSubmittable<(workerId: WorkerId | AnyNumber | Uint8Array, storageBucketId: StorageBucketId | AnyNumber | Uint8Array, acceptingNewBags: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [WorkerId, StorageBucketId, bool]>;
       /**
@@ -1230,7 +1363,7 @@ declare module '@polkadot/api/types/submittable' {
        **/
       updateStorageBucketsVoucherMaxLimits: AugmentedSubmittable<(newObjectsSize: u64 | AnyNumber | Uint8Array, newObjectsNumber: u64 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u64, u64]>;
       /**
-       * Update whether uploading is globally blocked.
+       * Updates global uploading flag.
        **/
       updateUploadingBlockedStatus: AugmentedSubmittable<(newStatus: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [bool]>;
     };

File diff suppressed because it is too large
+ 0 - 0
types/augment-codec/augment-types.ts


+ 52 - 35
types/augment/all/defs.json

@@ -552,34 +552,6 @@
         "identity": "IPNSIdentity",
         "expires_at": "u32"
     },
-    "LiaisonJudgement": {
-        "_enum": [
-            "Pending",
-            "Accepted",
-            "Rejected"
-        ]
-    },
-    "DataObject": {
-        "owner": "MemberId",
-        "added_at": "BlockAndTime",
-        "type_id": "DataObjectTypeId",
-        "size": "u64",
-        "liaison": "StorageProviderId",
-        "liaison_judgement": "LiaisonJudgement",
-        "ipfs_content_id": "Text"
-    },
-    "DataObjectStorageRelationshipId": "u64",
-    "DataObjectStorageRelationship": {
-        "content_id": "Hash",
-        "storage_provider": "StorageProviderId",
-        "ready": "bool"
-    },
-    "DataObjectTypeId": "u64",
-    "DataObjectType": {
-        "description": "Text",
-        "active": "bool"
-    },
-    "DataObjectsMap": "BTreeMap<[u8;32],DataObject>",
     "ProposalId": "u32",
     "ProposalStatus": {
         "_enum": {
@@ -1002,11 +974,26 @@
         ]
     },
     "DynamicBagCreationPolicy": {
-        "numberOfStorageBuckets": "u64"
+        "numberOfStorageBuckets": "u64",
+        "families": "BTreeMap<DistributionBucketFamilyId,u32>"
+    },
+    "DynamicBag": {
+        "objects": "DataObjectIdMap",
+        "stored_by": "StorageBucketIdSet",
+        "distributed_by": "Vec<DistributionBucketId>",
+        "deletion_prize": "u128"
+    },
+    "StaticBag": {
+        "objects": "DataObjectIdMap",
+        "stored_by": "StorageBucketIdSet",
+        "distributed_by": "Vec<DistributionBucketId>"
+    },
+    "StorageBucket": {
+        "operator_status": "StorageBucketOperatorStatus",
+        "accepting_new_bags": "bool",
+        "voucher": "Voucher",
+        "metadata": "Text"
     },
-    "DynamicBag": "u64",
-    "StaticBag": "u64",
-    "StorageBucket": "u64",
     "StaticBagId": {
         "_enum": {
             "Council": "Null",
@@ -1019,10 +1006,16 @@
             "WorkingGroup": "WorkingGroup"
         }
     },
+    "Dynamic": {
+        "_enum": {
+            "Member": "MemberId",
+            "Channel": "ChannelId"
+        }
+    },
     "BagId": {
         "_enum": {
             "Static": "Static",
-            "Dynamic": "DynamicBagIdType"
+            "Dynamic": "Dynamic"
         }
     },
     "DataObjectCreationParameters": {
@@ -1032,7 +1025,7 @@
     "BagIdType": {
         "_enum": {
             "Static": "Static",
-            "Dynamic": "DynamicBagIdType"
+            "Dynamic": "Dynamic"
         }
     },
     "UploadParameters": {
@@ -1044,5 +1037,29 @@
     "StorageBucketIdSet": "BTreeSet<StorageBucketId>",
     "DataObjectIdSet": "BTreeSet<DataObjectId>",
     "ContentIdSet": "BTreeSet<ContentId>",
-    "ContentId": "Text"
+    "ContentId": "Text",
+    "StorageBucketOperatorStatus": {
+        "_enum": {
+            "Missing": "Null",
+            "InvitedStorageWorker": "u64",
+            "StorageWorker": "u64"
+        }
+    },
+    "DistributionBucket": {
+        "acceptingNewBags": "bool",
+        "distributing": "bool",
+        "pendingInvitations": "Vec<WorkerId>",
+        "operators": "Vec<WorkerId>"
+    },
+    "DistributionBucketId": "u64",
+    "DistributionBucketFamily": {
+        "distributionBuckets": "BTreeMap<DistributionBucketId,DistributionBucket>"
+    },
+    "DistributionBucketFamilyId": "u64",
+    "DataObject": {
+        "accepted": "bool",
+        "deletion_prize": "u128",
+        "size": "u64"
+    },
+    "DataObjectIdMap": "BTreeMap<DataObjectId,DataObject>"
 }

+ 62 - 41
types/augment/all/types.ts

@@ -1,7 +1,7 @@
 // Auto-generated via `yarn polkadot-types-from-defs`, do not edit
 /* eslint-disable */
 
-import type { BTreeMap, BTreeSet, Bytes, Enum, GenericAccountId, Null, Option, Struct, Text, U8aFixed, Vec, bool, i16, i32, i64, u128, u16, u32, u64 } from '@polkadot/types';
+import type { BTreeMap, BTreeSet, Bytes, Enum, GenericAccountId, Null, Option, Struct, Text, Vec, bool, i16, i32, i64, u128, u16, u32, u64 } from '@polkadot/types';
 import type { ITuple } from '@polkadot/types/types';
 import type { AccountId, Balance, Hash } from '@polkadot/types/interfaces/runtime';
 
@@ -163,7 +163,7 @@ export interface BagId extends Enum {
   readonly isStatic: boolean;
   readonly asStatic: Static;
   readonly isDynamic: boolean;
-  readonly asDynamic: DynamicBagIdType;
+  readonly asDynamic: Dynamic;
 }
 
 /** @name BagIdType */
@@ -171,7 +171,7 @@ export interface BagIdType extends Enum {
   readonly isStatic: boolean;
   readonly asStatic: Static;
   readonly isDynamic: boolean;
-  readonly asDynamic: DynamicBagIdType;
+  readonly asDynamic: Dynamic;
 }
 
 /** @name BalanceOfMint */
@@ -399,12 +399,8 @@ export interface CuratorRoleStakeProfile extends Struct {
 
 /** @name DataObject */
 export interface DataObject extends Struct {
-  readonly owner: MemberId;
-  readonly added_at: BlockAndTime;
-  readonly type_id: DataObjectTypeId;
-  readonly liaison: StorageProviderId;
-  readonly liaison_judgement: LiaisonJudgement;
-  readonly ipfs_content_id: Text;
+  readonly accepted: bool;
+  readonly deletion_prize: u128;
 }
 
 /** @name DataObjectCreationParameters */
@@ -415,31 +411,12 @@ export interface DataObjectCreationParameters extends Struct {
 /** @name DataObjectId */
 export interface DataObjectId extends u64 {}
 
+/** @name DataObjectIdMap */
+export interface DataObjectIdMap extends BTreeMap<DataObjectId, DataObject> {}
+
 /** @name DataObjectIdSet */
 export interface DataObjectIdSet extends BTreeSet<DataObjectId> {}
 
-/** @name DataObjectsMap */
-export interface DataObjectsMap extends BTreeMap<U8aFixed, DataObject> {}
-
-/** @name DataObjectStorageRelationship */
-export interface DataObjectStorageRelationship extends Struct {
-  readonly content_id: Hash;
-  readonly storage_provider: StorageProviderId;
-  readonly ready: bool;
-}
-
-/** @name DataObjectStorageRelationshipId */
-export interface DataObjectStorageRelationshipId extends u64 {}
-
-/** @name DataObjectType */
-export interface DataObjectType extends Struct {
-  readonly description: Text;
-  readonly active: bool;
-}
-
-/** @name DataObjectTypeId */
-export interface DataObjectTypeId extends u64 {}
-
 /** @name Deactivated */
 export interface Deactivated extends Struct {
   readonly cause: OpeningDeactivationCause;
@@ -465,12 +442,45 @@ export interface DiscussionThread extends Struct {
   readonly author_id: MemberId;
 }
 
+/** @name DistributionBucket */
+export interface DistributionBucket extends Struct {
+  readonly acceptingNewBags: bool;
+  readonly distributing: bool;
+  readonly pendingInvitations: Vec<WorkerId>;
+  readonly operators: Vec<WorkerId>;
+}
+
+/** @name DistributionBucketFamily */
+export interface DistributionBucketFamily extends Struct {
+  readonly distributionBuckets: BTreeMap<DistributionBucketId, DistributionBucket>;
+}
+
+/** @name DistributionBucketFamilyId */
+export interface DistributionBucketFamilyId extends u64 {}
+
+/** @name DistributionBucketId */
+export interface DistributionBucketId extends u64 {}
+
+/** @name Dynamic */
+export interface Dynamic extends Enum {
+  readonly isMember: boolean;
+  readonly asMember: MemberId;
+  readonly isChannel: boolean;
+  readonly asChannel: ChannelId;
+}
+
 /** @name DynamicBag */
-export interface DynamicBag extends u64 {}
+export interface DynamicBag extends Struct {
+  readonly objects: DataObjectIdMap;
+  readonly stored_by: StorageBucketIdSet;
+  readonly distributed_by: Vec<DistributionBucketId>;
+  readonly deletion_prize: u128;
+}
 
 /** @name DynamicBagCreationPolicy */
 export interface DynamicBagCreationPolicy extends Struct {
   readonly numberOfStorageBuckets: u64;
+  readonly families: BTreeMap<DistributionBucketFamilyId, u32>;
 }
 
 /** @name DynamicBagId */
@@ -689,13 +699,6 @@ export interface LeadRoleState extends Enum {
   readonly asExited: ExitedLeadRole;
 }
 
-/** @name LiaisonJudgement */
-export interface LiaisonJudgement extends Enum {
-  readonly isPending: boolean;
-  readonly isAccepted: boolean;
-  readonly isRejected: boolean;
-}
-
 /** @name LookupSource */
 export interface LookupSource extends AccountId {}
 
@@ -1259,7 +1262,11 @@ export interface Static extends Enum {
 }
 
 /** @name StaticBag */
-export interface StaticBag extends u64 {}
+export interface StaticBag extends Struct {
+  readonly objects: DataObjectIdMap;
+  readonly stored_by: StorageBucketIdSet;
+  readonly distributed_by: Vec<DistributionBucketId>;
+}
 
 /** @name StaticBagId */
 export interface StaticBagId extends Enum {
@@ -1272,7 +1279,12 @@ export interface StaticBagId extends Enum {
 export interface Status extends bool {}
 
 /** @name StorageBucket */
-export interface StorageBucket extends u64 {}
+export interface StorageBucket extends Struct {
+  readonly operator_status: StorageBucketOperatorStatus;
+  readonly accepting_new_bags: bool;
+  readonly voucher: Voucher;
+  readonly metadata: Text;
+}
 
 /** @name StorageBucketId */
 export interface StorageBucketId extends u64 {}
@@ -1280,6 +1292,15 @@ export interface StorageBucketId extends u64 {}
 /** @name StorageBucketIdSet */
 export interface StorageBucketIdSet extends BTreeSet<StorageBucketId> {}
 
+/** @name StorageBucketOperatorStatus */
+export interface StorageBucketOperatorStatus extends Enum {
+  readonly isMissing: boolean;
+  readonly isInvitedStorageWorker: boolean;
+  readonly asInvitedStorageWorker: u64;
+  readonly isStorageWorker: boolean;
+  readonly asStorageWorker: u64;
+}
+
 /** @name StorageBucketsPerBagValueConstraint */
 export interface StorageBucketsPerBagValueConstraint extends Struct {
   readonly min: u64;

+ 29 - 5
types/augment/augment-api-consts.ts

@@ -2,7 +2,7 @@
 /* eslint-disable */
 
 import type { Vec, u32, u64 } from '@polkadot/types';
-import type { DynamicBagCreationPolicy, StorageBucketsPerBagValueConstraint } from './all';
+import type { StorageBucketsPerBagValueConstraint } from './all';
 import type { Balance, BalanceOf, BlockNumber, Moment, Perbill, RuntimeDbWeight, Weight } from '@polkadot/types/interfaces/runtime';
 import type { SessionIndex } from '@polkadot/types/interfaces/session';
 import type { EraIndex } from '@polkadot/types/interfaces/staking';
@@ -38,6 +38,12 @@ declare module '@polkadot/api/types/consts' {
        **/
       maxWorkerNumberLimit: u32 & AugmentedConst<ApiType>;
     };
+    distributionWorkingGroup: {
+      /**
+       * Exports const -  max simultaneous active worker number.
+       **/
+      maxWorkerNumberLimit: u32 & AugmentedConst<ApiType>;
+    };
     finalityTracker: {
       /**
        * The delay after which point things become suspicious. Default is 1000.
@@ -153,17 +159,35 @@ declare module '@polkadot/api/types/consts' {
        **/
       dataObjectDeletionPrize: BalanceOf & AugmentedConst<ApiType>;
       /**
-       * Exports const - the default dynamic bag creation policy for channels.
+       * Exports const - the default dynamic bag creation policy for channels (storage bucket
+       * number).
+       **/
+      defaultChannelDynamicBagNumberOfStorageBuckets: u64 & AugmentedConst<ApiType>;
+      /**
+       * Exports const - the default dynamic bag creation policy for members (storage bucket
+       * number).
        **/
-      defaultChannelDynamicBagCreationPolicy: DynamicBagCreationPolicy & AugmentedConst<ApiType>;
+      defaultMemberDynamicBagNumberOfStorageBuckets: u64 & AugmentedConst<ApiType>;
       /**
-       * Exports const - the default dynamic bag creation policy for members.
+       * Exports const - "Distribution buckets per bag" value constraint.
        **/
-      defaultMemberDynamicBagCreationPolicy: DynamicBagCreationPolicy & AugmentedConst<ApiType>;
+      distributionBucketsPerBagValueConstraint: StorageBucketsPerBagValueConstraint & AugmentedConst<ApiType>;
+      /**
+       * Exports const - max allowed distribution bucket family number.
+       **/
+      maxDistributionBucketFamilyNumber: u64 & AugmentedConst<ApiType>;
+      /**
+       * Exports const - max allowed distribution bucket number per family.
+       **/
+      maxDistributionBucketNumberPerFamily: u64 & AugmentedConst<ApiType>;
       /**
        * Exports const - max number of data objects per bag.
        **/
       maxNumberOfDataObjectsPerBag: u64 & AugmentedConst<ApiType>;
+      /**
+       * Exports const - max number of pending invitations per distribution bucket.
+       **/
+      maxNumberOfPendingInvitationsPerDistributionBucket: u64 & AugmentedConst<ApiType>;
       /**
        * Exports const - max allowed storage bucket number.
        **/

+ 466 - 0
types/augment/augment-api-errors.ts

@@ -763,6 +763,400 @@ declare module '@polkadot/api/types/errors' {
        **/
       WorkerHasNoReward: AugmentedError<ApiType>;
     };
+    distributionWorkingGroup: {
+      /**
+       * Opening does not exist.
+       **/
+      AcceptWorkerApplicationsOpeningDoesNotExist: AugmentedError<ApiType>;
+      /**
+       * Opening Is Not in Waiting to begin.
+       **/
+      AcceptWorkerApplicationsOpeningIsNotWaitingToBegin: AugmentedError<ApiType>;
+      /**
+       * Opening does not activate in the future.
+       **/
+      AddWorkerOpeningActivatesInThePast: AugmentedError<ApiType>;
+      /**
+       * Add worker opening application stake cannot be zero.
+       **/
+      AddWorkerOpeningApplicationStakeCannotBeZero: AugmentedError<ApiType>;
+      /**
+       * Application stake amount less than minimum currency balance.
+       **/
+      AddWorkerOpeningAppliicationStakeLessThanMinimum: AugmentedError<ApiType>;
+      /**
+       * New application was crowded out.
+       **/
+      AddWorkerOpeningNewApplicationWasCrowdedOut: AugmentedError<ApiType>;
+      /**
+       * Opening does not exist.
+       **/
+      AddWorkerOpeningOpeningDoesNotExist: AugmentedError<ApiType>;
+      /**
+       * Opening is not in accepting applications stage.
+       **/
+      AddWorkerOpeningOpeningNotInAcceptingApplicationStage: AugmentedError<ApiType>;
+      /**
+       * Add worker opening role stake cannot be zero.
+       **/
+      AddWorkerOpeningRoleStakeCannotBeZero: AugmentedError<ApiType>;
+      /**
+       * Role stake amount less than minimum currency balance.
+       **/
+      AddWorkerOpeningRoleStakeLessThanMinimum: AugmentedError<ApiType>;
+      /**
+       * Stake amount too low.
+       **/
+      AddWorkerOpeningStakeAmountTooLow: AugmentedError<ApiType>;
+      /**
+       * Stake missing when required.
+       **/
+      AddWorkerOpeningStakeMissingWhenRequired: AugmentedError<ApiType>;
+      /**
+       * Stake provided when redundant.
+       **/
+      AddWorkerOpeningStakeProvidedWhenRedundant: AugmentedError<ApiType>;
+      /**
+       * Application rationing has zero max active applicants.
+       **/
+      AddWorkerOpeningZeroMaxApplicantCount: AugmentedError<ApiType>;
+      /**
+       * Invalid OpeningPolicyCommitment parameter (application_rationing_policy):
+       * max_active_applicants should be non-zero.
+       **/
+      ApplicationRationingPolicyMaxActiveApplicantsIsZero: AugmentedError<ApiType>;
+      /**
+       * Invalid OpeningPolicyCommitment parameter (application_staking_policy):
+       * crowded_out_unstaking_period_length should be non-zero.
+       **/
+      ApplicationStakingPolicyCrowdedOutUnstakingPeriodIsZero: AugmentedError<ApiType>;
+      /**
+       * Invalid OpeningPolicyCommitment parameter (application_staking_policy):
+       * review_period_expired_unstaking_period_length should be non-zero.
+       **/
+      ApplicationStakingPolicyReviewPeriodUnstakingPeriodIsZero: AugmentedError<ApiType>;
+      /**
+       * Signer does not match controller account.
+       **/
+      ApplyOnWorkerOpeningSignerNotControllerAccount: AugmentedError<ApiType>;
+      /**
+       * Opening does not exist.
+       **/
+      BeginWorkerApplicantReviewOpeningDoesNotExist: AugmentedError<ApiType>;
+      /**
+       * Opening Is Not in Waiting.
+       **/
+      BeginWorkerApplicantReviewOpeningOpeningIsNotWaitingToBegin: AugmentedError<ApiType>;
+      /**
+       * Cannot find mint in the minting module.
+       **/
+      CannotFindMint: AugmentedError<ApiType>;
+      /**
+       * There is leader already, cannot hire another one.
+       **/
+      CannotHireLeaderWhenLeaderExists: AugmentedError<ApiType>;
+      /**
+       * Cannot fill opening with multiple applications.
+       **/
+      CannotHireMultipleLeaders: AugmentedError<ApiType>;
+      /**
+       * Current lead is not set.
+       **/
+      CurrentLeadNotSet: AugmentedError<ApiType>;
+      /**
+       * Invalid OpeningPolicyCommitment parameter:
+       * exit_role_application_stake_unstaking_period should be non-zero.
+       **/
+      ExitRoleApplicationStakeUnstakingPeriodIsZero: AugmentedError<ApiType>;
+      /**
+       * Invalid OpeningPolicyCommitment parameter:
+       * exit_role_stake_unstaking_period should be non-zero.
+       **/
+      ExitRoleStakeUnstakingPeriodIsZero: AugmentedError<ApiType>;
+      /**
+       * Invalid OpeningPolicyCommitment parameter:
+       * fill_opening_failed_applicant_application_stake_unstaking_period should be non-zero.
+       **/
+      FillOpeningFailedApplicantApplicationStakeUnstakingPeriodIsZero: AugmentedError<ApiType>;
+      /**
+       * Invalid OpeningPolicyCommitment parameter:
+       * fill_opening_failed_applicant_role_stake_unstaking_period should be non-zero.
+       **/
+      FillOpeningFailedApplicantRoleStakeUnstakingPeriodIsZero: AugmentedError<ApiType>;
+      /**
+       * Reward policy has invalid next payment block number.
+       **/
+      FillOpeningInvalidNextPaymentBlock: AugmentedError<ApiType>;
+      /**
+       * Working group mint does not exist.
+       **/
+      FillOpeningMintDoesNotExist: AugmentedError<ApiType>;
+      /**
+       * Invalid OpeningPolicyCommitment parameter:
+       * fill_opening_successful_applicant_application_stake_unstaking_period should be non-zero.
+       **/
+      FillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriodIsZero: AugmentedError<ApiType>;
+      /**
+       * Applications not for opening.
+       **/
+      FillWorkerOpeningApplicationForWrongOpening: AugmentedError<ApiType>;
+      /**
+       * Application does not exist.
+       **/
+      FullWorkerOpeningApplicationDoesNotExist: AugmentedError<ApiType>;
+      /**
+       * Application not in active stage.
+       **/
+      FullWorkerOpeningApplicationNotActive: AugmentedError<ApiType>;
+      /**
+       * OpeningDoesNotExist.
+       **/
+      FullWorkerOpeningOpeningDoesNotExist: AugmentedError<ApiType>;
+      /**
+       * Opening not in review period stage.
+       **/
+      FullWorkerOpeningOpeningNotInReviewPeriodStage: AugmentedError<ApiType>;
+      /**
+       * Application stake unstaking period for successful applicants redundant.
+       **/
+      FullWorkerOpeningSuccessfulApplicationStakeUnstakingPeriodRedundant: AugmentedError<ApiType>;
+      /**
+       * Application stake unstaking period for failed applicants too short.
+       **/
+      FullWorkerOpeningSuccessfulApplicationStakeUnstakingPeriodTooShort: AugmentedError<ApiType>;
+      /**
+       * Role stake unstaking period for successful applicants redundant.
+       **/
+      FullWorkerOpeningSuccessfulRoleStakeUnstakingPeriodRedundant: AugmentedError<ApiType>;
+      /**
+       * Role stake unstaking period for successful applicants too short.
+       **/
+      FullWorkerOpeningSuccessfulRoleStakeUnstakingPeriodTooShort: AugmentedError<ApiType>;
+      /**
+       * Application stake unstaking period for failed applicants redundant.
+       **/
+      FullWorkerOpeningUnsuccessfulApplicationStakeUnstakingPeriodRedundant: AugmentedError<ApiType>;
+      /**
+       * Application stake unstaking period for successful applicants too short.
+       **/
+      FullWorkerOpeningUnsuccessfulApplicationStakeUnstakingPeriodTooShort: AugmentedError<ApiType>;
+      /**
+       * Role stake unstaking period for failed applicants redundant.
+       **/
+      FullWorkerOpeningUnsuccessfulRoleStakeUnstakingPeriodRedundant: AugmentedError<ApiType>;
+      /**
+       * Role stake unstaking period for failed applicants too short.
+       **/
+      FullWorkerOpeningUnsuccessfulRoleStakeUnstakingPeriodTooShort: AugmentedError<ApiType>;
+      /**
+       * Insufficient balance to apply.
+       **/
+      InsufficientBalanceToApply: AugmentedError<ApiType>;
+      /**
+       * Insufficient balance to cover stake.
+       **/
+      InsufficientBalanceToCoverStake: AugmentedError<ApiType>;
+      /**
+       * Not a lead account.
+       **/
+      IsNotLeadAccount: AugmentedError<ApiType>;
+      /**
+       * Working group size limit exceeded.
+       **/
+      MaxActiveWorkerNumberExceeded: AugmentedError<ApiType>;
+      /**
+       * Member already has an active application on the opening.
+       **/
+      MemberHasActiveApplicationOnOpening: AugmentedError<ApiType>;
+      /**
+       * Member id is invalid.
+       **/
+      MembershipInvalidMemberId: AugmentedError<ApiType>;
+      /**
+       * Unsigned origin.
+       **/
+      MembershipUnsignedOrigin: AugmentedError<ApiType>;
+      /**
+       * Minting error: NextAdjustmentInPast
+       **/
+      MintingErrorNextAdjustmentInPast: AugmentedError<ApiType>;
+      /**
+       * Cannot get the worker stake profile.
+       **/
+      NoWorkerStakeProfile: AugmentedError<ApiType>;
+      /**
+       * Opening does not exist.
+       **/
+      OpeningDoesNotExist: AugmentedError<ApiType>;
+      /**
+       * Opening text too long.
+       **/
+      OpeningTextTooLong: AugmentedError<ApiType>;
+      /**
+       * Opening text too short.
+       **/
+      OpeningTextTooShort: AugmentedError<ApiType>;
+      /**
+       * Origin must be controller or root account of member.
+       **/
+      OriginIsNeitherMemberControllerOrRoot: AugmentedError<ApiType>;
+      /**
+       * Origin is not applicant.
+       **/
+      OriginIsNotApplicant: AugmentedError<ApiType>;
+      /**
+       * Next payment is not in the future.
+       **/
+      RecurringRewardsNextPaymentNotInFuture: AugmentedError<ApiType>;
+      /**
+       * Recipient not found.
+       **/
+      RecurringRewardsRecipientNotFound: AugmentedError<ApiType>;
+      /**
+       * Reward relationship not found.
+       **/
+      RecurringRewardsRewardRelationshipNotFound: AugmentedError<ApiType>;
+      /**
+       * Recipient reward source not found.
+       **/
+      RecurringRewardsRewardSourceNotFound: AugmentedError<ApiType>;
+      /**
+       * Relationship must exist.
+       **/
+      RelationshipMustExist: AugmentedError<ApiType>;
+      /**
+       * Require root origin in extrinsics.
+       **/
+      RequireRootOrigin: AugmentedError<ApiType>;
+      /**
+       * Require signed origin in extrinsics.
+       **/
+      RequireSignedOrigin: AugmentedError<ApiType>;
+      /**
+       * Invalid OpeningPolicyCommitment parameter (role_staking_policy):
+       * crowded_out_unstaking_period_length should be non-zero.
+       **/
+      RoleStakingPolicyCrowdedOutUnstakingPeriodIsZero: AugmentedError<ApiType>;
+      /**
+       * Invalid OpeningPolicyCommitment parameter (role_staking_policy):
+       * review_period_expired_unstaking_period_length should be non-zero.
+       **/
+      RoleStakingPolicyReviewPeriodUnstakingPeriodIsZero: AugmentedError<ApiType>;
+      /**
+       * Signer is not worker role account.
+       **/
+      SignerIsNotWorkerRoleAccount: AugmentedError<ApiType>;
+      /**
+       * Provided stake balance cannot be zero.
+       **/
+      StakeBalanceCannotBeZero: AugmentedError<ApiType>;
+      /**
+       * Already unstaking.
+       **/
+      StakingErrorAlreadyUnstaking: AugmentedError<ApiType>;
+      /**
+       * Cannot change stake by zero.
+       **/
+      StakingErrorCannotChangeStakeByZero: AugmentedError<ApiType>;
+      /**
+       * Cannot decrease stake while slashes ongoing.
+       **/
+      StakingErrorCannotDecreaseWhileSlashesOngoing: AugmentedError<ApiType>;
+      /**
+       * Cannot increase stake while unstaking.
+       **/
+      StakingErrorCannotIncreaseStakeWhileUnstaking: AugmentedError<ApiType>;
+      /**
+       * Cannot unstake while slashes ongoing.
+       **/
+      StakingErrorCannotUnstakeWhileSlashesOngoing: AugmentedError<ApiType>;
+      /**
+       * Insufficient balance in source account.
+       **/
+      StakingErrorInsufficientBalanceInSourceAccount: AugmentedError<ApiType>;
+      /**
+       * Insufficient stake to decrease.
+       **/
+      StakingErrorInsufficientStake: AugmentedError<ApiType>;
+      /**
+       * Not staked.
+       **/
+      StakingErrorNotStaked: AugmentedError<ApiType>;
+      /**
+       * Slash amount should be greater than zero.
+       **/
+      StakingErrorSlashAmountShouldBeGreaterThanZero: AugmentedError<ApiType>;
+      /**
+       * Stake not found.
+       **/
+      StakingErrorStakeNotFound: AugmentedError<ApiType>;
+      /**
+       * Unstaking period should be greater than zero.
+       **/
+      StakingErrorUnstakingPeriodShouldBeGreaterThanZero: AugmentedError<ApiType>;
+      /**
+       * Successful worker application does not exist.
+       **/
+      SuccessfulWorkerApplicationDoesNotExist: AugmentedError<ApiType>;
+      /**
+       * Invalid OpeningPolicyCommitment parameter:
+       * terminate_application_stake_unstaking_period should be non-zero.
+       **/
+      TerminateApplicationStakeUnstakingPeriodIsZero: AugmentedError<ApiType>;
+      /**
+       * Invalid OpeningPolicyCommitment parameter:
+       * terminate_role_stake_unstaking_period should be non-zero.
+       **/
+      TerminateRoleStakeUnstakingPeriodIsZero: AugmentedError<ApiType>;
+      /**
+       * Application does not exist.
+       **/
+      WithdrawWorkerApplicationApplicationDoesNotExist: AugmentedError<ApiType>;
+      /**
+       * Application is not active.
+       **/
+      WithdrawWorkerApplicationApplicationNotActive: AugmentedError<ApiType>;
+      /**
+       * Opening not accepting applications.
+       **/
+      WithdrawWorkerApplicationOpeningNotAcceptingApplications: AugmentedError<ApiType>;
+      /**
+       * Redundant unstaking period provided
+       **/
+      WithdrawWorkerApplicationRedundantUnstakingPeriod: AugmentedError<ApiType>;
+      /**
+       * UnstakingPeriodTooShort .... // <== SHOULD REALLY BE TWO SEPARATE, ONE FOR EACH STAKING PURPOSE
+       **/
+      WithdrawWorkerApplicationUnstakingPeriodTooShort: AugmentedError<ApiType>;
+      /**
+       * Worker application does not exist.
+       **/
+      WorkerApplicationDoesNotExist: AugmentedError<ApiType>;
+      /**
+       * Worker application text too long.
+       **/
+      WorkerApplicationTextTooLong: AugmentedError<ApiType>;
+      /**
+       * Worker application text too short.
+       **/
+      WorkerApplicationTextTooShort: AugmentedError<ApiType>;
+      /**
+       * Worker does not exist.
+       **/
+      WorkerDoesNotExist: AugmentedError<ApiType>;
+      /**
+       * Worker exit rationale text is too long.
+       **/
+      WorkerExitRationaleTextTooLong: AugmentedError<ApiType>;
+      /**
+       * Worker exit rationale text is too short.
+       **/
+      WorkerExitRationaleTextTooShort: AugmentedError<ApiType>;
+      /**
+       * Worker has no recurring reward.
+       **/
+      WorkerHasNoReward: AugmentedError<ApiType>;
+    };
     finalityTracker: {
       /**
        * Final hint must be updated only once in the block
@@ -1181,6 +1575,54 @@ declare module '@polkadot/api/types/errors' {
        * Invalid operation with invites: another storage provider was invited.
        **/
       DifferentStorageProviderInvited: AugmentedError<ApiType>;
+      /**
+       * Distribution bucket doesn't accept new bags.
+       **/
+      DistributionBucketDoesntAcceptNewBags: AugmentedError<ApiType>;
+      /**
+       * Distribution bucket doesn't exist.
+       **/
+      DistributionBucketDoesntExist: AugmentedError<ApiType>;
+      /**
+       * Distribution bucket family doesn't exist.
+       **/
+      DistributionBucketFamilyDoesntExist: AugmentedError<ApiType>;
+      /**
+       * Distribution bucket id collections are empty.
+       **/
+      DistributionBucketIdCollectionsAreEmpty: AugmentedError<ApiType>;
+      /**
+       * Distribution bucket is bound to a bag.
+       **/
+      DistributionBucketIsBoundToBag: AugmentedError<ApiType>;
+      /**
+       * Distribution bucket is not bound to a bag.
+       **/
+      DistributionBucketIsNotBoundToBag: AugmentedError<ApiType>;
+      /**
+       * The new `DistributionBucketsPerBagLimit` number is too high.
+       **/
+      DistributionBucketsPerBagLimitTooHigh: AugmentedError<ApiType>;
+      /**
+       * The new `DistributionBucketsPerBagLimit` number is too low.
+       **/
+      DistributionBucketsPerBagLimitTooLow: AugmentedError<ApiType>;
+      /**
+       * Distribution family bound to a bag creation policy.
+       **/
+      DistributionFamilyBoundToBagCreationPolicy: AugmentedError<ApiType>;
+      /**
+       * Distribution provider operator already invited.
+       **/
+      DistributionProviderOperatorAlreadyInvited: AugmentedError<ApiType>;
+      /**
+       * Distribution provider operator doesn't exist.
+       **/
+      DistributionProviderOperatorDoesntExist: AugmentedError<ApiType>;
+      /**
+       * Distribution provider operator already set.
+       **/
+      DistributionProviderOperatorSet: AugmentedError<ApiType>;
       /**
        * Dynamic bag doesn't exist.
        **/
@@ -1213,10 +1655,34 @@ declare module '@polkadot/api/types/errors' {
        * Invalid operation with invites: storage provider was already invited.
        **/
       InvitedStorageProvider: AugmentedError<ApiType>;
+      /**
+       * Max distribution bucket family number limit exceeded.
+       **/
+      MaxDistributionBucketFamilyNumberLimitExceeded: AugmentedError<ApiType>;
+      /**
+       * Max distribution bucket number per bag limit exceeded.
+       **/
+      MaxDistributionBucketNumberPerBagLimitExceeded: AugmentedError<ApiType>;
+      /**
+       * Max distribution bucket number per family limit exceeded.
+       **/
+      MaxDistributionBucketNumberPerFamilyLimitExceeded: AugmentedError<ApiType>;
+      /**
+       * Max number of pending invitations limit for a distribution bucket reached.
+       **/
+      MaxNumberOfPendingInvitationsLimitForDistributionBucketReached: AugmentedError<ApiType>;
       /**
        * Max storage bucket number limit exceeded.
        **/
       MaxStorageBucketNumberLimitExceeded: AugmentedError<ApiType>;
+      /**
+       * Invalid operations: must be a distribution provider operator for a bucket.
+       **/
+      MustBeDistributionProviderOperatorForBucket: AugmentedError<ApiType>;
+      /**
+       * No distribution bucket invitation.
+       **/
+      NoDistributionBucketInvitation: AugmentedError<ApiType>;
       /**
        * Empty "data object creation" collection.
        **/

+ 222 - 2
types/augment/augment-api-events.ts

@@ -1,8 +1,8 @@
 // Auto-generated via `yarn polkadot-types-from-chain`, do not edit
 /* eslint-disable */
 
-import type { BTreeSet, Bytes, Option, Vec, bool, u16, u32, u64 } from '@polkadot/types';
-import type { Actor, ApplicationId, ApplicationIdToWorkerIdMap, BagId, CategoryId, ChannelId, ClassId, ContentId, CuratorApplicationId, CuratorApplicationIdToCuratorIdMap, CuratorGroupId, CuratorId, CuratorOpeningId, DataObjectId, DynamicBagId, DynamicBagType, EntityController, EntityCreationVoucher, EntityId, FailedAt, LeadId, MemberId, MintBalanceOf, MintId, Nonce, OpeningId, PostId, PropertyId, ProposalId, ProposalStatus, RationaleText, SchemaId, SideEffect, SideEffects, Status, StorageBucketId, ThreadId, UploadParameters, VecMaxLength, VoteKind, Voucher, WorkerId } from './all';
+import type { BTreeMap, BTreeSet, Bytes, Option, Vec, bool, u16, u32, u64 } from '@polkadot/types';
+import type { Actor, ApplicationId, ApplicationIdToWorkerIdMap, BagId, CategoryId, ChannelId, ClassId, ContentId, CuratorApplicationId, CuratorApplicationIdToCuratorIdMap, CuratorGroupId, CuratorId, CuratorOpeningId, DataObjectId, DistributionBucketFamilyId, DistributionBucketId, DynamicBagId, DynamicBagType, EntityController, EntityCreationVoucher, EntityId, FailedAt, LeadId, MemberId, MintBalanceOf, MintId, Nonce, OpeningId, PostId, PropertyId, ProposalId, ProposalStatus, RationaleText, SchemaId, SideEffect, SideEffects, Status, StorageBucketId, ThreadId, UploadParameters, VecMaxLength, VoteKind, Voucher, WorkerId } from './all';
 import type { BalanceStatus } from '@polkadot/types/interfaces/balances';
 import type { AuthorityId } from '@polkadot/types/interfaces/consensus';
 import type { AuthorityList } from '@polkadot/types/interfaces/grandpa';
@@ -243,6 +243,129 @@ declare module '@polkadot/api/types/events' {
       VotingEnded: AugmentedEvent<ApiType, []>;
       VotingStarted: AugmentedEvent<ApiType, []>;
     };
+    distributionWorkingGroup: {
+      /**
+       * Emits on accepting application for the worker opening.
+       * Params:
+       * - Opening id
+       **/
+      AcceptedApplications: AugmentedEvent<ApiType, [OpeningId]>;
+      /**
+       * Emits on terminating the application for the worker/lead opening.
+       * Params:
+       * - Worker application id
+       **/
+      ApplicationTerminated: AugmentedEvent<ApiType, [ApplicationId]>;
+      /**
+       * Emits on withdrawing the application for the worker/lead opening.
+       * Params:
+       * - Worker application id
+       **/
+      ApplicationWithdrawn: AugmentedEvent<ApiType, [ApplicationId]>;
+      /**
+       * Emits on adding the application for the worker opening.
+       * Params:
+       * - Opening id
+       * - Application id
+       **/
+      AppliedOnOpening: AugmentedEvent<ApiType, [OpeningId, ApplicationId]>;
+      /**
+       * Emits on beginning the application review for the worker/lead opening.
+       * Params:
+       * - Opening id
+       **/
+      BeganApplicationReview: AugmentedEvent<ApiType, [OpeningId]>;
+      /**
+       * Emits on setting the leader.
+       * Params:
+       * - Worker id.
+       **/
+      LeaderSet: AugmentedEvent<ApiType, [WorkerId]>;
+      /**
+       * Emits on un-setting the leader.
+       * Params:
+       **/
+      LeaderUnset: AugmentedEvent<ApiType, []>;
+      /**
+       * Emits on changing working group mint capacity.
+       * Params:
+       * - mint id.
+       * - new mint balance.
+       **/
+      MintCapacityChanged: AugmentedEvent<ApiType, [MintId, MintBalanceOf]>;
+      /**
+       * Emits on adding new worker opening.
+       * Params:
+       * - Opening id
+       **/
+      OpeningAdded: AugmentedEvent<ApiType, [OpeningId]>;
+      /**
+       * Emits on filling the worker opening.
+       * Params:
+       * - Worker opening id
+       * - Worker application id to the worker id dictionary
+       **/
+      OpeningFilled: AugmentedEvent<ApiType, [OpeningId, ApplicationIdToWorkerIdMap]>;
+      /**
+       * Emits on decreasing the worker/lead stake.
+       * Params:
+       * - worker/lead id.
+       **/
+      StakeDecreased: AugmentedEvent<ApiType, [WorkerId]>;
+      /**
+       * Emits on increasing the worker/lead stake.
+       * Params:
+       * - worker/lead id.
+       **/
+      StakeIncreased: AugmentedEvent<ApiType, [WorkerId]>;
+      /**
+       * Emits on slashing the worker/lead stake.
+       * Params:
+       * - worker/lead id.
+       **/
+      StakeSlashed: AugmentedEvent<ApiType, [WorkerId]>;
+      /**
+       * Emits on terminating the leader.
+       * Params:
+       * - leader worker id.
+       * - termination rationale text
+       **/
+      TerminatedLeader: AugmentedEvent<ApiType, [WorkerId, RationaleText]>;
+      /**
+       * Emits on terminating the worker.
+       * Params:
+       * - worker id.
+       * - termination rationale text
+       **/
+      TerminatedWorker: AugmentedEvent<ApiType, [WorkerId, RationaleText]>;
+      /**
+       * Emits on exiting the worker.
+       * Params:
+       * - worker id.
+       * - exit rationale text
+       **/
+      WorkerExited: AugmentedEvent<ApiType, [WorkerId, RationaleText]>;
+      /**
+       * Emits on updating the reward account of the worker.
+       * Params:
+       * - Member id of the worker.
+       * - Reward account id of the worker.
+       **/
+      WorkerRewardAccountUpdated: AugmentedEvent<ApiType, [WorkerId, AccountId]>;
+      /**
+       * Emits on updating the reward amount of the worker.
+       * Params:
+       * - Id of the worker.
+       **/
+      WorkerRewardAmountUpdated: AugmentedEvent<ApiType, [WorkerId]>;
+      /**
+       * Emits on updating the role account of the worker.
+       * Params:
+       * - Id of the worker.
+       * - Role account id of the worker.
+       **/
+      WorkerRoleAccountUpdated: AugmentedEvent<ApiType, [WorkerId, AccountId]>;
+    };
     forum: {
       /**
        * A category was introduced
@@ -456,6 +579,96 @@ declare module '@polkadot/api/types/events' {
        * - new deletion prize
        **/
       DeletionPrizeChanged: AugmentedEvent<ApiType, [DynamicBagId, Balance]>;
+      /**
+       * Emits on creating distribution bucket.
+       * Params
+       * - distribution bucket family ID
+       * - accepting new bags
+       * - distribution bucket ID
+       **/
+      DistributionBucketCreated: AugmentedEvent<ApiType, [DistributionBucketFamilyId, bool, DistributionBucketId]>;
+      /**
+       * Emits on deleting distribution bucket.
+       * Params
+       * - distribution bucket family ID
+       * - distribution bucket ID
+       **/
+      DistributionBucketDeleted: AugmentedEvent<ApiType, [DistributionBucketFamilyId, DistributionBucketId]>;
+      /**
+       * Emits on creating distribution bucket family.
+       * Params
+       * - distribution family bucket ID
+       **/
+      DistributionBucketFamilyCreated: AugmentedEvent<ApiType, [DistributionBucketFamilyId]>;
+      /**
+       * Emits on deleting distribution bucket family.
+       * Params
+       * - distribution family bucket ID
+       **/
+      DistributionBucketFamilyDeleted: AugmentedEvent<ApiType, [DistributionBucketFamilyId]>;
+      /**
+       * Emits on accepting a distribution bucket invitation for the operator.
+       * Params
+       * - worker ID
+       * - distribution bucket family ID
+       * - distribution bucket ID
+       **/
+      DistributionBucketInvitationAccepted: AugmentedEvent<ApiType, [WorkerId, DistributionBucketFamilyId, DistributionBucketId]>;
+      /**
+       * Emits on canceling a distribution bucket invitation for the operator.
+       * Params
+       * - distribution bucket family ID
+       * - distribution bucket ID
+       * - operator worker ID
+       **/
+      DistributionBucketInvitationCancelled: AugmentedEvent<ApiType, [DistributionBucketFamilyId, DistributionBucketId, WorkerId]>;
+      /**
+       * Emits on setting the metadata by a distribution bucket operator.
+       * Params
+       * - worker ID
+       * - distribution bucket family ID
+       * - distribution bucket ID
+       * - metadata
+       **/
+      DistributionBucketMetadataSet: AugmentedEvent<ApiType, [WorkerId, DistributionBucketFamilyId, DistributionBucketId, Bytes]>;
+      /**
+       * Emits on storage bucket mode update (distributing flag).
+       * Params
+       * - distribution bucket family ID
+       * - distribution bucket ID
+       * - distributing
+       **/
+      DistributionBucketModeUpdated: AugmentedEvent<ApiType, [DistributionBucketFamilyId, DistributionBucketId, bool]>;
+      /**
+       * Emits on creating a distribution bucket invitation for the operator.
+       * Params
+       * - distribution bucket family ID
+       * - distribution bucket ID
+       * - worker ID
+       **/
+      DistributionBucketOperatorInvited: AugmentedEvent<ApiType, [DistributionBucketFamilyId, DistributionBucketId, WorkerId]>;
+      /**
+       * Emits on changing the "Distribution buckets per bag" number limit.
+       * Params
+       * - new limit
+       **/
+      DistributionBucketsPerBagLimitUpdated: AugmentedEvent<ApiType, [u64]>;
+      /**
+       * Emits on storage bucket status update (accepting new bags).
+       * Params
+       * - distribution bucket family ID
+       * - distribution bucket ID
+       * - new status (accepting new bags)
+       **/
+      DistributionBucketStatusUpdated: AugmentedEvent<ApiType, [DistributionBucketFamilyId, DistributionBucketId, bool]>;
+      /**
+       * Emits on updating distribution buckets for bag.
+       * Params
+       * - bag ID
+       * - storage buckets to add ID collection
+       * - storage buckets to remove ID collection
+       **/
+      DistributionBucketsUpdatedForBag: AugmentedEvent<ApiType, [BagId, DistributionBucketFamilyId, BTreeSet<DistributionBucketId>, BTreeSet<DistributionBucketId>]>;
       /**
        * Emits on creating a dynamic bag.
        * Params
@@ -469,6 +682,13 @@ declare module '@polkadot/api/types/events' {
        * - dynamic bag ID
        **/
       DynamicBagDeleted: AugmentedEvent<ApiType, [AccountId, DynamicBagId]>;
+      /**
+       * Emits on dynamic bag creation policy update (distribution bucket families).
+       * Params
+       * - dynamic bag type
+       * - families and bucket numbers
+       **/
+      FamiliesInDynamicBagCreationPolicyUpdated: AugmentedEvent<ApiType, [DynamicBagType, BTreeMap<DistributionBucketFamilyId, u32>]>;
       /**
        * Emits on updating the number of storage buckets in dynamic bag creation policy.
        * Params

+ 76 - 1
types/augment/augment-api-query.ts

@@ -3,7 +3,7 @@
 
 import type { Bytes, Option, Vec, bool, u32, u64 } from '@polkadot/types';
 import type { AnyNumber, ITuple, Observable } from '@polkadot/types/types';
-import type { Application, ApplicationId, ApplicationOf, Category, CategoryId, Channel, ChannelId, Class, ClassId, ClassOf, ClassPermissionsType, ContentId, Credential, Curator, CuratorApplication, CuratorApplicationId, CuratorGroup, CuratorGroupId, CuratorId, CuratorOpening, CuratorOpeningId, DataObjectId, DiscussionPost, DiscussionThread, DynamicBag, DynamicBagCreationPolicy, DynamicBagId, DynamicBagType, ElectionStage, ElectionStake, Entity, EntityController, EntityCreationVoucher, EntityId, EntityOf, HiringApplicationId, InputValidationLengthConstraint, Lead, LeadId, MemberId, Membership, MemoText, Mint, MintId, Opening, OpeningId, OpeningOf, PaidMembershipTerms, PaidTermId, Post, PostId, Principal, PrincipalId, PropertyId, ProposalDetailsOf, ProposalId, ProposalOf, Recipient, RecipientId, RewardRelationship, RewardRelationshipId, SealedVote, Seats, Stake, StakeId, StaticBag, StaticBagId, StorageBucket, StorageBucketId, Thread, ThreadCounter, ThreadId, TransferableStake, VoteKind, WorkerId, WorkerOf, WorkingGroupUnstaker } from './all';
+import type { Application, ApplicationId, ApplicationOf, Category, CategoryId, Channel, ChannelId, Class, ClassId, ClassOf, ClassPermissionsType, ContentId, Credential, Curator, CuratorApplication, CuratorApplicationId, CuratorGroup, CuratorGroupId, CuratorId, CuratorOpening, CuratorOpeningId, DataObjectId, DiscussionPost, DiscussionThread, DistributionBucketFamily, DistributionBucketFamilyId, DistributionBucketId, DynamicBag, DynamicBagCreationPolicy, DynamicBagId, DynamicBagType, ElectionStage, ElectionStake, Entity, EntityController, EntityCreationVoucher, EntityId, EntityOf, HiringApplicationId, InputValidationLengthConstraint, Lead, LeadId, MemberId, Membership, MemoText, Mint, MintId, Opening, OpeningId, OpeningOf, PaidMembershipTerms, PaidTermId, Post, PostId, Principal, PrincipalId, PropertyId, ProposalDetailsOf, ProposalId, ProposalOf, Recipient, RecipientId, RewardRelationship, RewardRelationshipId, SealedVote, Seats, Stake, StakeId, StaticBag, StaticBagId, StorageBucket, StorageBucketId, Thread, ThreadCounter, ThreadId, TransferableStake, VoteKind, WorkerId, WorkerOf, WorkingGroupUnstaker } from './all';
 import type { UncleEntryItem } from '@polkadot/types/interfaces/authorship';
 import type { BabeAuthorityWeight, MaybeRandomness, NextConfigDescriptor, Randomness } from '@polkadot/types/interfaces/babe';
 import type { AccountData, BalanceLock } from '@polkadot/types/interfaces/balances';
@@ -331,6 +331,61 @@ declare module '@polkadot/api/types/storage' {
       votes: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<SealedVote>, [Hash]>;
       votingPeriod: AugmentedQuery<ApiType, () => Observable<BlockNumber>, []>;
     };
+    distributionWorkingGroup: {
+      /**
+       * Count of active workers.
+       **/
+      activeWorkerCount: AugmentedQuery<ApiType, () => Observable<u32>, []>;
+      /**
+       * Maps identifier to worker application on opening.
+       **/
+      applicationById: AugmentedQuery<ApiType, (arg: ApplicationId | AnyNumber | Uint8Array) => Observable<ApplicationOf>, [ApplicationId]>;
+      /**
+       * The current lead.
+       **/
+      currentLead: AugmentedQuery<ApiType, () => Observable<Option<WorkerId>>, []>;
+      /**
+       * Map member id by hiring application id.
+       * Required by StakingEventsHandler callback call to refund the balance on unstaking.
+       **/
+      memberIdByHiringApplicationId: AugmentedQuery<ApiType, (arg: HiringApplicationId | AnyNumber | Uint8Array) => Observable<MemberId>, [HiringApplicationId]>;
+      /**
+       * The mint currently funding the rewards for this module.
+       **/
+      mint: AugmentedQuery<ApiType, () => Observable<MintId>, []>;
+      /**
+       * Next identifier value for new worker application.
+       **/
+      nextApplicationId: AugmentedQuery<ApiType, () => Observable<ApplicationId>, []>;
+      /**
+       * Next identifier value for new worker opening.
+       **/
+      nextOpeningId: AugmentedQuery<ApiType, () => Observable<OpeningId>, []>;
+      /**
+       * Next identifier for new worker.
+       **/
+      nextWorkerId: AugmentedQuery<ApiType, () => Observable<WorkerId>, []>;
+      /**
+       * Maps identifier to worker opening.
+       **/
+      openingById: AugmentedQuery<ApiType, (arg: OpeningId | AnyNumber | Uint8Array) => Observable<OpeningOf>, [OpeningId]>;
+      /**
+       * Opening human readable text length limits
+       **/
+      openingHumanReadableText: AugmentedQuery<ApiType, () => Observable<InputValidationLengthConstraint>, []>;
+      /**
+       * Worker application human readable text length limits
+       **/
+      workerApplicationHumanReadableText: AugmentedQuery<ApiType, () => Observable<InputValidationLengthConstraint>, []>;
+      /**
+       * Maps identifier to corresponding worker.
+       **/
+      workerById: AugmentedQuery<ApiType, (arg: WorkerId | AnyNumber | Uint8Array) => Observable<WorkerOf>, [WorkerId]>;
+      /**
+       * Worker exit rationale text length limits.
+       **/
+      workerExitRationaleText: AugmentedQuery<ApiType, () => Observable<InputValidationLengthConstraint>, []>;
+    };
     forum: {
       /**
        * Map category identifier to corresponding category.
@@ -969,6 +1024,18 @@ declare module '@polkadot/api/types/storage' {
        * Size based pricing of new objects uploaded.
        **/
       dataObjectPerMegabyteFee: AugmentedQuery<ApiType, () => Observable<BalanceOf>, []>;
+      /**
+       * Distribution bucket families.
+       **/
+      distributionBucketFamilyById: AugmentedQuery<ApiType, (arg: DistributionBucketFamilyId | AnyNumber | Uint8Array) => Observable<DistributionBucketFamily>, [DistributionBucketFamilyId]>;
+      /**
+       * Total number of distribution bucket families in the system.
+       **/
+      distributionBucketFamilyNumber: AugmentedQuery<ApiType, () => Observable<u64>, []>;
+      /**
+       * "Distribution buckets per bag" number limit.
+       **/
+      distributionBucketsPerBagLimit: AugmentedQuery<ApiType, () => Observable<u64>, []>;
       /**
        * DynamicBagCreationPolicy by bag type storage map.
        **/
@@ -981,6 +1048,14 @@ declare module '@polkadot/api/types/storage' {
        * Data object id counter. Starts at zero.
        **/
       nextDataObjectId: AugmentedQuery<ApiType, () => Observable<DataObjectId>, []>;
+      /**
+       * Distribution bucket family id counter. Starts at zero.
+       **/
+      nextDistributionBucketFamilyId: AugmentedQuery<ApiType, () => Observable<DistributionBucketFamilyId>, []>;
+      /**
+       * Distribution bucket id counter. Starts at zero.
+       **/
+      nextDistributionBucketId: AugmentedQuery<ApiType, () => Observable<DistributionBucketId>, []>;
       /**
        * Storage bucket id counter. Starts at zero.
        **/

+ 136 - 3
types/augment/augment-api-tx.ts

@@ -3,7 +3,7 @@
 
 import type { BTreeMap, BTreeSet, Bytes, Compact, Option, Vec, bool, u16, u32, u64 } from '@polkadot/types';
 import type { AnyNumber, ITuple } from '@polkadot/types/types';
-import type { ActivateOpeningAt, Actor, AddOpeningParameters, ApplicationId, ApplicationIdSet, BagId, BalanceOfMint, CategoryId, ChannelContentType, ChannelCurationStatus, ChannelId, ChannelPublicationStatus, ClassId, ClassPermissions, ClassPermissionsType, ClassPropertyValue, ContentId, Credential, CredentialSet, CurationActor, CuratorApplicationId, CuratorApplicationIdSet, CuratorGroupId, CuratorId, CuratorOpeningId, DataObjectId, DynamicBagType, ElectionParameters, EntityController, EntityId, EntityPermissions, FillOpeningParameters, InputPropertyValue, InputValue, MemberId, MemoText, Nonce, OpeningId, OpeningPolicyCommitment, OpeningType, Operation, OperationType, OptionalText, PaidTermId, PostId, Property, PropertyId, ProposalId, ReferenceConstraint, RewardPolicy, SchemaId, StorageBucketId, TerminateRoleParameters, ThreadId, UploadParameters, VecMaxLength, VoteKind, WorkerId, WorkingGroup } from './all';
+import type { ActivateOpeningAt, Actor, AddOpeningParameters, ApplicationId, ApplicationIdSet, BagId, BalanceOfMint, CategoryId, ChannelContentType, ChannelCurationStatus, ChannelId, ChannelPublicationStatus, ClassId, ClassPermissions, ClassPermissionsType, ClassPropertyValue, ContentId, Credential, CredentialSet, CurationActor, CuratorApplicationId, CuratorApplicationIdSet, CuratorGroupId, CuratorId, CuratorOpeningId, DataObjectId, DistributionBucketFamilyId, DistributionBucketId, DynamicBagId, DynamicBagType, ElectionParameters, EntityController, EntityId, EntityPermissions, FillOpeningParameters, InputPropertyValue, InputValue, MemberId, MemoText, Nonce, OpeningId, OpeningPolicyCommitment, OpeningType, Operation, OperationType, OptionalText, PaidTermId, PostId, Property, PropertyId, ProposalId, ReferenceConstraint, RewardPolicy, SchemaId, StorageBucketId, TerminateRoleParameters, ThreadId, UploadParameters, VecMaxLength, VoteKind, WorkerId, WorkingGroup } from './all';
 import type { BabeEquivocationProof } from '@polkadot/types/interfaces/babe';
 import type { Extrinsic, Signature } from '@polkadot/types/interfaces/extrinsics';
 import type { GrandpaEquivocationProof, KeyOwnerProof } from '@polkadot/types/interfaces/grandpa';
@@ -430,6 +430,83 @@ declare module '@polkadot/api/types/submittable' {
       setStageVoting: AugmentedSubmittable<(endsAt: BlockNumber | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [BlockNumber]>;
       vote: AugmentedSubmittable<(commitment: Hash | string | Uint8Array, stake: BalanceOf | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Hash, BalanceOf]>;
     };
+    distributionWorkingGroup: {
+      /**
+       * Begin accepting worker applications to an opening that is active.
+       * Require signed leader origin or the root (to accept applications for the leader position).
+       **/
+      acceptApplications: AugmentedSubmittable<(openingId: OpeningId | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [OpeningId]>;
+      /**
+       * Add an opening for a worker role.
+       * Require signed leader origin or the root (to add opening for the leader position).
+       **/
+      addOpening: AugmentedSubmittable<(activateAt: ActivateOpeningAt | { CurrentBlock: any } | { ExactBlock: any } | string | Uint8Array, commitment: OpeningPolicyCommitment | { application_rationing_policy?: any; max_review_period_length?: any; application_staking_policy?: any; role_staking_policy?: any; role_slashing_terms?: any; fill_opening_successful_applicant_application_stake_unstaking_period?: any; fill_opening_failed_applicant_application_stake_unstaking_period?: any; fill_opening_failed_applicant_role_stake_unstaking_period?: any; terminate_curator_application_stake_unstaking_period?: any; terminate_curator_role_stake_unstaking_period?: any; exit_curator_role_application_stake_unstaking_period?: any; exit_curator_role_stake_unstaking_period?: any } | string | Uint8Array, humanReadableText: Bytes | string | Uint8Array, openingType: OpeningType | 'Leader' | 'Worker' | number | Uint8Array) => SubmittableExtrinsic<ApiType>, [ActivateOpeningAt, OpeningPolicyCommitment, Bytes, OpeningType]>;
+      /**
+       * Apply on a worker opening.
+       **/
+      applyOnOpening: AugmentedSubmittable<(memberId: MemberId | AnyNumber | Uint8Array, openingId: OpeningId | AnyNumber | Uint8Array, roleAccountId: AccountId | string | Uint8Array, optRoleStakeBalance: Option<BalanceOf> | null | object | string | Uint8Array, optApplicationStakeBalance: Option<BalanceOf> | null | object | string | Uint8Array, humanReadableText: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [MemberId, OpeningId, AccountId, Option<BalanceOf>, Option<BalanceOf>, Bytes]>;
+      /**
+       * Begin reviewing, and therefore not accepting new applications.
+       * Require signed leader origin or the root (to begin review applications for the leader position).
+       **/
+      beginApplicantReview: AugmentedSubmittable<(openingId: OpeningId | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [OpeningId]>;
+      /**
+       * Decreases the worker/lead stake and returns the remainder to the worker role_account_id.
+       * Can be decreased to zero, no actions on zero stake.
+       * Require signed leader origin or the root (to decrease the leader stake).
+       **/
+      decreaseStake: AugmentedSubmittable<(workerId: WorkerId | AnyNumber | Uint8Array, balance: BalanceOf | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [WorkerId, BalanceOf]>;
+      /**
+       * Fill opening for worker/lead.
+       * Require signed leader origin or the root (to fill opening for the leader position).
+       **/
+      fillOpening: AugmentedSubmittable<(openingId: OpeningId | AnyNumber | Uint8Array, successfulApplicationIds: ApplicationIdSet, rewardPolicy: Option<RewardPolicy> | null | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [OpeningId, ApplicationIdSet, Option<RewardPolicy>]>;
+      /**
+       * Increases the worker/lead stake, demands a worker origin. Transfers tokens from the worker
+       * role_account_id to the stake. No limits on the stake.
+       **/
+      increaseStake: AugmentedSubmittable<(workerId: WorkerId | AnyNumber | Uint8Array, balance: BalanceOf | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [WorkerId, BalanceOf]>;
+      /**
+       * Leave the role by the active worker.
+       **/
+      leaveRole: AugmentedSubmittable<(workerId: WorkerId | AnyNumber | Uint8Array, rationaleText: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [WorkerId, Bytes]>;
+      /**
+       * Sets the capacity to enable working group budget. Requires root origin.
+       **/
+      setMintCapacity: AugmentedSubmittable<(newCapacity: BalanceOf | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [BalanceOf]>;
+      /**
+       * Slashes the worker stake, demands a leader origin. No limits, no actions on zero stake.
+       * If slashing balance greater than the existing stake - stake is slashed to zero.
+       * Require signed leader origin or the root (to slash the leader stake).
+       **/
+      slashStake: AugmentedSubmittable<(workerId: WorkerId | AnyNumber | Uint8Array, balance: BalanceOf | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [WorkerId, BalanceOf]>;
+      /**
+       * Terminate the worker application. Can be done by the lead only.
+       **/
+      terminateApplication: AugmentedSubmittable<(applicationId: ApplicationId | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [ApplicationId]>;
+      /**
+       * Terminate the active worker by the lead.
+       * Require signed leader origin or the root (to terminate the leader role).
+       **/
+      terminateRole: AugmentedSubmittable<(workerId: WorkerId | AnyNumber | Uint8Array, rationaleText: Bytes | string | Uint8Array, slashStake: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [WorkerId, Bytes, bool]>;
+      /**
+       * Update the reward account associated with a set reward relationship for the active worker.
+       **/
+      updateRewardAccount: AugmentedSubmittable<(workerId: WorkerId | AnyNumber | Uint8Array, newRewardAccountId: AccountId | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [WorkerId, AccountId]>;
+      /**
+       * Update the reward amount associated with a set reward relationship for the active worker.
+       * Require signed leader origin or the root (to update leader reward amount).
+       **/
+      updateRewardAmount: AugmentedSubmittable<(workerId: WorkerId | AnyNumber | Uint8Array, newAmount: BalanceOfMint | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [WorkerId, BalanceOfMint]>;
+      /**
+       * Update the associated role account of the active worker/lead.
+       **/
+      updateRoleAccount: AugmentedSubmittable<(workerId: WorkerId | AnyNumber | Uint8Array, newRoleAccountId: AccountId | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [WorkerId, AccountId]>;
+      /**
+       * Withdraw the worker application. Can be done by the worker itself only.
+       **/
+      withdrawApplication: AugmentedSubmittable<(applicationId: ApplicationId | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [ApplicationId]>;
+    };
     finalityTracker: {
       /**
        * Hint that the author of this block thinks the best finalized
@@ -1161,6 +1238,10 @@ declare module '@polkadot/api/types/submittable' {
       withdrawUnbonded: AugmentedSubmittable<(numSlashingSpans: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32]>;
     };
     storage: {
+      /**
+       * Accept pending invite.
+       **/
+      acceptDistributionBucketInvitation: AugmentedSubmittable<(workerId: WorkerId | AnyNumber | Uint8Array, distributionBucketFamilyId: DistributionBucketFamilyId | AnyNumber | Uint8Array, distributionBucketId: DistributionBucketId | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [WorkerId, DistributionBucketFamilyId, DistributionBucketId]>;
       /**
        * A storage provider signals that the data object was successfully uploaded to its storage.
        **/
@@ -1169,18 +1250,42 @@ declare module '@polkadot/api/types/submittable' {
        * Accept the storage bucket invitation. An invitation must match the worker_id parameter.
        **/
       acceptStorageBucketInvitation: AugmentedSubmittable<(workerId: WorkerId | AnyNumber | Uint8Array, storageBucketId: StorageBucketId | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [WorkerId, StorageBucketId]>;
+      /**
+       * Cancel pending invite. Must be pending.
+       **/
+      cancelDistributionBucketOperatorInvite: AugmentedSubmittable<(distributionBucketFamilyId: DistributionBucketFamilyId | AnyNumber | Uint8Array, distributionBucketId: DistributionBucketId | AnyNumber | Uint8Array, operatorWorkerId: WorkerId | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [DistributionBucketFamilyId, DistributionBucketId, WorkerId]>;
       /**
        * Cancel pending storage bucket invite. An invitation must be pending.
        **/
       cancelStorageBucketOperatorInvite: AugmentedSubmittable<(storageBucketId: StorageBucketId | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [StorageBucketId]>;
+      /**
+       * Create a distribution bucket.
+       **/
+      createDistributionBucket: AugmentedSubmittable<(familyId: DistributionBucketFamilyId | AnyNumber | Uint8Array, acceptingNewBags: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [DistributionBucketFamilyId, bool]>;
+      /**
+       * Create a distribution bucket family.
+       **/
+      createDistributionBucketFamily: AugmentedSubmittable<() => SubmittableExtrinsic<ApiType>, []>;
       /**
        * Create storage bucket.
        **/
       createStorageBucket: AugmentedSubmittable<(inviteWorker: Option<WorkerId> | null | object | string | Uint8Array, acceptingNewBags: bool | boolean | Uint8Array, sizeLimit: u64 | AnyNumber | Uint8Array, objectsLimit: u64 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Option<WorkerId>, bool, u64, u64]>;
+      /**
+       * Delete distribution bucket. Must be empty.
+       **/
+      deleteDistributionBucket: AugmentedSubmittable<(familyId: DistributionBucketFamilyId | AnyNumber | Uint8Array, distributionBucketId: DistributionBucketId | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [DistributionBucketFamilyId, DistributionBucketId]>;
+      /**
+       * Deletes a distribution bucket family.
+       **/
+      deleteDistributionBucketFamily: AugmentedSubmittable<(familyId: DistributionBucketFamilyId | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [DistributionBucketFamilyId]>;
       /**
        * Delete storage bucket. Must be empty. Storage operator must be missing.
        **/
       deleteStorageBucket: AugmentedSubmittable<(storageBucketId: StorageBucketId | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [StorageBucketId]>;
+      /**
+       * Invite an operator. Must be missing.
+       **/
+      inviteDistributionBucketOperator: AugmentedSubmittable<(distributionBucketFamilyId: DistributionBucketFamilyId | AnyNumber | Uint8Array, distributionBucketId: DistributionBucketId | AnyNumber | Uint8Array, operatorWorkerId: WorkerId | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [DistributionBucketFamilyId, DistributionBucketId, WorkerId]>;
       /**
        * Invite storage bucket operator. Must be missing.
        **/
@@ -1189,6 +1294,10 @@ declare module '@polkadot/api/types/submittable' {
        * Removes storage bucket operator. Must be invited.
        **/
       removeStorageBucketOperator: AugmentedSubmittable<(storageBucketId: StorageBucketId | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [StorageBucketId]>;
+      /**
+       * Set distribution operator metadata for the distribution bucket.
+       **/
+      setDistributionOperatorMetadata: AugmentedSubmittable<(workerId: WorkerId | AnyNumber | Uint8Array, distributionBucketFamilyId: DistributionBucketFamilyId | AnyNumber | Uint8Array, distributionBucketId: DistributionBucketId | AnyNumber | Uint8Array, metadata: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [WorkerId, DistributionBucketFamilyId, DistributionBucketId, Bytes]>;
       /**
        * Sets storage bucket voucher limits.
        **/
@@ -1197,6 +1306,10 @@ declare module '@polkadot/api/types/submittable' {
        * Sets storage operator metadata (eg.: storage node URL).
        **/
       setStorageOperatorMetadata: AugmentedSubmittable<(workerId: WorkerId | AnyNumber | Uint8Array, storageBucketId: StorageBucketId | AnyNumber | Uint8Array, metadata: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [WorkerId, StorageBucketId, Bytes]>;
+      /**
+       * Create a dynamic bag. Development mode.
+       **/
+      sudoCreateDynamicBag: AugmentedSubmittable<(bagId: DynamicBagId | { Member: any } | { Channel: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [DynamicBagId]>;
       /**
        * Upload new data objects. Development mode.
        **/
@@ -1209,12 +1322,32 @@ declare module '@polkadot/api/types/submittable' {
        * Updates size-based pricing of new objects uploaded.
        **/
       updateDataSizeFee: AugmentedSubmittable<(newDataSizeFee: BalanceOf | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [BalanceOf]>;
+      /**
+       * Updates 'distributing' flag for the distributing flag.
+       **/
+      updateDistributionBucketMode: AugmentedSubmittable<(familyId: DistributionBucketFamilyId | AnyNumber | Uint8Array, distributionBucketId: DistributionBucketId | AnyNumber | Uint8Array, distributing: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [DistributionBucketFamilyId, DistributionBucketId, bool]>;
+      /**
+       * Updates a distribution bucket 'accepts new bags' flag.
+       **/
+      updateDistributionBucketStatus: AugmentedSubmittable<(familyId: DistributionBucketFamilyId | AnyNumber | Uint8Array, distributionBucketId: DistributionBucketId | AnyNumber | Uint8Array, acceptingNewBags: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [DistributionBucketFamilyId, DistributionBucketId, bool]>;
+      /**
+       * Updates distribution buckets for a bag.
+       **/
+      updateDistributionBucketsForBag: AugmentedSubmittable<(bagId: BagId | { Static: any } | { Dynamic: any } | string | Uint8Array, familyId: DistributionBucketFamilyId | AnyNumber | Uint8Array, addBuckets: BTreeSet<DistributionBucketId>, removeBuckets: BTreeSet<DistributionBucketId>) => SubmittableExtrinsic<ApiType>, [BagId, DistributionBucketFamilyId, BTreeSet<DistributionBucketId>, BTreeSet<DistributionBucketId>]>;
+      /**
+       * Updates "Distribution buckets per bag" number limit.
+       **/
+      updateDistributionBucketsPerBagLimit: AugmentedSubmittable<(newLimit: u64 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u64]>;
+      /**
+       * Update number of distributed buckets used in given dynamic bag creation policy.
+       **/
+      updateFamiliesInDynamicBagCreationPolicy: AugmentedSubmittable<(dynamicBagType: DynamicBagType | 'Member' | 'Channel' | number | Uint8Array, families: BTreeMap<DistributionBucketFamilyId, u32>) => SubmittableExtrinsic<ApiType>, [DynamicBagType, BTreeMap<DistributionBucketFamilyId, u32>]>;
       /**
        * Update number of storage buckets used in given dynamic bag creation policy.
        **/
       updateNumberOfStorageBucketsInDynamicBagCreationPolicy: AugmentedSubmittable<(dynamicBagType: DynamicBagType | 'Member' | 'Channel' | number | Uint8Array, numberOfStorageBuckets: u64 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [DynamicBagType, u64]>;
       /**
-       * Update whether new bags are being accepted for storage.
+       * Updates a storage bucket 'accepts new bags' flag.
        **/
       updateStorageBucketStatus: AugmentedSubmittable<(workerId: WorkerId | AnyNumber | Uint8Array, storageBucketId: StorageBucketId | AnyNumber | Uint8Array, acceptingNewBags: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [WorkerId, StorageBucketId, bool]>;
       /**
@@ -1230,7 +1363,7 @@ declare module '@polkadot/api/types/submittable' {
        **/
       updateStorageBucketsVoucherMaxLimits: AugmentedSubmittable<(newObjectsSize: u64 | AnyNumber | Uint8Array, newObjectsNumber: u64 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u64, u64]>;
       /**
-       * Update whether uploading is globally blocked.
+       * Updates global uploading flag.
        **/
       updateUploadingBlockedStatus: AugmentedSubmittable<(newStatus: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [bool]>;
     };

File diff suppressed because it is too large
+ 0 - 0
types/augment/augment-types.ts


+ 0 - 3
types/src/index.ts

@@ -11,7 +11,6 @@ import hiring from './hiring'
 import contentWorkingGroup from './content-working-group'
 import workingGroup from './working-group'
 import discovery from './discovery'
-import media from './media'
 import proposals from './proposals'
 import contentDirectory from './content-directory'
 import storage from './storage'
@@ -35,7 +34,6 @@ export {
   contentWorkingGroup,
   workingGroup,
   discovery,
-  media,
   proposals,
   contentDirectory,
   storage,
@@ -54,7 +52,6 @@ export const types: RegistryTypes = {
   ...contentWorkingGroup,
   ...workingGroup,
   ...discovery,
-  ...media,
   ...proposals,
   ...contentDirectory,
   ...storage,

+ 0 - 83
types/src/media.ts

@@ -1,83 +0,0 @@
-import { Option, Vec as Vector, BTreeMap, u64, bool, Text, Null } from '@polkadot/types'
-import { BlockAndTime, JoyEnum, JoyStructDecorated, Hash } from './common'
-import { MemberId } from './members'
-import { StorageProviderId } from './working-group' // this should be in discovery really
-import { randomAsU8a } from '@polkadot/util-crypto'
-import { encodeAddress, decodeAddress } from '@polkadot/keyring'
-import { RegistryTypes, Registry } from '@polkadot/types/types'
-
-export class ContentId extends Hash {
-  static generate(registry: Registry): ContentId {
-    // randomAsU8a uses https://www.npmjs.com/package/tweetnacl#random-bytes-generation
-    return new ContentId(registry, randomAsU8a())
-  }
-
-  static decode(registry: Registry, contentId: string): ContentId {
-    return new ContentId(registry, decodeAddress(contentId))
-  }
-
-  static encode(contentId: Uint8Array): string {
-    // console.log('contentId:', Buffer.from(contentId).toString('hex'))
-    return encodeAddress(contentId)
-  }
-
-  encode(): string {
-    return ContentId.encode(this)
-  }
-}
-
-export class DataObjectTypeId extends u64 {}
-export class DataObjectStorageRelationshipId extends u64 {}
-
-export class VecContentId extends Vector.with(ContentId) {}
-export class OptionVecContentId extends Option.with(VecContentId) {}
-
-export const LiaisonJudgementDef = {
-  Pending: Null,
-  Accepted: Null,
-  Rejected: Null,
-} as const
-export type LiaisonJudgementKey = keyof typeof LiaisonJudgementDef
-export class LiaisonJudgement extends JoyEnum(LiaisonJudgementDef) {}
-
-export class DataObject extends JoyStructDecorated({
-  owner: MemberId,
-  added_at: BlockAndTime,
-  type_id: DataObjectTypeId,
-  size: u64,
-  liaison: StorageProviderId,
-  liaison_judgement: LiaisonJudgement,
-  ipfs_content_id: Text,
-}) {
-  /** Actually it's 'size', but 'size' is already reserved by a parent class. */
-  get size_in_bytes(): u64 {
-    return this.get('size') as u64
-  }
-}
-
-export class DataObjectStorageRelationship extends JoyStructDecorated({
-  content_id: ContentId,
-  storage_provider: StorageProviderId,
-  ready: bool,
-}) {}
-
-export class DataObjectType extends JoyStructDecorated({
-  description: Text,
-  active: bool,
-}) {}
-
-export class DataObjectsMap extends BTreeMap.with(ContentId, DataObject) {}
-
-export const mediaTypes: RegistryTypes = {
-  // FIXME: Clash with storage v2 module!
-  // ContentId,
-  LiaisonJudgement,
-  DataObject,
-  DataObjectStorageRelationshipId,
-  DataObjectStorageRelationship,
-  DataObjectTypeId,
-  DataObjectType,
-  DataObjectsMap,
-}
-
-export default mediaTypes

+ 0 - 2
types/src/scripts/generateAugmentCodec.ts

@@ -20,7 +20,6 @@ import hiring from '../hiring'
 import contentWorkingGroup from '../content-working-group'
 import workingGroup from '../working-group'
 import discovery from '../discovery'
-import media from '../media'
 import proposals from '../proposals'
 import contentDirectory from '../content-directory'
 import storage from '../storage'
@@ -43,7 +42,6 @@ const typesByModule = {
   'content-working-group': contentWorkingGroup,
   'working-group': workingGroup,
   'discovery': discovery,
-  'media': media,
   'proposals': proposals,
   'content-directory': contentDirectory,
   'storage': storage,

+ 116 - 16
types/src/storage.ts

@@ -1,9 +1,22 @@
-import { Null, u64, Text, Vec, GenericAccountId as AccountId, BTreeSet } from '@polkadot/types'
+import {
+  Null,
+  u128,
+  u64,
+  Text,
+  Vec,
+  bool,
+  GenericAccountId as AccountId,
+  BTreeSet,
+  BTreeMap,
+  u32,
+} from '@polkadot/types'
 import { RegistryTypes } from '@polkadot/types/types'
 import { JoyBTreeSet, JoyEnum, JoyStructDecorated, WorkingGroup } from './common'
 import { ChannelId } from './content-working-group'
 import { MemberId } from './members'
+import { WorkerId } from './working-group'
 
+export class BalanceOf extends u128 {}
 export class DataObjectId extends u64 {}
 export class StorageBucketId extends u64 {}
 
@@ -19,29 +32,66 @@ export class StorageBucketsPerBagValueConstraint
   })
   implements StorageBucketsPerBagValueConstraintType {}
 
-export const DynamicBagIdDef = {
-  Member: MemberId,
-  Channel: ChannelId,
+export type DataObjectType = {
+  accepted: bool
+  deletion_prize: BalanceOf
+  size: u64
 }
-export type DynamicBagIdKey = keyof typeof DynamicBagIdDef
-export class DynamicBagIdType extends JoyEnum(DynamicBagIdDef) {}
 
-// Runtime alias
-export class DynamicBagId extends DynamicBagIdType {}
+export class DataObject
+  extends JoyStructDecorated({
+    accepted: bool,
+    deletion_prize: BalanceOf,
+    size: u64,
+  })
+  implements DataObjectType {}
 
-// TODO: implement these types:
-export class DynamicBag extends u64 {}
-export class StaticBag extends u64 {}
-export class StorageBucket extends u64 {}
-//
+export class DataObjectIdSet extends JoyBTreeSet(DataObjectId) {}
+export class DataObjectIdMap extends BTreeMap.with(DataObjectId, DataObject) {}
+export class DistributionBucketId extends u64 {}
+export class DistributionBucketFamilyId extends u64 {}
+export class StorageBucketIdSet extends JoyBTreeSet(StorageBucketId) {}
+export class DistributionBucketSet extends JoyBTreeSet(DistributionBucketId) {}
+
+export type StaticBagType = {
+  objects: DataObjectIdMap
+  stored_by: StorageBucketIdSet
+  distributed_by: DistributionBucketSet
+}
+
+export class StaticBag
+  extends JoyStructDecorated({
+    objects: DataObjectIdMap,
+    stored_by: StorageBucketIdSet,
+    distributed_by: DistributionBucketSet,
+  })
+  implements StaticBagType {}
+
+export type DynamicBagTypeDef = {
+  objects: DataObjectIdMap
+  stored_by: StorageBucketIdSet
+  distributed_by: DistributionBucketSet
+  deletion_prize: BalanceOf
+}
+
+export class DynamicBag
+  extends JoyStructDecorated({
+    objects: DataObjectIdMap,
+    stored_by: StorageBucketIdSet,
+    distributed_by: DistributionBucketSet,
+    deletion_prize: BalanceOf,
+  })
+  implements DynamicBagTypeDef {}
 
 export type DynamicBagCreationPolicyType = {
   numberOfStorageBuckets: u64
+  families: BTreeMap<DistributionBucketFamilyId, u32>
 }
 
 export class DynamicBagCreationPolicy
   extends JoyStructDecorated({
     numberOfStorageBuckets: u64,
+    families: BTreeMap.with(DistributionBucketFamilyId, u32),
   })
   implements DynamicBagCreationPolicyType {}
 
@@ -52,6 +102,16 @@ export const DynamicBagTypeDef = {
 export type DynamicBagTypeKey = keyof typeof DynamicBagTypeDef
 export class DynamicBagType extends JoyEnum(DynamicBagTypeDef) {}
 
+export const DynamicBagIdDef = {
+  Member: MemberId,
+  Channel: ChannelId,
+}
+export type DynamicBagIdKey = keyof typeof DynamicBagIdDef
+export class DynamicBagIdType extends JoyEnum(DynamicBagIdDef) {}
+
+// Runtime alias
+export class DynamicBagId extends DynamicBagIdType {}
+
 export const StaticBagIdDef = {
   Council: Null,
   WorkingGroup: WorkingGroup,
@@ -60,10 +120,11 @@ export type StaticBagIdKey = keyof typeof StaticBagIdDef
 export class StaticBagId extends JoyEnum(StaticBagIdDef) {}
 
 export class Static extends StaticBagId {}
+export class Dynamic extends DynamicBagId {}
 
 export const BagIdDef = {
   Static,
-  Dynamic: DynamicBagIdType,
+  Dynamic,
 } as const
 export type BagIdKey = keyof typeof BagIdDef
 export class BagId extends JoyEnum(BagIdDef) {}
@@ -87,9 +148,29 @@ export class Voucher
   })
   implements VoucherType {}
 
-export class StorageBucketIdSet extends JoyBTreeSet(StorageBucketId) {}
+export const StorageBucketOperatorStatusDef = {
+  Missing: Null,
+  InvitedStorageWorker: u64,
+  StorageWorker: u64,
+} as const
+export type StorageBucketOperatorStatusKey = keyof typeof StorageBucketOperatorStatusDef
+export class StorageBucketOperatorStatus extends JoyEnum(StorageBucketOperatorStatusDef) {}
+
+export type StorageBucketType = {
+  operator_status: StorageBucketOperatorStatus
+  accepting_new_bags: bool
+  voucher: Voucher
+  metadata: Text
+}
 
-export class DataObjectIdSet extends JoyBTreeSet(DataObjectId) {}
+export class StorageBucket
+  extends JoyStructDecorated({
+    operator_status: StorageBucketOperatorStatus,
+    accepting_new_bags: bool,
+    voucher: Voucher,
+    metadata: Text,
+  })
+  implements StorageBucketType {}
 
 export type DataObjectCreationParametersType = {
   size: u64
@@ -122,6 +203,17 @@ export class UploadParameters
 export class ContentId extends Text {}
 export class ContentIdSet extends BTreeSet.with(ContentId) {}
 
+export class DistributionBucket extends JoyStructDecorated({
+  acceptingNewBags: bool,
+  distributing: bool,
+  pendingInvitations: JoyBTreeSet(WorkerId),
+  operators: JoyBTreeSet(WorkerId),
+}) {}
+
+export class DistributionBucketFamily extends JoyStructDecorated({
+  distributionBuckets: BTreeMap.with(DistributionBucketId, DistributionBucket),
+}) {}
+
 export const storageTypes: RegistryTypes = {
   StorageBucketId,
   StorageBucketsPerBagValueConstraint,
@@ -136,6 +228,7 @@ export const storageTypes: RegistryTypes = {
   StorageBucket,
   StaticBagId,
   Static,
+  Dynamic,
   BagId,
   DataObjectCreationParameters,
   BagIdType,
@@ -144,5 +237,12 @@ export const storageTypes: RegistryTypes = {
   DataObjectIdSet,
   ContentIdSet,
   ContentId,
+  StorageBucketOperatorStatus,
+  DistributionBucket,
+  DistributionBucketId,
+  DistributionBucketFamily,
+  DistributionBucketFamilyId,
+  DataObject,
+  DataObjectIdMap,
 }
 export default storageTypes

Some files were not shown because too many files changed in this diff