diff --git a/invarch/Cargo.lock b/invarch/Cargo.lock index 980329bb..cb8262b6 100644 --- a/invarch/Cargo.lock +++ b/invarch/Cargo.lock @@ -4377,7 +4377,6 @@ dependencies = [ [[package]] name = "invarch-primitives" version = "0.1.0-dev" -source = "git+https://github.com/InvArch/InvArch-Frames?branch=francisco-weight_fixes#c7bd7bb82384fcd4cd75d4030dfc0c637dd6f58a" dependencies = [ "frame-system", "parity-scale-codec", @@ -6564,7 +6563,6 @@ dependencies = [ [[package]] name = "pallet-checked-inflation" version = "0.1.0-dev" -source = "git+https://github.com/InvArch/InvArch-Frames?branch=francisco-weight_fixes#c7bd7bb82384fcd4cd75d4030dfc0c637dd6f58a" dependencies = [ "frame-benchmarking", "frame-support", @@ -6827,7 +6825,6 @@ dependencies = [ [[package]] name = "pallet-inv4" version = "0.1.0-dev" -source = "git+https://github.com/InvArch/InvArch-Frames?branch=francisco-weight_fixes#c7bd7bb82384fcd4cd75d4030dfc0c637dd6f58a" dependencies = [ "frame-benchmarking", "frame-support", @@ -6989,7 +6986,6 @@ dependencies = [ [[package]] name = "pallet-ocif-staking" version = "0.1.0-dev" -source = "git+https://github.com/InvArch/InvArch-Frames?branch=francisco-weight_fixes#c7bd7bb82384fcd4cd75d4030dfc0c637dd6f58a" dependencies = [ "cumulus-primitives-core", "frame-benchmarking", diff --git a/invarch/Cargo.toml b/invarch/Cargo.toml index fc6d918d..3b614fbd 100644 --- a/invarch/Cargo.toml +++ b/invarch/Cargo.toml @@ -44,10 +44,10 @@ pallet-tx-pause = { git = "https://github.com/paritytech/polkadot-sdk.git", bran # InvArch -pallet-inv4 = { git = "https://github.com/InvArch/InvArch-Frames", branch = "francisco-weight_fixes", default-features = false } -pallet-ocif-staking = { git = "https://github.com/InvArch/InvArch-Frames", branch = "francisco-weight_fixes", default-features = false } -pallet-checked-inflation = { git = "https://github.com/InvArch/InvArch-Frames", branch = "francisco-weight_fixes", default-features = false } -pallet-rings = { git = "https://github.com/InvArch/InvArch-Frames", branch = "francisco-weight_fixes", default-features = false } +pallet-inv4 = { path = "../pallets/INV4/pallet-inv4", default-features = false } +pallet-ocif-staking = { path = "../pallets/OCIF/staking", default-features = false } +pallet-checked-inflation = { path = "../pallets/pallet-checked-inflation", default-features = false } +pallet-rings = { path = "../pallets/pallet-rings", default-features = false } # Substrate frame-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "release-polkadot-v1.6.0", default-features = false } diff --git a/pallets/.github/workflows/build.yml b/pallets/.github/workflows/build.yml new file mode 100644 index 00000000..c65d42cc --- /dev/null +++ b/pallets/.github/workflows/build.yml @@ -0,0 +1,46 @@ +name: Checks + +on: + push: + branches: [ main, development ] + pull_request: + branches: [ main, development ] + +env: + CARGO_TERM_COLOR: always + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Install & display rust toolchain + run: rustup show + - name: Build + run: cargo build --verbose + + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Install & display rust toolchain + run: rustup show + - name: Run tests + run: cargo test --verbose + + clippy: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Install & display rust toolchain + run: rustup show + - name: Run clippy + run: cargo clippy -- -D warnings + fmt: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Install & display rust toolchain + run: rustup show + - name: Run cargofmt + run: cargo fmt --all -- --check diff --git a/pallets/.github/workflows/rustdoc.yml b/pallets/.github/workflows/rustdoc.yml new file mode 100644 index 00000000..62b836e4 --- /dev/null +++ b/pallets/.github/workflows/rustdoc.yml @@ -0,0 +1,32 @@ +name: Build Rust Docs + +on: + push: + branches: + - main + +jobs: + rustdoc: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v3 + + - name: Install deps + run: sudo apt -y install protobuf-compiler + + - name: Install & display rust toolchain + run: rustup show + + - name: Check targets are installed correctly + run: rustup target list --installed + + - name: Build Documentation + run: RUSTDOCFLAGS="--enable-index-page -Zunstable-options" cargo doc --no-deps --document-private-items + + - name: Deploy Docs + uses: peaceiris/actions-gh-pages@v3 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + publish_branch: gh-pages + publish_dir: ./target/doc diff --git a/pallets/.gitignore b/pallets/.gitignore new file mode 100644 index 00000000..c1de5505 --- /dev/null +++ b/pallets/.gitignore @@ -0,0 +1,8 @@ +# Generated by Cargo +# will have compiled files and executables +**/target/ + +#local dependencies +**/Cargo.lock +.idea/vcs.xml +.idea/workspace.xml diff --git a/pallets/Cargo.toml b/pallets/Cargo.toml new file mode 100644 index 00000000..5a35d27d --- /dev/null +++ b/pallets/Cargo.toml @@ -0,0 +1,58 @@ +[workspace] +resolver = "2" +members = [ + "INV4/pallet-inv4", + "OCIF/staking", + "pallet-checked-inflation", + "pallet-rings", +] + +[workspace.dependencies] + +# crates.io dependencies +codec = { package = "parity-scale-codec", version = "3.6.5", features = [ + "derive", +], default-features = false } +log = { version = "0.4.20", default-features = false } +num-traits = { version = "0.2", default-features = false } +scale-info = { version = "2.10.0", default-features = false, features = [ + "derive", +] } +serde = { version = "1.0.189", features = ["derive"] } +smallvec = { version = "1.6.1" } + +# polkadot-sdk dependencies +frame-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk.git", default-features = false, branch = "release-polkadot-v1.6.0" } +frame-support = { git = "https://github.com/paritytech/polkadot-sdk.git", default-features = false, branch = "release-polkadot-v1.6.0" } +frame-system = { git = "https://github.com/paritytech/polkadot-sdk.git", default-features = false, branch = "release-polkadot-v1.6.0" } +pallet-balances = { git = "https://github.com/paritytech/polkadot-sdk.git", default-features = false, branch = "release-polkadot-v1.6.0" } +pallet-message-queue = { git = "https://github.com/paritytech/polkadot-sdk.git", default-features = false, branch = "release-polkadot-v1.6.0" } +pallet-session = { git = "https://github.com/paritytech/polkadot-sdk.git", default-features = false, branch = "release-polkadot-v1.6.0" } +pallet-timestamp = { git = "https://github.com/paritytech/polkadot-sdk.git", default-features = false, branch = "release-polkadot-v1.6.0" } +pallet-xcm = { git = "https://github.com/paritytech/polkadot-sdk.git", default-features = false, branch = "release-polkadot-v1.6.0" } +sp-api = { git = "https://github.com/paritytech/polkadot-sdk.git", default-features = false, branch = "release-polkadot-v1.6.0" } +sp-arithmetic = { git = "https://github.com/paritytech/polkadot-sdk.git", default-features = false, branch = "release-polkadot-v1.6.0" } +sp-core = { git = "https://github.com/paritytech/polkadot-sdk.git", default-features = false, branch = "release-polkadot-v1.6.0" } +sp-io = { git = "https://github.com/paritytech/polkadot-sdk.git", default-features = false, branch = "release-polkadot-v1.6.0" } +sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk.git", default-features = false, branch = "release-polkadot-v1.6.0" } +sp-staking = { git = "https://github.com/paritytech/polkadot-sdk.git", default-features = false, branch = "release-polkadot-v1.6.0" } +sp-std = { git = "https://github.com/paritytech/polkadot-sdk.git", default-features = false, branch = "release-polkadot-v1.6.0" } +xcm = { package = "staging-xcm", git = "https://github.com/paritytech/polkadot-sdk.git", default-features = false, branch = "release-polkadot-v1.6.0" } +xcm-builder = { package = "staging-xcm-builder", git = "https://github.com/paritytech/polkadot-sdk.git", default-features = false, branch = "release-polkadot-v1.6.0" } +xcm-executor = { package = "staging-xcm-executor", git = "https://github.com/paritytech/polkadot-sdk.git", default-features = false, branch = "release-polkadot-v1.6.0" } + + +# dev dependencies + +cumulus-primitives-core = { git = "https://github.com/paritytech/polkadot-sdk.git", branch = "release-polkadot-v1.6.0", default-features = false } + +orml-asset-registry = { git = "https://github.com/InvArch/open-runtime-module-library.git", default-features = false, branch = "polkadot-v1.6.0" } +orml-tokens2 = { package = "orml-tokens", git = "https://github.com/arrudagates/open-runtime-module-library.git", default-features = false, rev = "bc6b41e8a9539971a2da5d62cf8f550cde985f00" } +orml-traits2 = { package = "orml-traits", git = "https://github.com/arrudagates/open-runtime-module-library.git", default-features = false, rev = "bc6b41e8a9539971a2da5d62cf8f550cde985f00" } + +orml-tokens = { package = "orml-tokens", git = "https://github.com/InvArch/open-runtime-module-library.git", default-features = false, branch = "polkadot-v1.6.0" } +orml-traits = { package = "orml-traits", git = "https://github.com/InvArch/open-runtime-module-library.git", default-features = false, branch = "polkadot-v1.6.0" } + +# orml-asset-registry = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, rev = "7ecebeab7e3dbc2226ed58d32ee159271a8176ae" } +# orml-tokens = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, rev = "7ecebeab7e3dbc2226ed58d32ee159271a8176ae" } +# orml-traits = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, rev = "7ecebeab7e3dbc2226ed58d32ee159271a8176ae" } diff --git a/pallets/INV4/pallet-inv4/Cargo.toml b/pallets/INV4/pallet-inv4/Cargo.toml new file mode 100644 index 00000000..0ac6d557 --- /dev/null +++ b/pallets/INV4/pallet-inv4/Cargo.toml @@ -0,0 +1,76 @@ +[package] +authors = ['InvArchitects '] +description = '' +edition = '2021' +homepage = 'https://invarch.network' +license = 'GPLv3' +name = 'pallet-inv4' +repository = 'https://github.com/InvArch/InvArch-Frames' +version = '0.1.0-dev' + +[dependencies] +serde = { workspace = true, optional = true } +codec = { package = "parity-scale-codec", version = "3.6.5", default-features = false, features = [ + "derive", + "max-encoded-len", +] } +sp-runtime = { workspace = true, default-features = false } +sp-arithmetic = { workspace = true, default-features = false } +sp-std = { workspace = true, default-features = false } +frame-support = { workspace = true, default-features = false } +smallvec = { workspace = true } + +scale-info = { workspace = true, default-features = false } + +log = { workspace = true, default-features = false } + +# InvArch dependencies +primitives = { package = "invarch-primitives", path = "../../primitives", default-features = false } + +sp-io = { workspace = true, default-features = false } +sp-api = { workspace = true, default-features = false } +sp-core = { workspace = true, default-features = false } + +pallet-balances = { workspace = true, default-features = false } + +frame-system = { workspace = true, default-features = false } # frame-benchmarking requires system +frame-benchmarking = { workspace = true, default-features = false, optional = true } + + +xcm = { workspace = true, default-features = false } +orml-tokens2 = { workspace = true, default-features = false } + +[dev-dependencies] + +orml-traits2 = { workspace = true, default-features = false } +orml-tokens = { workspace = true, default-features = false } +orml-traits = { workspace = true, default-features = false } +orml-asset-registry = { workspace = true, default-features = false } + + +[features] +default = ["std"] +std = [ + "serde", + "codec/std", + "sp-runtime/std", + "sp-std/std", + "frame-support/std", + "frame-system/std", + "sp-io/std", + "scale-info/std", + "pallet-balances/std", + "frame-benchmarking?/std", + "xcm/std", + "orml-asset-registry/std", + "orml-tokens/std", + "orml-tokens2/std", + "orml-traits/std", + "orml-traits2/std", +] +runtime-benchmarks = [ + "frame-benchmarking/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", + "frame-system/runtime-benchmarks", +] +try-runtime = ["frame-support/try-runtime"] diff --git a/pallets/INV4/pallet-inv4/README.md b/pallets/INV4/pallet-inv4/README.md new file mode 100644 index 00000000..96459ab4 --- /dev/null +++ b/pallets/INV4/pallet-inv4/README.md @@ -0,0 +1,43 @@ +# INV4 Pallet + +## Introduction + +The INV4 pallet is designed to manage advanced virtual multisigs, internally referred to as cores. It provides the functionality to create cores, mint and burn the core's voting tokens, and manage multisig proposals. This pallet is a comprehensive solution for decentralized decision-making processes, allowing for flexible and secure management of multisig operations. + +## Features + +- **Core Creation**: Establish new cores with customizable parameters, including metadata, voting thresholds, and token freeze state. +- **Token Management**: Mint and burn the core's voting tokens to manage the voting power within the core. +- **Multisig Proposals**: Create, vote on, and cancel multisig proposals. Proposals automatically execute if they meet the execution threshold requirements. +- **Vote Management**: Members can vote on proposals, withdraw their votes, and influence the outcome of decisions. +- **Parameter Adjustment**: Core parameters, such as voting thresholds and token freeze state, can be dynamically adjusted by core origins. + +## Functionality Overview + +### Core Management + +- `create_core`: Initialize a new core with specific parameters and distribute initial voting tokens to the creator. +- `set_parameters`: Modify core parameters, including voting thresholds, metadata, and token freeze state. + +### Token Operations + +- `token_mint`: Mint the core's voting tokens to a specified target, increasing their voting power within the core. +- `token_burn`: Burn the core's voting tokens from a specified target, decreasing their voting power. + +### Multisig Operations + +- `operate_multisig`: Submit a new multisig proposal. If the proposal meets execution thresholds, it is automatically executed. +- `vote_multisig`: Cast a vote on an existing multisig proposal. Proposals execute automatically if they meet threshold requirements after the vote. +- `withdraw_vote_multisig`: Withdraw a previously cast vote from a multisig proposal. +- `cancel_multisig_proposal`: Cancel an existing multisig proposal. This action can only be performed by a core origin. + +### Utility Functions + +- `CoreAccountDerivation`: Derive consistent core AccountIds across parachains for seamless interaction. +- `INV4Lookup`: Custom account lookup implementation for converting CoreIds to AccountIds. +- `FeeAsset`: Define the asset used by the multisig for paying transaction fees. +- `MultisigFeeHandler`: Manage fee payments for multisig operations, supporting both native and non-native assets. + +## Usage + +To utilize the INV4 pallet, users must first create a core and receive initial voting tokens. Cores can propose actions, vote on proposals, and execute decisions based on the collective voting power of their members. The pallet's flexible design supports a wide range of multisig use cases, from simple governance decisions to complex, conditional executions. diff --git a/pallets/INV4/pallet-inv4/src/account_derivation.rs b/pallets/INV4/pallet-inv4/src/account_derivation.rs new file mode 100644 index 00000000..a9a0e4cb --- /dev/null +++ b/pallets/INV4/pallet-inv4/src/account_derivation.rs @@ -0,0 +1,54 @@ +//! Core Account Derivation. +//! +//! ## Overview +//! +//! This module defines a method for generating account addresses, and how it's implemented within this +//! pallet. We use a custom derivation scheme to ensure that when a multisig is created, its AccountId +//! remains consistent across different parachains, promoting seamless interaction. +//! +//! ### The module contains: +//! - `CoreAccountDerivation` trait: The interface for our derivation method. +//! - Pallet implementation: The specific logic used to derive AccountIds. + +use crate::{Config, Pallet}; +use codec::{Compact, Encode}; +use frame_support::traits::Get; +use sp_io::hashing::blake2_256; +use xcm::v3::{BodyId, BodyPart, Junction, Junctions}; +/// Trait providing the XCM location and the derived account of a core. +pub trait CoreAccountDerivation { + /// Derives the core's AccountId. + fn derive_core_account(core_id: T::CoreId) -> T::AccountId; + /// Specifies a core's location. + fn core_location(core_id: T::CoreId) -> Junctions; +} + +impl CoreAccountDerivation for Pallet +where + T::AccountId: From<[u8; 32]>, +{ + /// HashedDescription of the core location from the perspective of a sibling chain. + /// This derivation allows the local account address to match the account address in other parachains. + /// Reference: https://github.com/paritytech/polkadot-sdk/blob/master/polkadot/xcm/xcm-builder/src/location_conversion.rs + fn derive_core_account(core_id: T::CoreId) -> T::AccountId { + blake2_256( + &( + b"SiblingChain", + Compact::::from(T::ParaId::get()), + (b"Body", BodyId::Index(core_id.into()), BodyPart::Voice).encode(), + ) + .encode(), + ) + .into() + } + /// Core location is defined as a plurality within the parachain. + fn core_location(core_id: T::CoreId) -> Junctions { + Junctions::X2( + Junction::Parachain(T::ParaId::get()), + Junction::Plurality { + id: BodyId::Index(core_id.into()), + part: BodyPart::Voice, + }, + ) + } +} diff --git a/pallets/INV4/pallet-inv4/src/benchmarking.rs b/pallets/INV4/pallet-inv4/src/benchmarking.rs new file mode 100644 index 00000000..2e0bb5db --- /dev/null +++ b/pallets/INV4/pallet-inv4/src/benchmarking.rs @@ -0,0 +1,334 @@ +#![cfg(feature = "runtime-benchmarks")] + +use super::*; +use crate::{ + fee_handling::FeeAsset, + multisig::MAX_SIZE, + origin::{INV4Origin, MultisigInternalOrigin}, + voting::{Tally, Vote}, + BalanceOf, +}; +use core::convert::TryFrom; +use frame_benchmarking::{account, benchmarks, whitelisted_caller}; +use frame_support::{ + dispatch::PostDispatchInfo, + pallet_prelude::DispatchResultWithPostInfo, + traits::{Currency, Get}, + BoundedBTreeMap, BoundedVec, +}; +use frame_system::RawOrigin as SystemOrigin; +use sp_runtime::{ + traits::{Bounded, Hash, Zero}, + DispatchError, DispatchErrorWithPostInfo, Perbill, +}; +use sp_std::{ + collections::btree_map::BTreeMap, convert::TryInto, iter::Sum, ops::Div, prelude::*, vec, +}; + +use crate::Pallet as INV4; + +const SEED: u32 = 0; + +fn assert_last_event(generic_event: ::RuntimeEvent) { + frame_system::Pallet::::assert_last_event(generic_event.into()); +} + +fn perbill_one() -> Perbill { + Perbill::one() +} + +fn derive_account(core_id: T::CoreId) -> T::AccountId +where + T: Config, + T::AccountId: From<[u8; 32]>, +{ + INV4::::derive_core_account(core_id) +} + +fn mock_core() -> DispatchResultWithPostInfo +where + Result, ::RuntimeOrigin>: + From<::RuntimeOrigin>, + <::Currency as Currency<::AccountId>>::Balance: + Sum, + T::AccountId: From<[u8; 32]>, +{ + T::Currency::make_free_balance_be( + &whitelisted_caller(), + T::CoreCreationFee::get() + T::CoreCreationFee::get(), + ); + + INV4::::create_core( + SystemOrigin::Signed(whitelisted_caller()).into(), + vec![].try_into().unwrap(), + perbill_one(), + perbill_one(), + FeeAsset::Native, + ) +} + +fn mock_mint() -> Result<(), DispatchError> +where + Result, ::RuntimeOrigin>: + From<::RuntimeOrigin>, + <::Currency as Currency<::AccountId>>::Balance: + Sum, + ::RuntimeOrigin: From>, + T::AccountId: From<[u8; 32]>, +{ + INV4::::token_mint( + INV4Origin::Multisig(MultisigInternalOrigin::new(0u32.into())).into(), + BalanceOf::::max_value().div(4u32.into()), + account("target", 0, SEED), + ) +} + +fn mock_mint_2() -> Result<(), DispatchError> +where + Result, ::RuntimeOrigin>: + From<::RuntimeOrigin>, + <::Currency as Currency<::AccountId>>::Balance: + Sum, + ::RuntimeOrigin: From>, + T::AccountId: From<[u8; 32]>, +{ + INV4::::token_mint( + INV4Origin::Multisig(MultisigInternalOrigin::new(0u32.into())).into(), + BalanceOf::::max_value().div(4u32.into()), + account("target1", 1, SEED + 1), + ) +} + +fn mock_call() -> Result> +where + Result, ::RuntimeOrigin>: + From<::RuntimeOrigin>, + <::Currency as Currency<::AccountId>>::Balance: + Sum, + ::RuntimeOrigin: From>, + T::AccountId: From<[u8; 32]>, +{ + INV4::::operate_multisig( + SystemOrigin::Signed(whitelisted_caller()).into(), + 0u32.into(), + None, + FeeAsset::Native, + Box::new(frame_system::Call::::remark { remark: vec![0] }.into()), + ) +} + +fn mock_vote() -> Result> +where + Result, ::RuntimeOrigin>: + From<::RuntimeOrigin>, + <::Currency as Currency<::AccountId>>::Balance: + Sum, + ::RuntimeOrigin: From>, + T::AccountId: From<[u8; 32]>, +{ + let call: ::RuntimeCall = + frame_system::Call::::remark { remark: vec![0] }.into(); + let call_hash = <::Hashing as Hash>::hash_of(&call.clone()); + + INV4::::vote_multisig( + SystemOrigin::Signed(account("target", 0, SEED)).into(), + 0u32.into(), + call_hash, + true, + ) +} + +benchmarks! { + + where_clause { + where + Result< + INV4Origin, + ::RuntimeOrigin, + >: From<::RuntimeOrigin>, + <::Currency as Currency<::AccountId>>::Balance: Sum, + ::RuntimeOrigin: From>, + T::AccountId: From<[u8; 32]>, +} + + create_core { + let m in 0 .. T::MaxMetadata::get(); + + let metadata: BoundedVec = vec![u8::MAX; m as usize].try_into().unwrap(); + let caller = whitelisted_caller(); + let minimum_support = perbill_one(); + let required_approval = perbill_one(); + let creation_fee_asset = FeeAsset::Native; + + T::Currency::make_free_balance_be(&caller, T::CoreCreationFee::get() + T::CoreCreationFee::get()); + }: _(SystemOrigin::Signed(caller.clone()), metadata.clone(), minimum_support, required_approval, creation_fee_asset) + verify { + assert_last_event::(Event::CoreCreated { + core_account: derive_account::(0u32.into()), + core_id: 0u32.into(), + metadata: metadata.to_vec(), + minimum_support, + required_approval + }.into()); + } + + set_parameters { + let m in 0 .. T::MaxMetadata::get(); + + mock_core().unwrap(); + + let metadata: Option> = Some(vec![u8::MAX; m as usize].try_into().unwrap()); + let minimum_support = Some(perbill_one()); + let required_approval = Some(perbill_one()); + let frozen_tokens = Some(true); + + }: _(INV4Origin::Multisig(MultisigInternalOrigin::new(0u32.into())), metadata.clone(), minimum_support, required_approval, frozen_tokens) + verify { + assert_last_event::(Event::ParametersSet { + core_id: 0u32.into(), + metadata: metadata.map(|m| m.to_vec()), + minimum_support, + required_approval, + frozen_tokens + }.into()); + } + + token_mint { + mock_core().unwrap(); + + let amount = BalanceOf::::max_value().div(2u32.into()); + let target: T::AccountId = account("target", 0, SEED); + + }: _(INV4Origin::Multisig(MultisigInternalOrigin::new(0u32.into())), amount, target.clone()) + verify { + assert_last_event::(Event::Minted { + core_id: 0u32.into(), + target, + amount + }.into()); + } + + token_burn { + mock_core().unwrap(); + mock_mint().unwrap(); + + let amount = BalanceOf::::max_value().div(4u32.into()); + let target: T::AccountId = account("target", 0, SEED); + + }: _(INV4Origin::Multisig(MultisigInternalOrigin::new(0u32.into())), amount, target.clone()) + verify { + assert_last_event::(Event::Burned { + core_id: 0u32.into(), + target, + amount + }.into()); + } + + operate_multisig { + let m in 0 .. T::MaxMetadata::get(); + let z in 0 .. (MAX_SIZE - 10); + + mock_core().unwrap(); + mock_mint().unwrap(); + + let call: ::RuntimeCall = frame_system::Call::::remark { + remark: vec![0; z as usize] + }.into(); + + let metadata: BoundedVec = vec![u8::MAX; m as usize].try_into().unwrap(); + let caller: T::AccountId = whitelisted_caller(); + let core_id: T::CoreId = 0u32.into(); + let call_hash = <::Hashing as Hash>::hash_of(&call.clone()); + let fee_asset = FeeAsset::Native; + + }: _(SystemOrigin::Signed(caller.clone()), core_id, Some(metadata), fee_asset, Box::new(call.clone())) + verify { + assert_last_event::(Event::MultisigVoteStarted { + core_id, + executor_account: derive_account::(core_id), + voter: caller, + votes_added: Vote::Aye(T::CoreSeedBalance::get()), + call_hash, + }.into()); + } + + vote_multisig { + mock_core().unwrap(); + mock_mint().unwrap(); + mock_mint_2().unwrap(); + mock_call().unwrap(); + + let caller: T::AccountId = account("target", 0, SEED); + let core_id: T::CoreId = 0u32.into(); + let call: ::RuntimeCall = frame_system::Call::::remark { + remark: vec![0] + }.into(); + let call_hash = <::Hashing as Hash>::hash_of(&call.clone()); + + }: _(SystemOrigin::Signed(caller.clone()), core_id, call_hash, true) + verify { + assert_last_event::(Event::MultisigVoteAdded { + core_id, + executor_account: derive_account::(core_id), + voter: caller.clone(), + votes_added: Vote::Aye(BalanceOf::::max_value().div(4u32.into())), + current_votes: Tally::::from_parts( + (BalanceOf::::max_value().div(4u32.into()) + T::CoreSeedBalance::get()).into(), + Zero::zero(), + BoundedBTreeMap::try_from(BTreeMap::from([( + whitelisted_caller(), + Vote::Aye(T::CoreSeedBalance::get()), + ), + (caller, Vote::Aye(BalanceOf::::max_value().div(4u32.into()))) + ])).unwrap() + ), + call_hash, + }.into()); + } + + withdraw_vote_multisig { + mock_core().unwrap(); + mock_mint().unwrap(); + mock_mint_2().unwrap(); + mock_call().unwrap(); + mock_vote().unwrap(); + + let caller: T::AccountId = account("target", 0, SEED); + let core_id: T::CoreId = 0u32.into(); + let call: ::RuntimeCall = frame_system::Call::::remark { + remark: vec![0] + }.into(); + let call_hash = <::Hashing as Hash>::hash_of(&call.clone()); + + }: _(SystemOrigin::Signed(caller.clone()), core_id, call_hash) + verify { + assert_last_event::(Event::MultisigVoteWithdrawn { + core_id, + executor_account: derive_account::(core_id), + voter: caller, + votes_removed: Vote::Aye(BalanceOf::::max_value().div(4u32.into())), + call_hash, + }.into()); + } + + cancel_multisig_proposal { + mock_core().unwrap(); + mock_mint().unwrap(); + mock_mint_2().unwrap(); + mock_call().unwrap(); + + let caller: T::AccountId = account("target", 0, SEED); + let core_id: T::CoreId = 0u32.into(); + let call: ::RuntimeCall = frame_system::Call::::remark { + remark: vec![0] + }.into(); + let call_hash = <::Hashing as Hash>::hash_of(&call.clone()); + + }: _(INV4Origin::Multisig(MultisigInternalOrigin::new(0u32.into())), call_hash) + verify { + assert_last_event::(Event::MultisigCanceled { + core_id, + call_hash, + }.into()); + } +} diff --git a/pallets/INV4/pallet-inv4/src/dispatch.rs b/pallets/INV4/pallet-inv4/src/dispatch.rs new file mode 100644 index 00000000..8721faee --- /dev/null +++ b/pallets/INV4/pallet-inv4/src/dispatch.rs @@ -0,0 +1,63 @@ +//! Dispatches calls internally, charging fees to the multisig account. +//! +//! ## Overview +//! +//! This module employs a custom `MultisigInternalOrigin` to ensure calls originate +//! from the multisig account itself, automating fee payments. The `dispatch_call` function +//! includes pre and post dispatch handling for streamlined fee management within the multisig context. + +use crate::{ + fee_handling::{FeeAsset, MultisigFeeHandler}, + origin::{INV4Origin, MultisigInternalOrigin}, + Config, Error, +}; +use frame_support::{dispatch::GetDispatchInfo, pallet_prelude::*}; + +use sp_runtime::traits::Dispatchable; + +/// Dispatch a call executing pre/post dispatch for proper fee handling. +pub fn dispatch_call( + core_id: ::CoreId, + fee_asset: &FeeAsset, + call: ::RuntimeCall, +) -> DispatchResultWithPostInfo +where + T::AccountId: From<[u8; 32]>, +{ + // Create new custom origin as the multisig. + let internal_origin = MultisigInternalOrigin::new(core_id); + let multisig_account = internal_origin.to_account_id(); + let origin = INV4Origin::Multisig(internal_origin).into(); + + let info = call.get_dispatch_info(); + let len = call.encode().len(); + + // Execute pre dispatch using the multisig account instead of the extrinsic caller. + let pre = >::pre_dispatch( + fee_asset, + &multisig_account, + &call, + &info, + len, + ) + .map_err(|_| Error::::CallFeePaymentFailed)?; + + let dispatch_result = call.dispatch(origin); + + let post = match dispatch_result { + Ok(p) => p, + Err(e) => e.post_info, + }; + + >::post_dispatch( + fee_asset, + Some(pre), + &info, + &post, + len, + &dispatch_result.map(|_| ()).map_err(|e| e.error), + ) + .map_err(|_| Error::::CallFeePaymentFailed)?; + + dispatch_result +} diff --git a/pallets/INV4/pallet-inv4/src/fee_handling.rs b/pallets/INV4/pallet-inv4/src/fee_handling.rs new file mode 100644 index 00000000..abec8cf5 --- /dev/null +++ b/pallets/INV4/pallet-inv4/src/fee_handling.rs @@ -0,0 +1,77 @@ +//! MultisigFeeHandler trait. +//! +//! ## Overview +//! +//! Defines how transaction fees are charged to the multisig account. +//! This trait requires proper runtime implementation to allow the usage of native or non-native assets. + +use crate::Config; +use codec::{Decode, Encode, MaxEncodedLen}; +use frame_support::{ + traits::{fungibles::Credit, Currency}, + unsigned::TransactionValidityError, +}; +use scale_info::TypeInfo; +use sp_runtime::{ + traits::{DispatchInfoOf, PostDispatchInfoOf}, + DispatchResult, +}; + +/// Represents the asset to be used by the multisig for paying transaction fees. +/// +/// This enum defines the assets that can be used to pay for transaction fees. +#[derive(Clone, TypeInfo, Encode, Decode, MaxEncodedLen, Debug, PartialEq, Eq)] +pub enum FeeAsset { + Native, + Relay, +} + +/// Represents a potential negative asset balance incurred during fee payment operations +/// within a multisig context. +/// +/// This enum handles imbalances in either the native token or +/// a relay chain asset used for fees. +/// +/// - `Native(NativeNegativeImbalance)`: Indicates a deficit balance in the chain's native asset. +/// - `Relay(RelayNegativeImbalance)`: Indicates a deficit balance in an asset originating on the relay chain. +/// +/// This enum plays a role in resolving deficit balances in the `MultisigFeeHandler` trait. +pub enum FeeAssetNegativeImbalance { + Native(NativeNegativeImbalance), + Relay(RelayNegativeImbalance), +} + +/// Fee handler trait. +/// +/// This should be implemented properly in the runtime to account for native and non-native assets. +pub trait MultisigFeeHandler { + /// Type returned by `pre_dispatch` - implementation dependent. + type Pre; + + /// Checks if the fee can be paid using the selected asset. + fn pre_dispatch( + asset: &FeeAsset, + who: &T::AccountId, + call: &::RuntimeCall, + info: &DispatchInfoOf<::RuntimeCall>, + len: usize, + ) -> Result; + + /// Charges the call dispatching fee from the multisig directly. + fn post_dispatch( + asset: &FeeAsset, + pre: Option, + info: &DispatchInfoOf<::RuntimeCall>, + post_info: &PostDispatchInfoOf<::RuntimeCall>, + len: usize, + result: &DispatchResult, + ) -> Result<(), TransactionValidityError>; + + /// Charges the fee for creating the core (multisig). + fn handle_creation_fee( + imbalance: FeeAssetNegativeImbalance< + >::NegativeImbalance, + Credit, + >, + ); +} diff --git a/pallets/INV4/pallet-inv4/src/inv4_core.rs b/pallets/INV4/pallet-inv4/src/inv4_core.rs new file mode 100644 index 00000000..37f09abf --- /dev/null +++ b/pallets/INV4/pallet-inv4/src/inv4_core.rs @@ -0,0 +1,161 @@ +//! Core creation and internal management. +//! +//! ## Overview +//! +//! This module handles the mechanics of creating multisigs (referred to as "cores") and their lifecycle management. Key functions include: +//! +//! - `inner_create_core`: Sets up a new core, deriving its AccountId, distributing voting tokens, and handling creation fees. +//! - `inner_set_parameters`: Updates the core's operational rules. +//! - `is_asset_frozen`: Utility function for checking if a core's voting asset is frozen (can't be transferred by the owner). + +use super::pallet::*; +use crate::{ + account_derivation::CoreAccountDerivation, + fee_handling::{FeeAsset, FeeAssetNegativeImbalance, MultisigFeeHandler}, + origin::{ensure_multisig, INV4Origin}, +}; +use frame_support::{ + pallet_prelude::*, + traits::{ + fungibles::{Balanced, Mutate}, + tokens::{Fortitude, Precision, Preservation}, + Currency, ExistenceRequirement, WithdrawReasons, + }, +}; +use frame_system::{ensure_signed, pallet_prelude::*}; +use primitives::CoreInfo; +use sp_arithmetic::traits::{CheckedAdd, One}; +use sp_runtime::Perbill; + +pub type CoreIndexOf = ::CoreId; + +pub type CoreMetadataOf = BoundedVec::MaxMetadata>; + +impl Pallet +where + Result, ::RuntimeOrigin>: + From<::RuntimeOrigin>, + ::AccountId: From<[u8; 32]>, +{ + /// Inner function for the create_core call. + pub(crate) fn inner_create_core( + origin: OriginFor, + metadata: BoundedVec, + minimum_support: Perbill, + required_approval: Perbill, + creation_fee_asset: FeeAsset, + ) -> DispatchResult { + NextCoreId::::try_mutate(|next_id| -> DispatchResult { + let creator = ensure_signed(origin)?; + + // Increment core id counter + let current_id = *next_id; + *next_id = next_id + .checked_add(&One::one()) + .ok_or(Error::::NoAvailableCoreId)?; + + // Derive the account of this core based on the core id + let core_account = Self::derive_core_account(current_id); + + // Mint base amount of voting token to the caller + let seed_balance = ::CoreSeedBalance::get(); + T::AssetsProvider::mint_into(current_id, &creator, seed_balance)?; + + // Build the structure of the new core + // Tokens are set to frozen by default + let info = CoreInfo { + account: core_account.clone(), + metadata: metadata.clone(), + minimum_support, + required_approval, + frozen_tokens: true, + }; + + // Charge creation fee from the caller + T::FeeCharger::handle_creation_fee(match creation_fee_asset { + FeeAsset::Native => { + FeeAssetNegativeImbalance::Native(::Currency::withdraw( + &creator, + T::CoreCreationFee::get(), + WithdrawReasons::TRANSACTION_PAYMENT, + ExistenceRequirement::KeepAlive, + )?) + } + + FeeAsset::Relay => { + FeeAssetNegativeImbalance::Relay(::Tokens::withdraw( + T::RelayAssetId::get(), + &creator, + T::RelayCoreCreationFee::get(), + Precision::Exact, + Preservation::Protect, + Fortitude::Force, + )?) + } + }); + + // Update core storages + CoreStorage::::insert(current_id, info); + CoreByAccount::::insert(core_account.clone(), current_id); + + Self::deposit_event(Event::CoreCreated { + core_account, + metadata: metadata.to_vec(), + core_id: current_id, + minimum_support, + required_approval, + }); + + Ok(()) + }) + } + + /// Inner function for the set_parameters call. + pub(crate) fn inner_set_parameters( + origin: OriginFor, + metadata: Option>, + minimum_support: Option, + required_approval: Option, + frozen_tokens: Option, + ) -> DispatchResult { + let core_origin = ensure_multisig::>(origin)?; + let core_id = core_origin.id; + + CoreStorage::::try_mutate(core_id, |core| { + let mut c = core.take().ok_or(Error::::CoreNotFound)?; + + if let Some(ms) = minimum_support { + c.minimum_support = ms; + } + + if let Some(ra) = required_approval { + c.required_approval = ra; + } + + if let Some(m) = metadata.clone() { + c.metadata = m; + } + + if let Some(f) = frozen_tokens { + c.frozen_tokens = f; + } + + *core = Some(c); + + Self::deposit_event(Event::ParametersSet { + core_id, + metadata: metadata.map(|m| m.to_vec()), + minimum_support, + required_approval, + frozen_tokens, + }); + + Ok(()) + }) + } + + /// Checks if the voting asset is frozen. + pub fn is_asset_frozen(core_id: T::CoreId) -> Option { + CoreStorage::::get(core_id).map(|c| c.frozen_tokens) + } +} diff --git a/pallets/INV4/pallet-inv4/src/lib.rs b/pallets/INV4/pallet-inv4/src/lib.rs new file mode 100644 index 00000000..bdb74eb2 --- /dev/null +++ b/pallets/INV4/pallet-inv4/src/lib.rs @@ -0,0 +1,489 @@ +//! # Pallet INV4 +//! +//! - [`Config`] +//! - [`Call`] +//! - [`Pallet`] +//! +//! ## Overview +//! This pallet handles advanced virtual multisigs (internally called cores). +//! +//! Lower level implementation details of this pallet's calls are contained in separate modules, each of them +//! containing their own docs. +//! +//! ### Pallet Functions +//! +//! - `create_core` - Create a new core +//! - `token_mint` - Mint the core's voting token to a target (called by a core origin) +//! - `token_burn` - Burn the core's voting token from a target (called by a core origin) +//! - `operate_multisig` - Create a new multisig proposal, auto-executing if caller passes execution threshold requirements +//! - `vote_multisig` - Vote on an existing multisig proposal, auto-executing if caller puts vote tally past execution threshold requirements +//! - `withdraw_vote_multisig` - Remove caller's vote from an existing multisig proposal +//! - `cancel_multisig_proposal` - Cancel an existing multisig proposal (called by a core origin) +//! - `set_parameters` - Change core parameters incl. voting thresholds and token freeze state (called by a core origin) + +#![cfg_attr(not(feature = "std"), no_std)] +#![allow(clippy::unused_unit)] +#![allow(clippy::type_complexity)] +#![allow(clippy::too_many_arguments)] + +pub use pallet::*; + +#[cfg(feature = "runtime-benchmarks")] +mod benchmarking; + +#[cfg(test)] +mod tests; + +//pub mod migrations; + +pub mod account_derivation; +mod dispatch; +pub mod fee_handling; +pub mod inv4_core; +mod lookup; +pub mod multisig; +pub mod origin; +pub mod voting; +pub mod weights; + +pub use account_derivation::CoreAccountDerivation; +use fee_handling::FeeAsset; +pub use lookup::INV4Lookup; +pub use weights::WeightInfo; + +#[frame_support::pallet] +pub mod pallet { + use core::iter::Sum; + + use crate::{ + fee_handling::MultisigFeeHandler, + voting::{Tally, VoteRecord}, + }; + + use super::*; + use codec::FullCodec; + use frame_support::{ + dispatch::{GetDispatchInfo, Pays, PostDispatchInfo}, + pallet_prelude::*, + traits::{ + fungibles, + fungibles::{Balanced, Inspect}, + Currency, Get, GetCallMetadata, ReservableCurrency, + }, + transactional, + weights::WeightToFee, + Parameter, + }; + use frame_system::{pallet_prelude::*, RawOrigin}; + use primitives::CoreInfo; + use scale_info::prelude::fmt::Display; + use sp_runtime::{ + traits::{AtLeast32BitUnsigned, Dispatchable, Member}, + Perbill, + }; + use sp_std::{boxed::Box, convert::TryInto, vec::Vec}; + + pub use super::{inv4_core, multisig}; + + use crate::origin::INV4Origin; + + pub type BalanceOf = + <::Currency as Currency<::AccountId>>::Balance; + + pub type CoreInfoOf = + CoreInfo<::AccountId, inv4_core::CoreMetadataOf>; + + pub type CallOf = ::RuntimeCall; + + #[pallet::config] + pub trait Config: frame_system::Config + pallet_balances::Config { + /// Runtime event type + type RuntimeEvent: From> + IsType<::RuntimeEvent>; + /// Integer id type for the core id + type CoreId: Parameter + + Member + + AtLeast32BitUnsigned + + Default + + Copy + + Display + + MaxEncodedLen + + Clone + + Into; + + /// Currency type + type Currency: Currency + ReservableCurrency; + + /// The overarching call type + type RuntimeCall: Parameter + + Dispatchable< + Info = frame_support::dispatch::DispatchInfo, + RuntimeOrigin = ::RuntimeOrigin, + PostInfo = PostDispatchInfo, + > + GetDispatchInfo + + From> + + GetCallMetadata + + FullCodec; + + /// The maximum numbers of caller accounts on a single multisig proposal + #[pallet::constant] + type MaxCallers: Get; + + /// The maximum length of the core metadata and the metadata of multisig proposals + #[pallet::constant] + type MaxMetadata: Get; + + /// The outer `Origin` type. + type RuntimeOrigin: From> + + From<::RuntimeOrigin> + + From::AccountId>>; + + /// Base voting token balance to give callers when creating a core + #[pallet::constant] + type CoreSeedBalance: Get>; + + /// Fee for creating a core in the native token + #[pallet::constant] + type CoreCreationFee: Get>; + + /// Fee for creating a core in the relay token + #[pallet::constant] + type RelayCoreCreationFee: Get< + <::Tokens as Inspect<::AccountId>>::Balance, + >; + + /// Relay token asset id in the runtime + #[pallet::constant] + type RelayAssetId: Get<<::Tokens as Inspect<::AccountId>>::AssetId>; + + /// Provider of assets functionality for the voting tokens + type AssetsProvider: fungibles::Inspect, AssetId = Self::CoreId> + + fungibles::Mutate; + + /// Provider of balance tokens in the runtime + type Tokens: Balanced + Inspect; + + /// Implementation of the fee handler for both core creation fee and multisig call fees + type FeeCharger: MultisigFeeHandler; + + /// ParaId of the parachain, to be used for deriving the core account id + type ParaId: Get; + + /// Maximum size of a multisig proposal call + #[pallet::constant] + type MaxCallSize: Get; + + /// Weight info for dispatchable calls + type WeightInfo: WeightInfo; + + /// Byte to fee conversion provider, from pallet_transaction_payment. + type LengthToFee: WeightToFee>; + } + + /// The current storage version. + const STORAGE_VERSION: StorageVersion = StorageVersion::new(2); + + /// The custom core origin. + #[pallet::origin] + pub type Origin = INV4Origin; + + #[pallet::pallet] + #[pallet::storage_version(STORAGE_VERSION)] + pub struct Pallet(_); + + /// Next available Core ID. + #[pallet::storage] + #[pallet::getter(fn next_core_id)] + pub type NextCoreId = StorageValue<_, T::CoreId, ValueQuery>; + + /// Core info storage. + #[pallet::storage] + #[pallet::getter(fn core_storage)] + pub type CoreStorage = StorageMap<_, Blake2_128Concat, T::CoreId, CoreInfoOf>; + + /// Mapping of account id -> core id. + #[pallet::storage] + #[pallet::getter(fn core_by_account)] + pub type CoreByAccount = StorageMap<_, Blake2_128Concat, T::AccountId, T::CoreId>; + + /// Details of a multisig call. + /// + /// Key: (Core ID, call hash) + #[pallet::storage] + #[pallet::getter(fn multisig)] + pub type Multisig = StorageDoubleMap< + _, + Blake2_128Concat, + T::CoreId, + Blake2_128Concat, + T::Hash, + crate::multisig::MultisigOperationOf, + >; + + /// Stores a list of members for each Core. + /// This storage should be always handled by the runtime and mutated by CoreAssets hooks. + // We make this a StorageDoubleMap so we don't have to bound the list. + #[pallet::storage] + #[pallet::getter(fn core_members)] + pub type CoreMembers = + StorageDoubleMap<_, Blake2_128Concat, T::CoreId, Blake2_128Concat, T::AccountId, ()>; + + #[pallet::event] + #[pallet::generate_deposit(pub(crate) fn deposit_event)] + pub enum Event { + /// A core was created + CoreCreated { + core_account: T::AccountId, + core_id: T::CoreId, + metadata: Vec, + minimum_support: Perbill, + required_approval: Perbill, + }, + + /// A core had parameters changed + ParametersSet { + core_id: T::CoreId, + metadata: Option>, + minimum_support: Option, + required_approval: Option, + frozen_tokens: Option, + }, + + /// A core's voting token was minted + Minted { + core_id: T::CoreId, + target: T::AccountId, + amount: BalanceOf, + }, + + /// A core's voting token was burned + Burned { + core_id: T::CoreId, + target: T::AccountId, + amount: BalanceOf, + }, + + /// A multisig proposal has started, it needs more votes to pass + MultisigVoteStarted { + core_id: T::CoreId, + executor_account: T::AccountId, + voter: T::AccountId, + votes_added: VoteRecord, + call_hash: T::Hash, + }, + + /// A vote was added to an existing multisig proposal + MultisigVoteAdded { + core_id: T::CoreId, + executor_account: T::AccountId, + voter: T::AccountId, + votes_added: VoteRecord, + current_votes: Tally, + call_hash: T::Hash, + }, + + /// A vote was removed from an existing multisig proposal + MultisigVoteWithdrawn { + core_id: T::CoreId, + executor_account: T::AccountId, + voter: T::AccountId, + votes_removed: VoteRecord, + call_hash: T::Hash, + }, + + /// A multisig proposal passed and it's call was executed + MultisigExecuted { + core_id: T::CoreId, + executor_account: T::AccountId, + voter: T::AccountId, + call_hash: T::Hash, + call: CallOf, + result: DispatchResult, + }, + + /// A multisig proposal was cancelled + MultisigCanceled { + core_id: T::CoreId, + call_hash: T::Hash, + }, + } + + /// Errors for INV4 pallet + #[pallet::error] + pub enum Error { + /// No available Core ID + NoAvailableCoreId, + /// Core not found + CoreNotFound, + /// The caller has no permissions in the core + NoPermission, + /// Maximum metadata length exceeded + MaxMetadataExceeded, + /// Maximum amount of callers exceeded + MaxCallersExceeded, + /// Multisig call not found + MultisigCallNotFound, + /// Failed to decode stored multisig call + FailedDecodingCall, + /// Multisig proposal already exists and is being voted on + MultisigCallAlreadyExists, + /// Cannot withdraw a vote on a multisig transaction you have not voted on + NotAVoter, + /// Failed to extract metadata from a call + CallHasTooFewBytes, + /// Incomplete vote cleanup + IncompleteVoteCleanup, + /// Multisig fee payment failed, probably due to lack of funds to pay for fees + CallFeePaymentFailed, + /// Call is too long + MaxCallLengthExceeded, + } + + /// Dispatch functions + #[pallet::call] + impl Pallet + where + Result< + INV4Origin, + ::RuntimeOrigin, + >: From<::RuntimeOrigin>, + <::Currency as Currency<::AccountId>>::Balance: Sum, + ::AccountId: From<[u8; 32]>, + { + /// Create a new core + /// - `metadata`: Arbitrary byte vec to be attached to the core info + /// - `minimum_support`: Minimum amount of positive votes out of total token supply required to approve a proposal + /// - `required_approval`: Minimum amount of positive votes out of current positive + negative votes required to approve a proposal + /// - `creation_fee_asset`: Token to be used to pay the core creation fee + #[pallet::call_index(0)] + #[transactional] + #[pallet::weight(::WeightInfo::create_core(metadata.len() as u32))] + pub fn create_core( + owner: OriginFor, + metadata: BoundedVec, + minimum_support: Perbill, + required_approval: Perbill, + creation_fee_asset: FeeAsset, + ) -> DispatchResultWithPostInfo { + Pallet::::inner_create_core( + owner, + metadata, + minimum_support, + required_approval, + creation_fee_asset, + )?; + + Ok(PostDispatchInfo { + actual_weight: None, + pays_fee: Pays::No, + }) + } + + /// Mint the core's voting token to a target (called by a core origin) + /// - `amount`: Balance amount + /// - `target`: Account receiving the minted tokens + #[pallet::call_index(1)] + #[pallet::weight(::WeightInfo::token_mint())] + pub fn token_mint( + origin: OriginFor, + amount: BalanceOf, + target: T::AccountId, + ) -> DispatchResult { + Pallet::::inner_token_mint(origin, amount, target) + } + + /// Burn the core's voting token from a target (called by a core origin) + /// - `amount`: Balance amount + /// - `target`: Account having tokens burned + #[pallet::call_index(2)] + #[pallet::weight(::WeightInfo::token_burn())] + pub fn token_burn( + origin: OriginFor, + amount: BalanceOf, + target: T::AccountId, + ) -> DispatchResult { + Pallet::::inner_token_burn(origin, amount, target) + } + + /// Create a new multisig proposal, auto-executing if caller passes execution threshold requirements + /// Fees are calculated using the length of the metadata and the call + /// The proposed call's weight is used internally to charge the multisig instead of the user proposing the call + /// - `core_id`: Id of the core to propose the call in + /// - `metadata`: Arbitrary byte vec to be attached to the proposal + /// - `fee_asset`: Token to be used by the multisig to pay for call fees + /// - `call`: The actual call to be proposed + #[pallet::call_index(3)] + #[pallet::weight( + ::WeightInfo::operate_multisig( + metadata.clone().map(|m| m.len()).unwrap_or(0) as u32, + call.using_encoded(|c| c.len() as u32) + ) + )] + pub fn operate_multisig( + caller: OriginFor, + core_id: T::CoreId, + metadata: Option>, + fee_asset: FeeAsset, + call: Box<::RuntimeCall>, + ) -> DispatchResultWithPostInfo { + Pallet::::inner_operate_multisig(caller, core_id, metadata, fee_asset, call) + } + + /// Vote on an existing multisig proposal, auto-executing if caller puts vote tally past execution threshold requirements + /// - `core_id`: Id of the core where the proposal is + /// - `call_hash`: Hash of the call identifying the proposal + /// - `aye`: Wheter or not to vote positively + #[pallet::call_index(4)] + #[pallet::weight(::WeightInfo::vote_multisig())] + pub fn vote_multisig( + caller: OriginFor, + core_id: T::CoreId, + call_hash: T::Hash, + aye: bool, + ) -> DispatchResultWithPostInfo { + Pallet::::inner_vote_multisig(caller, core_id, call_hash, aye) + } + + /// Remove caller's vote from an existing multisig proposal + /// - `core_id`: Id of the core where the proposal is + /// - `call_hash`: Hash of the call identifying the proposal + #[pallet::call_index(5)] + #[pallet::weight(::WeightInfo::withdraw_vote_multisig())] + pub fn withdraw_vote_multisig( + caller: OriginFor, + core_id: T::CoreId, + call_hash: T::Hash, + ) -> DispatchResultWithPostInfo { + Pallet::::inner_withdraw_vote_multisig(caller, core_id, call_hash) + } + + /// Cancel an existing multisig proposal (called by a core origin) + /// - `call_hash`: Hash of the call identifying the proposal + #[pallet::call_index(6)] + #[pallet::weight(::WeightInfo::cancel_multisig_proposal())] + pub fn cancel_multisig_proposal( + caller: OriginFor, + call_hash: T::Hash, + ) -> DispatchResultWithPostInfo { + Pallet::::inner_cancel_multisig_proposal(caller, call_hash) + } + + /// Change core parameters incl. voting thresholds and token freeze state (called by a core origin) + /// - `metadata`: Arbitrary byte vec to be attached to the core info + /// - `minimum_support`: Minimum amount of positive votes out of total token supply required to approve a proposal + /// - `required_approval`: Minimum amount of positive votes out of current positive + negative votes required to approve a proposal + /// - `frozen_tokens`: Wheter or not the core's voting token should be transferable by the holders + #[pallet::call_index(9)] + #[pallet::weight(::WeightInfo::set_parameters( + metadata.clone().map(|m| m.len()).unwrap_or(0) as u32 + ))] + pub fn set_parameters( + origin: OriginFor, + metadata: Option>, + minimum_support: Option, + required_approval: Option, + frozen_tokens: Option, + ) -> DispatchResult { + Pallet::::inner_set_parameters(origin, metadata, minimum_support, required_approval, frozen_tokens) + } + } +} diff --git a/pallets/INV4/pallet-inv4/src/lookup.rs b/pallets/INV4/pallet-inv4/src/lookup.rs new file mode 100644 index 00000000..901bd670 --- /dev/null +++ b/pallets/INV4/pallet-inv4/src/lookup.rs @@ -0,0 +1,50 @@ +//! Custom account lookup implementation. +//! +//! ## Overview +//! +//! This module implements the [`StaticLookup`] trait allowing for convenient lookup of a core's +//! AccountId from its CoreId. +//! This implementation abstracts on top of two lower level functions: +//! - `lookup_core`: Used for accessing the storage and retrieving a core's AccountId. +//! - `lookup_address`: Used for converting from a `MultiAddress::Index` that contains a CoreId to this core's AccountId. + +use crate::{Config, CoreByAccount, CoreStorage, Pallet}; +use core::marker::PhantomData; +use frame_support::error::LookupError; +use sp_runtime::{traits::StaticLookup, MultiAddress}; + +impl Pallet { + /// Queries `CoreStorage` to retrieve the AccountId of a core. + pub fn lookup_core(core_id: T::CoreId) -> Option { + CoreStorage::::get(core_id).map(|core| core.account) + } + + /// Matches `MultiAddress` to allow for a `MultiAddress::Index` containing a CoreId to be converted + /// to it's derived AccountId. + pub fn lookup_address(a: MultiAddress) -> Option { + match a { + MultiAddress::Id(i) => Some(i), + MultiAddress::Index(i) => Self::lookup_core(i), + _ => None, + } + } +} + +/// StaticLookup implementor using MultiAddress::Index for looking up cores by id. +pub struct INV4Lookup(PhantomData); + +impl StaticLookup for INV4Lookup { + type Source = MultiAddress; + type Target = T::AccountId; + + fn lookup(a: Self::Source) -> Result { + Pallet::::lookup_address(a).ok_or(LookupError) + } + + fn unlookup(a: Self::Target) -> Self::Source { + match CoreByAccount::::get(&a) { + Some(core_id) => MultiAddress::Index(core_id), + None => MultiAddress::Id(a), + } + } +} diff --git a/pallets/INV4/pallet-inv4/src/migrations.rs b/pallets/INV4/pallet-inv4/src/migrations.rs new file mode 100644 index 00000000..eba5c8ad --- /dev/null +++ b/pallets/INV4/pallet-inv4/src/migrations.rs @@ -0,0 +1,126 @@ +use super::*; +use frame_support::{ + dispatch::GetStorageVersion, + traits::{Get, OnRuntimeUpgrade}, + weights::Weight, +}; +use log::{info, warn}; + +pub mod v1 { + + use super::*; + + pub fn clear_storages() { + let _ = frame_support::migration::clear_storage_prefix(b"INV4", b"", b"", None, None); + } + + pub struct MigrateToV1(sp_std::marker::PhantomData); + impl OnRuntimeUpgrade for MigrateToV1 { + #[cfg(feature = "try-runtime")] + fn pre_upgrade() -> Result, &'static str> { + frame_support::ensure!( + Pallet::::current_storage_version() == 0, + "Required v0 before upgrading to v1" + ); + + Ok(Default::default()) + } + + fn on_runtime_upgrade() -> Weight { + let current = Pallet::::current_storage_version(); + + if current == 1 { + clear_storages::(); + + current.put::>(); + + info!("v1 applied successfully"); + T::DbWeight::get().reads_writes(0, 1) + } else { + warn!("Skipping v1, should be removed"); + T::DbWeight::get().reads(1) + } + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade(_state: sp_std::vec::Vec) -> Result<(), &'static str> { + frame_support::ensure!( + Pallet::::on_chain_storage_version() == 1, + "v1 not applied" + ); + + Ok(()) + } + } +} + +pub mod v2 { + use super::*; + use codec::{Decode, Encode}; + use frame_support::{ + pallet_prelude::ValueQuery, storage_alias, Blake2_128Concat, Twox64Concat, + }; + + #[derive(Default, Encode, Decode)] + pub struct AccountData { + pub free: Balance, + pub reserved: Balance, + pub frozen: Balance, + } + + #[storage_alias] + pub type Accounts = + StorageDoubleMap< + orml_tokens2::Pallet, + Blake2_128Concat, + ::AccountId, + Twox64Concat, + ::CoreId, + AccountData, + ValueQuery, + >; + + pub fn fill_core_owners() { + Accounts::::iter_keys() + .for_each(|(member, core_id)| CoreMembers::::insert(core_id, member, ())); + } + + pub struct MigrateToV2(sp_std::marker::PhantomData); + impl OnRuntimeUpgrade for MigrateToV2 { + #[cfg(feature = "try-runtime")] + fn pre_upgrade() -> Result, &'static str> { + frame_support::ensure!( + Pallet::::current_storage_version() == 1, + "Required v1 before upgrading to v2" + ); + + Ok(Default::default()) + } + + fn on_runtime_upgrade() -> Weight { + let current = Pallet::::current_storage_version(); + + if current == 2 { + fill_core_owners::(); + + current.put::>(); + + info!("v2 applied successfully"); + T::DbWeight::get().reads_writes(0, 1) + } else { + warn!("Skipping v1, should be removed"); + T::DbWeight::get().reads(1) + } + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade(_state: sp_std::vec::Vec) -> Result<(), &'static str> { + frame_support::ensure!( + Pallet::::on_chain_storage_version() == 2, + "v2 not applied" + ); + + Ok(()) + } + } +} diff --git a/pallets/INV4/pallet-inv4/src/multisig.rs b/pallets/INV4/pallet-inv4/src/multisig.rs new file mode 100644 index 00000000..6689c5e9 --- /dev/null +++ b/pallets/INV4/pallet-inv4/src/multisig.rs @@ -0,0 +1,358 @@ +//! Multisig Operations. +//! +//! ## Overview +//! +//! Handles the core actions within an already established multisig. +//! +//! ### Core functionalities: +//! - Minting/Burning voting tokens to existing and new members. +//! - Handling proposal votes. +//! - Dispatching approved proposals when both support and approval meet/exceed their minimum required thresholds. +//! - Canceling proposals. + +use super::pallet::{self, *}; +use crate::{ + account_derivation::CoreAccountDerivation, + fee_handling::{FeeAsset, FeeAssetNegativeImbalance, MultisigFeeHandler}, + origin::{ensure_multisig, INV4Origin}, + voting::{Tally, Vote}, +}; +use codec::DecodeLimit; +use core::{ + convert::{TryFrom, TryInto}, + iter::Sum, +}; +use frame_support::{ + pallet_prelude::*, + traits::{ + fungibles::{Inspect, Mutate}, + tokens::{Fortitude, Precision}, + Currency, ExistenceRequirement, VoteTally, WithdrawReasons, + }, + weights::WeightToFee, + BoundedBTreeMap, +}; +use frame_system::{ensure_signed, pallet_prelude::*}; +use sp_runtime::{ + traits::{Hash, Zero}, + Perbill, +}; +use sp_std::{boxed::Box, collections::btree_map::BTreeMap}; + +/// Maximum size of call we store is 50kb. +pub const MAX_SIZE: u32 = 50 * 1024; + +pub type BoundedCallBytes = BoundedVec::MaxCallSize>; + +/// Details of a multisig operation. +#[derive(Clone, Encode, Decode, RuntimeDebug, MaxEncodedLen, TypeInfo, PartialEq, Eq)] +pub struct MultisigOperation { + pub tally: TallyOf, + pub original_caller: AccountId, + pub actual_call: Call, + pub metadata: Option, + pub fee_asset: FeeAsset, +} + +pub type MultisigOperationOf = MultisigOperation< + ::AccountId, + Tally, + BoundedCallBytes, + BoundedVec::MaxMetadata>, +>; + +impl Pallet +where + Result, ::RuntimeOrigin>: + From<::RuntimeOrigin>, + <::Currency as Currency<::AccountId>>::Balance: Sum, + ::AccountId: From<[u8; 32]>, +{ + /// Inner function for the token_mint call. + pub(crate) fn inner_token_mint( + origin: OriginFor, + amount: BalanceOf, + target: T::AccountId, + ) -> DispatchResult { + // Grab the core id from the origin + let core_origin = ensure_multisig::>(origin)?; + let core_id = core_origin.id; + + // Mint the core's voting token to the target. + T::AssetsProvider::mint_into(core_id, &target, amount)?; + + Self::deposit_event(Event::Minted { + core_id, + target, + amount, + }); + + Ok(()) + } + + /// Inner function for the token_burn call. + pub(crate) fn inner_token_burn( + origin: OriginFor, + amount: BalanceOf, + target: T::AccountId, + ) -> DispatchResult { + // Grab the core id from the origin + let core_origin = ensure_multisig::>(origin)?; + let core_id = core_origin.id; + + // Burn the core's voting token from the target. + T::AssetsProvider::burn_from( + core_id, + &target, + amount, + Precision::Exact, + Fortitude::Polite, + )?; + + Self::deposit_event(Event::Burned { + core_id, + target, + amount, + }); + + Ok(()) + } + + /// Inner function for the operate_multisig call. + pub(crate) fn inner_operate_multisig( + caller: OriginFor, + core_id: T::CoreId, + metadata: Option>, + fee_asset: FeeAsset, + call: Box<::RuntimeCall>, + ) -> DispatchResultWithPostInfo { + let owner = ensure_signed(caller)?; + + // Get the voting token balance of the caller + let owner_balance: BalanceOf = T::AssetsProvider::balance(core_id, &owner); + + ensure!(!owner_balance.is_zero(), Error::::NoPermission); + + // Get the minimum support value of the target core + let (minimum_support, _) = Pallet::::minimum_support_and_required_approval(core_id) + .ok_or(Error::::CoreNotFound)?; + + // Get the total issuance of the core's voting token + let total_issuance: BalanceOf = T::AssetsProvider::total_issuance(core_id); + + // Compute the call hash + let call_hash = <::Hashing as Hash>::hash_of(&call); + + // Make sure this exact multisig call doesn't already exist + ensure!( + Multisig::::get(core_id, call_hash).is_none(), + Error::::MultisigCallAlreadyExists + ); + + // If caller has enough balance to meet/exeed the threshold, then go ahead and execute the call now + // There is no need to check against required_approval as it's assumed the caller is voting aye + if Perbill::from_rational(owner_balance, total_issuance) >= minimum_support { + let dispatch_result = + crate::dispatch::dispatch_call::(core_id, &fee_asset, *call.clone()); + + Self::deposit_event(Event::MultisigExecuted { + core_id, + executor_account: Self::derive_core_account(core_id), + voter: owner, + call_hash, + call: *call, + result: dispatch_result.map(|_| ()).map_err(|e| e.error), + }); + } else { + // Wrap the call making sure it fits the size boundary + let bounded_call: BoundedCallBytes = (*call) + .encode() + .try_into() + .map_err(|_| Error::::MaxCallLengthExceeded)?; + + let total_lenght = (bounded_call.len() as u64) + .saturating_add(metadata.clone().unwrap_or_default().len() as u64); + + let storage_cost: BalanceOf = + T::LengthToFee::weight_to_fee(&Weight::from_parts(total_lenght as u64, 0)); + + T::FeeCharger::handle_creation_fee(FeeAssetNegativeImbalance::Native( + ::Currency::withdraw( + &owner, + storage_cost, + WithdrawReasons::TRANSACTION_PAYMENT, + ExistenceRequirement::KeepAlive, + )?, + )); + + // Insert proposal in storage, it's now in the voting stage + Multisig::::insert( + core_id, + call_hash, + MultisigOperation { + tally: Tally::from_parts( + owner_balance, + Zero::zero(), + BoundedBTreeMap::try_from(BTreeMap::from([( + owner.clone(), + Vote::Aye(owner_balance), + )])) + .map_err(|_| Error::::MaxCallersExceeded)?, + ), + original_caller: owner.clone(), + actual_call: bounded_call, + metadata, + fee_asset, + }, + ); + + Self::deposit_event(Event::MultisigVoteStarted { + core_id, + executor_account: Self::derive_core_account(core_id), + voter: owner, + votes_added: Vote::Aye(owner_balance), + call_hash, + }); + } + + Ok(().into()) + } + + /// Inner function for the vote_multisig call. + pub(crate) fn inner_vote_multisig( + caller: OriginFor, + core_id: T::CoreId, + call_hash: T::Hash, + aye: bool, + ) -> DispatchResultWithPostInfo { + Multisig::::try_mutate_exists(core_id, call_hash, |data| { + let owner = ensure_signed(caller.clone())?; + + // Get the voting token balance of the caller + let voter_balance: BalanceOf = T::AssetsProvider::balance(core_id, &owner); + + // If caller doesn't own the token, they have no voting power. + ensure!(!voter_balance.is_zero(), Error::::NoPermission); + + // Get the multisig call data from the storage + let mut old_data = data.take().ok_or(Error::::MultisigCallNotFound)?; + + // Get the minimum support and required approval values of the target core + let (minimum_support, required_approval) = + Pallet::::minimum_support_and_required_approval(core_id) + .ok_or(Error::::CoreNotFound)?; + + let new_vote_record = if aye { + Vote::Aye(voter_balance) + } else { + Vote::Nay(voter_balance) + }; + + // Mutate tally with the new vote + old_data + .tally + .process_vote(owner.clone(), Some(new_vote_record))?; + + let support = old_data.tally.support(core_id); + let approval = old_data.tally.approval(core_id); + + // Check if the multisig proposal passes the thresholds with the added vote + if (support >= minimum_support) && (approval >= required_approval) { + // Decode the call + let decoded_call = ::RuntimeCall::decode_all_with_depth_limit( + sp_api::MAX_EXTRINSIC_DEPTH / 4, + &mut &old_data.actual_call[..], + ) + .map_err(|_| Error::::FailedDecodingCall)?; + + // If the proposal thresholds are met, remove proposal from storage + *data = None; + + // Dispatch the call and get the result + let dispatch_result = crate::dispatch::dispatch_call::( + core_id, + &old_data.fee_asset, + decoded_call.clone(), + ); + + Self::deposit_event(Event::MultisigExecuted { + core_id, + executor_account: Self::derive_core_account(core_id), + voter: owner, + call_hash, + call: decoded_call, + result: dispatch_result.map(|_| ()).map_err(|e| e.error), + }); + } else { + // If the thresholds aren't met, update storage with the new tally + *data = Some(old_data.clone()); + + Self::deposit_event(Event::MultisigVoteAdded { + core_id, + executor_account: Self::derive_core_account(core_id), + voter: owner, + votes_added: new_vote_record, + current_votes: old_data.tally, + call_hash, + }); + } + + Ok(().into()) + }) + } + + /// Inner function for the withdraw_token_multisig call. + pub(crate) fn inner_withdraw_vote_multisig( + caller: OriginFor, + core_id: T::CoreId, + call_hash: T::Hash, + ) -> DispatchResultWithPostInfo { + Multisig::::try_mutate_exists(core_id, call_hash, |data| { + let owner = ensure_signed(caller.clone())?; + + // Get the voting token balance of the caller + let mut old_data = data.take().ok_or(Error::::MultisigCallNotFound)?; + + // Try to mutate tally to remove the vote + let old_vote = old_data.tally.process_vote(owner.clone(), None)?; + + // Update storage with the new tally + *data = Some(old_data.clone()); + + Self::deposit_event(Event::MultisigVoteWithdrawn { + core_id, + executor_account: Self::derive_core_account(core_id), + voter: owner, + votes_removed: old_vote, + call_hash, + }); + + Ok(().into()) + }) + } + + /// Inner function for the cancel_multisig_proposal call. + pub(crate) fn inner_cancel_multisig_proposal( + origin: OriginFor, + call_hash: T::Hash, + ) -> DispatchResultWithPostInfo { + // Ensure that this is being called by the multisig origin rather than by a normal caller + let core_origin = ensure_multisig::>(origin)?; + let core_id = core_origin.id; + + // Remove the proposal from storage + Multisig::::remove(core_id, call_hash); + + Self::deposit_event(Event::::MultisigCanceled { core_id, call_hash }); + + Ok(().into()) + } + + pub fn add_member(core_id: &T::CoreId, member: &T::AccountId) { + CoreMembers::::insert(core_id, member, ()) + } + + pub fn remove_member(core_id: &T::CoreId, member: &T::AccountId) { + CoreMembers::::remove(core_id, member) + } +} diff --git a/pallets/INV4/pallet-inv4/src/origin.rs b/pallets/INV4/pallet-inv4/src/origin.rs new file mode 100644 index 00000000..39a2328b --- /dev/null +++ b/pallets/INV4/pallet-inv4/src/origin.rs @@ -0,0 +1,56 @@ +//! Custom Multisig Origin (`INV4Origin`). +//! +//! ## Overview +//! +//! This module introduces a custom origin [`INV4Origin`], enabling self-management for cores and +//! includes the [`ensure_multisig`] function to guarantee calls genuinely come from the multisig account. +//! This is an efficient approach considering that converting from CoreId to AccountId is a one-way operation, +//! so the origin brings the CoreId to dispatchable calls. +//! Converting to a `RawOrigin::Signed` origin for other calls is handled in the runtime. + +use crate::{ + account_derivation::CoreAccountDerivation, + pallet::{self, Origin, Pallet}, + Config, +}; +use codec::{Decode, Encode, MaxEncodedLen}; +use frame_support::{error::BadOrigin, pallet_prelude::RuntimeDebug}; +use scale_info::TypeInfo; + +/// Origin representing a core by its id. +#[derive(PartialEq, Eq, Encode, Decode, TypeInfo, MaxEncodedLen, Clone, RuntimeDebug)] +pub enum INV4Origin { + Multisig(MultisigInternalOrigin), +} + +/// Internal origin for identifying the multisig CoreId. +#[derive(PartialEq, Eq, Encode, Decode, TypeInfo, MaxEncodedLen, Clone, RuntimeDebug)] +pub struct MultisigInternalOrigin { + pub id: T::CoreId, +} + +impl MultisigInternalOrigin +where + T::AccountId: From<[u8; 32]>, +{ + pub fn new(id: T::CoreId) -> Self { + Self { id } + } + + pub fn to_account_id(&self) -> T::AccountId { + Pallet::::derive_core_account(self.id) + } +} + +/// Ensures the passed origin is a multisig, returning [`MultisigInternalOrigin`]. +pub fn ensure_multisig( + o: OuterOrigin, +) -> Result, BadOrigin> +where + OuterOrigin: Into, OuterOrigin>>, +{ + match o.into() { + Ok(Origin::::Multisig(internal)) => Ok(internal), + _ => Err(BadOrigin), + } +} diff --git a/pallets/INV4/pallet-inv4/src/tests/mock.rs b/pallets/INV4/pallet-inv4/src/tests/mock.rs new file mode 100644 index 00000000..e391a184 --- /dev/null +++ b/pallets/INV4/pallet-inv4/src/tests/mock.rs @@ -0,0 +1,436 @@ +use crate::{fee_handling::*, *}; +use codec::{Decode, Encode}; +use core::convert::TryFrom; +use frame_support::{ + derive_impl, parameter_types, + traits::{ + fungibles::Credit, ConstU128, ConstU32, ConstU64, Contains, Currency, EnsureOrigin, + EnsureOriginWithArg, + }, + weights::ConstantMultiplier, +}; +use frame_system::EnsureRoot; +use orml_asset_registry::AssetMetadata; +use pallet_balances::AccountData; +use scale_info::TypeInfo; +use sp_core::H256; +use sp_runtime::{AccountId32, BuildStorage}; +use sp_std::{convert::TryInto, vec}; + +type Block = frame_system::mocking::MockBlock; +type Balance = u128; + +type AccountId = AccountId32; + +pub const EXISTENTIAL_DEPOSIT: Balance = 1_000_000_000; + +pub const ALICE: AccountId = AccountId::new([0u8; 32]); +pub const BOB: AccountId = AccountId::new([1u8; 32]); +pub const CHARLIE: AccountId = AccountId::new([2u8; 32]); +pub const DAVE: AccountId = AccountId::new([3u8; 32]); + +frame_support::construct_runtime!( + pub enum Test + { + System: frame_system, + Balances: pallet_balances, + Tokens: orml_tokens, + AssetRegistry: orml_asset_registry, + CoreAssets: orml_tokens2, + INV4: pallet, + } +); + +pub struct TestBaseCallFilter; +impl Contains for TestBaseCallFilter { + fn contains(_c: &RuntimeCall) -> bool { + true + } +} + +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +impl frame_system::Config for Test { + type RuntimeOrigin = RuntimeOrigin; + type Nonce = u64; + type RuntimeCall = RuntimeCall; + type Hash = H256; + type Hashing = ::sp_runtime::traits::BlakeTwo256; + type AccountId = AccountId; + type Lookup = sp_runtime::traits::IdentityLookup; + type Block = Block; + type RuntimeEvent = RuntimeEvent; + type BlockHashCount = ConstU64<250>; + type BlockWeights = (); + type BlockLength = (); + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type DbWeight = (); + type BaseCallFilter = TestBaseCallFilter; + type SystemWeightInfo = (); + type SS58Prefix = (); + type OnSetCode = (); + type MaxConsumers = ConstU32<16>; +} + +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig as pallet_balances::DefaultConfig)] +impl pallet_balances::Config for Test { + type MaxLocks = ConstU32<50>; + type Balance = Balance; + type RuntimeEvent = RuntimeEvent; + type ExistentialDeposit = ConstU128; + type AccountStore = System; + type MaxReserves = ConstU32<50>; + type ReserveIdentifier = [u8; 8]; + type MaxFreezes = ConstU32<1>; +} + +const UNIT: u128 = 1000000000000; +const MICROUNIT: Balance = 1_000_000; + +pub struct CoreDustRemovalWhitelist; +impl Contains for CoreDustRemovalWhitelist { + fn contains(_: &AccountId) -> bool { + true + } +} + +pub struct DisallowIfFrozen; +impl + orml_traits2::currency::OnTransfer< + ::AccountId, + ::CoreId, + Balance, + > for DisallowIfFrozen +{ + fn on_transfer( + currency_id: ::CoreId, + _from: &AccountId, + _to: &AccountId, + _amount: Balance, + ) -> sp_std::result::Result<(), orml_traits::parameters::sp_runtime::DispatchError> { + if let Some(true) = INV4::is_asset_frozen(currency_id) { + Err(sp_runtime::DispatchError::Token( + sp_runtime::TokenError::Frozen, + )) + } else { + Ok(()) + } + } +} + +pub struct HandleNewMembers; +impl + orml_traits2::Happened<( + ::AccountId, + ::CoreId, + )> for HandleNewMembers +{ + fn happened((member, core_id): &(AccountId, ::CoreId)) { + INV4::add_member(core_id, member) + } +} + +pub struct HandleRemovedMembers; +impl + orml_traits2::Happened<( + ::AccountId, + ::CoreId, + )> for HandleRemovedMembers +{ + fn happened((member, core_id): &(AccountId, ::CoreId)) { + INV4::remove_member(core_id, member) + } +} + +pub struct INV4TokenHooks; +impl + orml_traits2::currency::MutationHooks< + ::AccountId, + ::CoreId, + Balance, + > for INV4TokenHooks +{ + type PreTransfer = DisallowIfFrozen; + type OnDust = (); + type OnSlash = (); + type PreDeposit = (); + type PostDeposit = (); + type PostTransfer = (); + type OnNewTokenAccount = HandleNewMembers; + type OnKilledTokenAccount = HandleRemovedMembers; +} + +orml_traits2::parameter_type_with_key! { + pub CoreExistentialDeposits: |_currency_id: ::CoreId| -> Balance { + CExistentialDeposit::get() + }; +} + +impl orml_tokens2::Config for Test { + type RuntimeEvent = RuntimeEvent; + type Balance = Balance; + type Amount = i128; + type CurrencyId = ::CoreId; + type WeightInfo = (); + type ExistentialDeposits = CoreExistentialDeposits; + type MaxLocks = ConstU32<0u32>; + type MaxReserves = ConstU32<0u32>; + type DustRemovalWhitelist = CoreDustRemovalWhitelist; + type ReserveIdentifier = [u8; 8]; + type CurrencyHooks = INV4TokenHooks; +} + +parameter_types! { + pub const MaxMetadata: u32 = 10000; + pub const MaxCallers: u32 = 10000; + pub const CoreSeedBalance: Balance = 1000000u128; + pub const CoreCreationFee: Balance = UNIT; + pub const GenesisHash: ::Hash = H256([ + 212, 46, 150, 6, 169, 149, 223, 228, 51, 220, 121, 85, 220, 42, 112, 244, 149, 243, 80, + 243, 115, 218, 162, 0, 9, 138, 232, 68, 55, 129, 106, 210, + ]); + + pub const RelayCoreCreationFee: Balance = UNIT; +} + +pub type AssetId = u32; + +pub const NATIVE_ASSET_ID: AssetId = 0; +pub const RELAY_ASSET_ID: AssetId = 1; + +parameter_types! { + pub const NativeAssetId: AssetId = NATIVE_ASSET_ID; + pub const RelayAssetId: AssetId = RELAY_ASSET_ID; + pub const ExistentialDeposit: u128 = 100000000000; + pub const CExistentialDeposit: u128 = 1; + pub const MaxLocks: u32 = 1; + pub const MaxReserves: u32 = 1; + pub const MaxCallSize: u32 = 50 * 1024; + pub const StringLimit: u32 = 2125; + pub const TransactionByteFee: Balance = 10 * MICROUNIT; + +} + +pub struct AssetAuthority; +impl EnsureOriginWithArg> for AssetAuthority { + type Success = (); + + fn try_origin( + origin: RuntimeOrigin, + _asset_id: &Option, + ) -> Result { + as EnsureOrigin>::try_origin(origin) + } + + fn ensure_origin( + o: RuntimeOrigin, + a: &Option, + ) -> Result { + Self::try_origin(o, a).map_err(|_| sp_runtime::traits::BadOrigin) + } + + #[cfg(feature = "runtime-benchmarks")] + fn try_successful_origin(_o: &Option) -> Result { + Err(()) + } +} + +impl orml_asset_registry::Config for Test { + type RuntimeEvent = RuntimeEvent; + type AuthorityOrigin = AssetAuthority; + type AssetId = AssetId; + type Balance = Balance; + type AssetProcessor = orml_asset_registry::SequentialId; + type CustomMetadata = (); + type WeightInfo = (); + type StringLimit = StringLimit; +} + +pub struct DustRemovalWhitelist; +impl Contains for DustRemovalWhitelist { + fn contains(_: &AccountId) -> bool { + true + } +} + +pub type Amount = i128; + +orml_traits::parameter_type_with_key! { + pub ExistentialDeposits: |currency_id: AssetId| -> Balance { + if currency_id == &RELAY_ASSET_ID { + ExistentialDeposit::get() + } else { + orml_asset_registry::ExistentialDeposits::::get(currency_id) + } + }; +} + +impl orml_tokens::Config for Test { + type RuntimeEvent = RuntimeEvent; + type Balance = Balance; + type Amount = Amount; + type CurrencyId = AssetId; + type WeightInfo = (); + type ExistentialDeposits = ExistentialDeposits; + type MaxLocks = MaxLocks; + type DustRemovalWhitelist = CoreDustRemovalWhitelist; + type MaxReserves = MaxReserves; + type ReserveIdentifier = [u8; 8]; + type CurrencyHooks = (); +} + +#[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo, Debug)] +pub struct FeeCharger; + +impl MultisigFeeHandler for FeeCharger { + type Pre = ( + // tip + Balance, + // who paid the fee + AccountId, + // imbalance resulting from withdrawing the fee + (), + // asset_id for the transaction payment + Option, + ); + + fn pre_dispatch( + fee_asset: &FeeAsset, + who: &AccountId, + _call: &RuntimeCall, + _info: &sp_runtime::traits::DispatchInfoOf, + _len: usize, + ) -> Result { + Ok(( + 0u128, + who.clone(), + (), + match fee_asset { + FeeAsset::Native => None, + FeeAsset::Relay => Some(1u32), + }, + )) + } + + fn post_dispatch( + _fee_asset: &FeeAsset, + _pre: Option, + _info: &sp_runtime::traits::DispatchInfoOf, + _post_info: &sp_runtime::traits::PostDispatchInfoOf, + _len: usize, + _result: &sp_runtime::DispatchResult, + ) -> Result<(), frame_support::unsigned::TransactionValidityError> { + Ok(()) + } + + fn handle_creation_fee( + _imbalance: FeeAssetNegativeImbalance< + >::NegativeImbalance, + Credit, + >, + ) { + } +} + +impl pallet::Config for Test { + type MaxMetadata = MaxMetadata; + type CoreId = u32; + type RuntimeEvent = RuntimeEvent; + type Currency = Balances; + type RuntimeCall = RuntimeCall; + type MaxCallers = MaxCallers; + type CoreSeedBalance = CoreSeedBalance; + type AssetsProvider = CoreAssets; + type RuntimeOrigin = RuntimeOrigin; + type CoreCreationFee = CoreCreationFee; + type FeeCharger = FeeCharger; + type WeightInfo = crate::weights::SubstrateWeight; + + type Tokens = Tokens; + type RelayAssetId = RelayAssetId; + type RelayCoreCreationFee = RelayCoreCreationFee; + + type MaxCallSize = MaxCallSize; + + type ParaId = ConstU32<2125>; + type LengthToFee = ConstantMultiplier; +} + +pub struct ExtBuilder; + +impl Default for ExtBuilder { + fn default() -> Self { + ExtBuilder + } +} + +pub const INITIAL_BALANCE: Balance = 100000000000000000; + +impl ExtBuilder { + pub fn build(self) -> sp_io::TestExternalities { + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); + + pallet_balances::GenesisConfig:: { + balances: vec![ + (ALICE, INITIAL_BALANCE), + (BOB, INITIAL_BALANCE), + (CHARLIE, INITIAL_BALANCE), + (INV4::derive_core_account(0u32), INITIAL_BALANCE), + ], + } + .assimilate_storage(&mut t) + .unwrap(); + + orml_asset_registry::GenesisConfig:: { + assets: vec![ + ( + 0u32, + AssetMetadata { + decimals: 12, + name: sp_core::bounded_vec::BoundedVec::::new(), + symbol: sp_core::bounded_vec::BoundedVec::::new(), + existential_deposit: ExistentialDeposit::get(), + location: None, + additional: (), + } + .encode(), + ), + ( + 1u32, + AssetMetadata { + decimals: 12, + name: sp_core::bounded_vec::BoundedVec::::new(), + symbol: sp_core::bounded_vec::BoundedVec::::new(), + existential_deposit: ExistentialDeposit::get(), + location: None, + additional: (), + } + .encode(), + ), + ], + last_asset_id: 1u32, + } + .assimilate_storage(&mut t) + .unwrap(); + + orml_tokens::GenesisConfig:: { + balances: vec![ + (ALICE, RELAY_ASSET_ID, INITIAL_BALANCE), + (BOB, RELAY_ASSET_ID, INITIAL_BALANCE), + (CHARLIE, RELAY_ASSET_ID, INITIAL_BALANCE), + ], + } + .assimilate_storage(&mut t) + .unwrap(); + + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(0)); + + ext + } +} diff --git a/pallets/INV4/pallet-inv4/src/tests/mod.rs b/pallets/INV4/pallet-inv4/src/tests/mod.rs new file mode 100644 index 00000000..35fedb5f --- /dev/null +++ b/pallets/INV4/pallet-inv4/src/tests/mod.rs @@ -0,0 +1,1371 @@ +#[allow(unused_imports)] +mod mock; + +extern crate alloc; + +use crate::{ + multisig::{BoundedCallBytes, MultisigOperation, MAX_SIZE}, + origin::MultisigInternalOrigin, + voting::{Tally, Vote}, + *, +}; +use alloc::collections::BTreeMap; +use codec::Encode; +use frame_support::{assert_err, assert_ok, error::BadOrigin, BoundedBTreeMap}; +use frame_system::RawOrigin; +use mock::*; +use primitives::CoreInfo; +use sp_runtime::{ + traits::{Hash, Zero}, + ArithmeticError, Perbill, TokenError, +}; +use sp_std::{ + convert::{TryFrom, TryInto}, + vec, +}; + +#[test] +fn create_core_works() { + ExtBuilder::default().build().execute_with(|| { + assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); + + assert_eq!(INV4::next_core_id(), 0u32); + + assert_eq!(INV4::core_storage(0u32), None); + + assert_ok!(INV4::create_core( + RawOrigin::Signed(ALICE).into(), + vec![].try_into().unwrap(), + Perbill::from_percent(1), + Perbill::from_percent(1), + FeeAsset::Native + )); + + assert_eq!(INV4::next_core_id(), 1u32); + + assert_eq!( + INV4::core_storage(0u32), + Some(CoreInfo { + account: INV4::derive_core_account(0u32), + metadata: vec![].try_into().unwrap(), + minimum_support: Perbill::from_percent(1), + required_approval: Perbill::from_percent(1), + frozen_tokens: true, + }) + ); + + assert_eq!( + Balances::free_balance(ALICE), + INITIAL_BALANCE - CoreCreationFee::get() + ); + + // Another attempt + + assert_eq!(INV4::next_core_id(), 1u32); + + assert_eq!(INV4::core_storage(1u32), None); + + assert_ok!(INV4::create_core( + RawOrigin::Signed(BOB).into(), + vec![1, 2, 3].try_into().unwrap(), + Perbill::from_percent(100), + Perbill::from_percent(100), + FeeAsset::Relay + )); + + assert_eq!(INV4::next_core_id(), 2u32); + + assert_eq!( + INV4::core_storage(1u32), + Some(CoreInfo { + account: INV4::derive_core_account(1u32), + metadata: vec![1, 2, 3].try_into().unwrap(), + minimum_support: Perbill::from_percent(100), + required_approval: Perbill::from_percent(100), + frozen_tokens: true, + }) + ); + + assert_eq!( + Tokens::accounts(BOB, RELAY_ASSET_ID).free, + INITIAL_BALANCE - RelayCoreCreationFee::get() + ); + }); +} + +#[test] +fn create_core_fails() { + ExtBuilder::default().build().execute_with(|| { + // Not enough balance for creation fee. + + assert_eq!(Balances::free_balance(DAVE), 0u128); + + assert_eq!(INV4::next_core_id(), 0u32); + + assert_eq!(INV4::core_storage(0u32), None); + + assert_err!( + INV4::create_core( + RawOrigin::Signed(DAVE).into(), + vec![].try_into().unwrap(), + Perbill::from_percent(1), + Perbill::from_percent(1), + FeeAsset::Native + ), + pallet_balances::Error::::InsufficientBalance + ); + + assert_eq!(INV4::next_core_id(), 0u32); + assert_eq!(INV4::core_storage(0u32), None); + + // With Relay token. + + assert_eq!(Tokens::accounts(DAVE, RELAY_ASSET_ID).free, 0u128); + + assert_err!( + INV4::create_core( + RawOrigin::Signed(DAVE).into(), + vec![].try_into().unwrap(), + Perbill::from_percent(1), + Perbill::from_percent(1), + FeeAsset::Relay + ), + TokenError::FundsUnavailable + ); + + assert_eq!(INV4::next_core_id(), 0u32); + assert_eq!(INV4::core_storage(0u32), None); + }); +} + +#[test] +fn set_parameters_works() { + ExtBuilder::default().build().execute_with(|| { + INV4::create_core( + RawOrigin::Signed(ALICE).into(), + vec![].try_into().unwrap(), + Perbill::from_percent(1), + Perbill::from_percent(1), + FeeAsset::Native, + ) + .unwrap(); + + assert_ok!(INV4::set_parameters( + Origin::Multisig(MultisigInternalOrigin::new(0u32)).into(), + Some(vec![1, 2, 3].try_into().unwrap()), + Some(Perbill::from_percent(100)), + Some(Perbill::from_percent(100)), + Some(false) + )); + + assert_eq!( + INV4::core_storage(0u32), + Some(CoreInfo { + account: INV4::derive_core_account(0u32), + metadata: vec![1, 2, 3].try_into().unwrap(), + minimum_support: Perbill::from_percent(100), + required_approval: Perbill::from_percent(100), + frozen_tokens: false, + }) + ); + }); +} + +#[test] +fn set_parameters_fails() { + ExtBuilder::default().build().execute_with(|| { + INV4::create_core( + RawOrigin::Signed(ALICE).into(), + vec![].try_into().unwrap(), + Perbill::from_percent(1), + Perbill::from_percent(1), + FeeAsset::Native, + ) + .unwrap(); + + // Wrong origin. + + assert_err!( + INV4::set_parameters( + RawOrigin::Signed(ALICE).into(), + Some(vec![1, 2, 3].try_into().unwrap()), + Some(Perbill::from_percent(100)), + Some(Perbill::from_percent(100)), + Some(false) + ), + BadOrigin + ); + + // Core doesn't exist (can't actually happen as core id is taken from origin). + + assert_err!( + INV4::set_parameters( + Origin::Multisig(MultisigInternalOrigin::new(1u32)).into(), + Some(vec![1, 2, 3].try_into().unwrap()), + Some(Perbill::from_percent(100)), + Some(Perbill::from_percent(100)), + Some(false) + ), + Error::::CoreNotFound + ); + }); +} + +#[test] +fn token_mint_works() { + ExtBuilder::default().build().execute_with(|| { + INV4::create_core( + RawOrigin::Signed(ALICE).into(), + vec![].try_into().unwrap(), + Perbill::from_percent(1), + Perbill::from_percent(1), + FeeAsset::Native, + ) + .unwrap(); + + assert_eq!( + CoreAssets::accounts(ALICE, 0u32).free, + CoreSeedBalance::get() + ); + assert_eq!(INV4::core_members(0u32, ALICE), Some(())); + + assert_eq!(CoreAssets::accounts(BOB, 0u32).free, 0u128); + assert_eq!(INV4::core_members(0u32, BOB), None); + + assert_ok!(INV4::token_mint( + Origin::Multisig(MultisigInternalOrigin::new(0u32)).into(), + CoreSeedBalance::get(), + BOB + )); + + assert_eq!(CoreAssets::accounts(BOB, 0u32).free, CoreSeedBalance::get()); + assert_eq!(INV4::core_members(0u32, BOB), Some(())); + }); +} + +#[test] +fn token_mint_fails() { + ExtBuilder::default().build().execute_with(|| { + INV4::create_core( + RawOrigin::Signed(ALICE).into(), + vec![].try_into().unwrap(), + Perbill::from_percent(1), + Perbill::from_percent(1), + FeeAsset::Native, + ) + .unwrap(); + + // Wrong origin. + assert_err!( + INV4::token_mint(RawOrigin::Signed(ALICE).into(), CoreSeedBalance::get(), BOB), + BadOrigin + ); + + // Overflow + assert_err!( + INV4::token_mint( + Origin::Multisig(MultisigInternalOrigin::new(0u32)).into(), + u128::MAX, + ALICE + ), + ArithmeticError::Overflow + ); + }); +} + +#[test] +fn token_burn_works() { + ExtBuilder::default().build().execute_with(|| { + INV4::create_core( + RawOrigin::Signed(ALICE).into(), + vec![].try_into().unwrap(), + Perbill::from_percent(1), + Perbill::from_percent(1), + FeeAsset::Native, + ) + .unwrap(); + + assert_eq!( + CoreAssets::accounts(ALICE, 0u32).free, + CoreSeedBalance::get() + ); + assert_eq!(INV4::core_members(0u32, ALICE), Some(())); + + INV4::token_mint( + Origin::Multisig(MultisigInternalOrigin::new(0u32)).into(), + CoreSeedBalance::get(), + BOB, + ) + .unwrap(); + + assert_eq!(CoreAssets::accounts(BOB, 0u32).free, CoreSeedBalance::get()); + assert_eq!(INV4::core_members(0u32, BOB), Some(())); + + // Actual burn test + + assert_ok!(INV4::token_burn( + Origin::Multisig(MultisigInternalOrigin::new(0u32)).into(), + CoreSeedBalance::get() / 2, + ALICE + )); + + assert_eq!( + CoreAssets::accounts(ALICE, 0u32).free, + CoreSeedBalance::get() / 2 + ); + assert_eq!(INV4::core_members(0u32, ALICE), Some(())); + + assert_ok!(INV4::token_burn( + Origin::Multisig(MultisigInternalOrigin::new(0u32)).into(), + CoreSeedBalance::get(), + BOB + )); + + assert_eq!(CoreAssets::accounts(BOB, 0u32).free, 0u128); + assert_eq!(INV4::core_members(0u32, BOB), None); + }); +} + +#[test] +fn token_burn_fails() { + ExtBuilder::default().build().execute_with(|| { + INV4::create_core( + RawOrigin::Signed(ALICE).into(), + vec![].try_into().unwrap(), + Perbill::from_percent(1), + Perbill::from_percent(1), + FeeAsset::Native, + ) + .unwrap(); + + assert_eq!( + CoreAssets::accounts(ALICE, 0u32).free, + CoreSeedBalance::get() + ); + assert_eq!(INV4::core_members(0u32, ALICE), Some(())); + + INV4::token_mint( + Origin::Multisig(MultisigInternalOrigin::new(0u32)).into(), + CoreSeedBalance::get(), + BOB, + ) + .unwrap(); + + assert_eq!(CoreAssets::accounts(BOB, 0u32).free, CoreSeedBalance::get()); + assert_eq!(INV4::core_members(0u32, BOB), Some(())); + + // Actual burn test + + // Wrong origin. + assert_err!( + INV4::token_burn( + RawOrigin::Signed(ALICE).into(), + CoreSeedBalance::get(), + ALICE + ), + BadOrigin + ); + + // Underflow + assert_err!( + INV4::token_burn( + Origin::Multisig(MultisigInternalOrigin::new(0u32)).into(), + CoreSeedBalance::get() * 3, + ALICE + ), + ArithmeticError::Underflow + ); + + // Not enough to burn + assert_err!( + INV4::token_burn( + Origin::Multisig(MultisigInternalOrigin::new(0u32)).into(), + CoreSeedBalance::get() + 1, + ALICE + ), + TokenError::FundsUnavailable + ); + }); +} + +#[test] +fn operate_multisig_works() { + ExtBuilder::default().build().execute_with(|| { + INV4::create_core( + RawOrigin::Signed(ALICE).into(), + vec![].try_into().unwrap(), + Perbill::from_percent(100), + Perbill::from_percent(100), + FeeAsset::Native, + ) + .unwrap(); + + System::set_block_number(1); + + let call: RuntimeCall = pallet::Call::token_mint { + amount: CoreSeedBalance::get(), + target: BOB, + } + .into(); + + // Test with single voter. + + assert_ok!(INV4::operate_multisig( + RawOrigin::Signed(ALICE).into(), + 0u32, + Some(vec![1, 2, 3].try_into().unwrap()), + FeeAsset::Native, + Box::new(call.clone()) + )); + + System::assert_has_event( + orml_tokens2::Event::Deposited { + currency_id: 0u32, + who: BOB, + amount: CoreSeedBalance::get(), + } + .into(), + ); + + System::assert_has_event( + Event::Minted { + core_id: 0u32, + target: BOB, + amount: CoreSeedBalance::get(), + } + .into(), + ); + + System::assert_has_event( + Event::MultisigExecuted { + core_id: 0u32, + executor_account: INV4::derive_core_account(0u32), + voter: ALICE, + call: call.clone(), + call_hash: <::Hashing as Hash>::hash_of(&call), + result: Ok(()), + } + .into(), + ); + + // Test with 2 voters, call should be stored for voting. + + assert_eq!( + INV4::multisig( + 0u32, + <::Hashing as Hash>::hash_of(&call) + ), + None, + ); + + assert_ok!(INV4::operate_multisig( + RawOrigin::Signed(ALICE).into(), + 0u32, + Some(vec![1, 2, 3].try_into().unwrap()), + FeeAsset::Native, + Box::new(call.clone()) + )); + + System::assert_has_event( + Event::MultisigVoteStarted { + core_id: 0u32, + executor_account: INV4::derive_core_account(0u32), + voter: ALICE, + votes_added: Vote::Aye(CoreSeedBalance::get()), + call_hash: <::Hashing as Hash>::hash_of(&call), + } + .into(), + ); + + assert_eq!( + INV4::multisig( + 0u32, + <::Hashing as Hash>::hash_of(&call) + ), + Some(MultisigOperation { + actual_call: BoundedCallBytes::::try_from(call.clone().encode()).unwrap(), + fee_asset: FeeAsset::Native, + original_caller: ALICE, + metadata: Some(vec![1, 2, 3].try_into().unwrap()), + tally: Tally::from_parts( + CoreSeedBalance::get(), + Zero::zero(), + BoundedBTreeMap::try_from(BTreeMap::from([( + ALICE, + Vote::Aye(CoreSeedBalance::get()) + )])) + .unwrap() + ), + }) + ); + }); +} + +#[test] +fn operate_multisig_fails() { + ExtBuilder::default().build().execute_with(|| { + INV4::create_core( + RawOrigin::Signed(ALICE).into(), + vec![].try_into().unwrap(), + Perbill::from_percent(100), + Perbill::from_percent(100), + FeeAsset::Native, + ) + .unwrap(); + + System::set_block_number(1); + + let call: RuntimeCall = pallet::Call::token_mint { + amount: CoreSeedBalance::get(), + target: BOB, + } + .into(); + + // Using this call now to add a second member to the multisig. + INV4::operate_multisig( + RawOrigin::Signed(ALICE).into(), + 0u32, + None, + FeeAsset::Native, + Box::new(call.clone()), + ) + .unwrap(); + + // Not a member of the multisig + assert_err!( + INV4::operate_multisig( + RawOrigin::Signed(CHARLIE).into(), + 0u32, + Some(vec![1, 2, 3].try_into().unwrap()), + FeeAsset::Native, + Box::new(call.clone()) + ), + Error::::NoPermission + ); + + // Max call length exceeded. + assert_err!( + INV4::operate_multisig( + RawOrigin::Signed(ALICE).into(), + 0u32, + None, + FeeAsset::Native, + Box::new( + frame_system::pallet::Call::::remark { + remark: vec![0u8; MAX_SIZE as usize] + } + .into() + ) + ), + Error::::MaxCallLengthExceeded + ); + + // Multisig call already exists in storage. + INV4::operate_multisig( + RawOrigin::Signed(ALICE).into(), + 0u32, + None, + FeeAsset::Native, + Box::new(call.clone()), + ) + .unwrap(); + assert_err!( + INV4::operate_multisig( + RawOrigin::Signed(ALICE).into(), + 0u32, + None, + FeeAsset::Native, + Box::new(call.clone()) + ), + Error::::MultisigCallAlreadyExists + ); + }); +} + +#[test] +fn cancel_multisig_works() { + ExtBuilder::default().build().execute_with(|| { + INV4::create_core( + RawOrigin::Signed(ALICE).into(), + vec![].try_into().unwrap(), + Perbill::from_percent(100), + Perbill::from_percent(100), + FeeAsset::Native, + ) + .unwrap(); + + System::set_block_number(1); + + let call: RuntimeCall = pallet::Call::token_mint { + amount: CoreSeedBalance::get(), + target: BOB, + } + .into(); + + INV4::operate_multisig( + RawOrigin::Signed(ALICE).into(), + 0u32, + Some(vec![1, 2, 3].try_into().unwrap()), + FeeAsset::Native, + Box::new(call.clone()), + ) + .unwrap(); + + System::set_block_number(2); + + INV4::operate_multisig( + RawOrigin::Signed(ALICE).into(), + 0u32, + Some(vec![1, 2, 3].try_into().unwrap()), + FeeAsset::Native, + Box::new(call.clone()), + ) + .unwrap(); + + assert_eq!( + INV4::multisig( + 0u32, + <::Hashing as Hash>::hash_of(&call) + ), + Some(MultisigOperation { + actual_call: BoundedCallBytes::::try_from(call.clone().encode()).unwrap(), + fee_asset: FeeAsset::Native, + original_caller: ALICE, + metadata: Some(vec![1, 2, 3].try_into().unwrap()), + tally: Tally::from_parts( + CoreSeedBalance::get(), + Zero::zero(), + BoundedBTreeMap::try_from(BTreeMap::from([( + ALICE, + Vote::Aye(CoreSeedBalance::get()) + )])) + .unwrap() + ), + }) + ); + + assert_ok!(INV4::cancel_multisig_proposal( + Origin::Multisig(MultisigInternalOrigin::new(0u32)).into(), + <::Hashing as Hash>::hash_of(&call) + )); + + assert_eq!( + INV4::multisig( + 0u32, + <::Hashing as Hash>::hash_of(&call) + ), + None + ); + }); +} + +#[test] +fn cancel_multisig_fails() { + ExtBuilder::default().build().execute_with(|| { + INV4::create_core( + RawOrigin::Signed(ALICE).into(), + vec![].try_into().unwrap(), + Perbill::from_percent(100), + Perbill::from_percent(100), + FeeAsset::Native, + ) + .unwrap(); + + System::set_block_number(1); + + let call: RuntimeCall = pallet::Call::token_mint { + amount: CoreSeedBalance::get(), + target: BOB, + } + .into(); + + INV4::operate_multisig( + RawOrigin::Signed(ALICE).into(), + 0u32, + Some(vec![1, 2, 3].try_into().unwrap()), + FeeAsset::Native, + Box::new(call.clone()), + ) + .unwrap(); + + System::set_block_number(2); + + INV4::operate_multisig( + RawOrigin::Signed(ALICE).into(), + 0u32, + Some(vec![1, 2, 3].try_into().unwrap()), + FeeAsset::Native, + Box::new(call.clone()), + ) + .unwrap(); + + // Wrong origin. + assert_err!( + INV4::cancel_multisig_proposal( + RawOrigin::Signed(ALICE).into(), + <::Hashing as Hash>::hash_of(&call) + ), + BadOrigin + ); + + assert_eq!( + INV4::multisig( + 0u32, + <::Hashing as Hash>::hash_of(&call) + ), + Some(MultisigOperation { + actual_call: BoundedCallBytes::::try_from(call.clone().encode()).unwrap(), + fee_asset: FeeAsset::Native, + original_caller: ALICE, + metadata: Some(vec![1, 2, 3].try_into().unwrap()), + tally: Tally::from_parts( + CoreSeedBalance::get(), + Zero::zero(), + BoundedBTreeMap::try_from(BTreeMap::from([( + ALICE, + Vote::Aye(CoreSeedBalance::get()) + )])) + .unwrap() + ), + }) + ); + }); +} + +#[test] +fn vote_multisig_works() { + ExtBuilder::default().build().execute_with(|| { + INV4::create_core( + RawOrigin::Signed(ALICE).into(), + vec![].try_into().unwrap(), + Perbill::from_percent(100), + Perbill::from_percent(100), + FeeAsset::Native, + ) + .unwrap(); + + System::set_block_number(1); + + let call1: RuntimeCall = pallet::Call::token_mint { + amount: CoreSeedBalance::get(), + target: BOB, + } + .into(); + + let call2: RuntimeCall = pallet::Call::token_mint { + amount: CoreSeedBalance::get(), + target: CHARLIE, + } + .into(); + + // Adding BOB. + + INV4::operate_multisig( + RawOrigin::Signed(ALICE).into(), + 0u32, + None, + FeeAsset::Native, + Box::new(call1.clone()), + ) + .unwrap(); + + System::set_block_number(2); + + // Adding CHARLIE + + INV4::operate_multisig( + RawOrigin::Signed(ALICE).into(), + 0u32, + None, + FeeAsset::Native, + Box::new(call2.clone()), + ) + .unwrap(); + + assert_eq!( + INV4::multisig( + 0u32, + <::Hashing as Hash>::hash_of(&call2) + ), + Some(MultisigOperation { + actual_call: BoundedCallBytes::::try_from(call2.clone().encode()).unwrap(), + fee_asset: FeeAsset::Native, + original_caller: ALICE, + metadata: None, + tally: Tally::from_parts( + CoreSeedBalance::get(), + Zero::zero(), + BoundedBTreeMap::try_from(BTreeMap::from([( + ALICE, + Vote::Aye(CoreSeedBalance::get()) + )])) + .unwrap() + ), + }) + ); + + // BOB votes nay. + + assert_ok!(INV4::vote_multisig( + RawOrigin::Signed(BOB).into(), + 0u32, + <::Hashing as Hash>::hash_of(&call2), + false + )); + + System::assert_has_event( + Event::MultisigVoteAdded { + core_id: 0u32, + executor_account: INV4::derive_core_account(0u32), + voter: BOB, + votes_added: Vote::Nay(CoreSeedBalance::get()), + current_votes: Tally::from_parts( + CoreSeedBalance::get(), + CoreSeedBalance::get(), + BoundedBTreeMap::try_from(BTreeMap::from([ + (ALICE, Vote::Aye(CoreSeedBalance::get())), + (BOB, Vote::Nay(CoreSeedBalance::get())), + ])) + .unwrap(), + ), + call_hash: <::Hashing as Hash>::hash_of(&call2), + } + .into(), + ); + + assert_eq!( + INV4::multisig( + 0u32, + <::Hashing as Hash>::hash_of(&call2) + ), + Some(MultisigOperation { + actual_call: BoundedCallBytes::::try_from(call2.clone().encode()).unwrap(), + fee_asset: FeeAsset::Native, + original_caller: ALICE, + metadata: None, + tally: Tally::from_parts( + CoreSeedBalance::get(), + CoreSeedBalance::get(), + BoundedBTreeMap::try_from(BTreeMap::from([ + (ALICE, Vote::Aye(CoreSeedBalance::get())), + (BOB, Vote::Nay(CoreSeedBalance::get())) + ])) + .unwrap() + ), + }) + ); + + // BOB changes vote to aye, executing the call. + + assert_ok!(INV4::vote_multisig( + RawOrigin::Signed(BOB).into(), + 0u32, + <::Hashing as Hash>::hash_of(&call2), + true + )); + + System::assert_has_event( + Event::MultisigExecuted { + core_id: 0u32, + executor_account: INV4::derive_core_account(0u32), + voter: BOB, + call: call2.clone(), + call_hash: <::Hashing as Hash>::hash_of(&call2), + result: Ok(()), + } + .into(), + ); + + assert_eq!( + INV4::multisig( + 0u32, + <::Hashing as Hash>::hash_of(&call2) + ), + None + ); + }); +} + +#[test] +fn vote_multisig_fails() { + ExtBuilder::default().build().execute_with(|| { + INV4::create_core( + RawOrigin::Signed(ALICE).into(), + vec![].try_into().unwrap(), + Perbill::from_percent(100), + Perbill::from_percent(100), + FeeAsset::Native, + ) + .unwrap(); + + System::set_block_number(1); + + let call1: RuntimeCall = pallet::Call::token_mint { + amount: CoreSeedBalance::get(), + target: BOB, + } + .into(); + + let call2: RuntimeCall = pallet::Call::token_mint { + amount: CoreSeedBalance::get(), + target: CHARLIE, + } + .into(); + + // Adding BOB. + + INV4::operate_multisig( + RawOrigin::Signed(ALICE).into(), + 0u32, + None, + FeeAsset::Native, + Box::new(call1.clone()), + ) + .unwrap(); + + System::set_block_number(2); + + // Adding CHARLIE + + INV4::operate_multisig( + RawOrigin::Signed(ALICE).into(), + 0u32, + None, + FeeAsset::Native, + Box::new(call2.clone()), + ) + .unwrap(); + + assert_eq!( + INV4::multisig( + 0u32, + <::Hashing as Hash>::hash_of(&call2) + ), + Some(MultisigOperation { + actual_call: BoundedCallBytes::::try_from(call2.clone().encode()).unwrap(), + fee_asset: FeeAsset::Native, + original_caller: ALICE, + metadata: None, + tally: Tally::from_parts( + CoreSeedBalance::get(), + Zero::zero(), + BoundedBTreeMap::try_from(BTreeMap::from([( + ALICE, + Vote::Aye(CoreSeedBalance::get()) + )])) + .unwrap() + ), + }) + ); + + // Not a member of the multisig. + assert_err!( + INV4::vote_multisig( + RawOrigin::Signed(DAVE).into(), + 0u32, + <::Hashing as Hash>::hash_of(&call2), + true + ), + Error::::NoPermission + ); + + // Call not found. + assert_err!( + INV4::vote_multisig( + RawOrigin::Signed(BOB).into(), + 0u32, + <::Hashing as Hash>::hash_of(&call1), + true + ), + Error::::MultisigCallNotFound + ); + }); +} + +#[test] +fn withdraw_vote_multisig_works() { + ExtBuilder::default().build().execute_with(|| { + INV4::create_core( + RawOrigin::Signed(ALICE).into(), + vec![].try_into().unwrap(), + Perbill::from_percent(100), + Perbill::from_percent(100), + FeeAsset::Native, + ) + .unwrap(); + + System::set_block_number(1); + + let call1: RuntimeCall = pallet::Call::token_mint { + amount: CoreSeedBalance::get(), + target: BOB, + } + .into(); + + let call2: RuntimeCall = pallet::Call::token_mint { + amount: CoreSeedBalance::get(), + target: CHARLIE, + } + .into(); + + // Adding BOB. + + INV4::operate_multisig( + RawOrigin::Signed(ALICE).into(), + 0u32, + None, + FeeAsset::Native, + Box::new(call1.clone()), + ) + .unwrap(); + + System::set_block_number(2); + + // Adding CHARLIE + + INV4::operate_multisig( + RawOrigin::Signed(ALICE).into(), + 0u32, + None, + FeeAsset::Native, + Box::new(call2.clone()), + ) + .unwrap(); + + // BOB votes nay. + + assert_ok!(INV4::vote_multisig( + RawOrigin::Signed(BOB).into(), + 0u32, + <::Hashing as Hash>::hash_of(&call2), + false + )); + + System::assert_has_event( + Event::MultisigVoteAdded { + core_id: 0u32, + executor_account: INV4::derive_core_account(0u32), + voter: BOB, + votes_added: Vote::Nay(CoreSeedBalance::get()), + current_votes: Tally::from_parts( + CoreSeedBalance::get(), + CoreSeedBalance::get(), + BoundedBTreeMap::try_from(BTreeMap::from([ + (ALICE, Vote::Aye(CoreSeedBalance::get())), + (BOB, Vote::Nay(CoreSeedBalance::get())), + ])) + .unwrap(), + ), + call_hash: <::Hashing as Hash>::hash_of(&call2), + } + .into(), + ); + + assert_eq!( + INV4::multisig( + 0u32, + <::Hashing as Hash>::hash_of(&call2) + ), + Some(MultisigOperation { + actual_call: BoundedCallBytes::::try_from(call2.clone().encode()).unwrap(), + fee_asset: FeeAsset::Native, + original_caller: ALICE, + metadata: None, + tally: Tally::from_parts( + CoreSeedBalance::get(), + CoreSeedBalance::get(), + BoundedBTreeMap::try_from(BTreeMap::from([ + (ALICE, Vote::Aye(CoreSeedBalance::get())), + (BOB, Vote::Nay(CoreSeedBalance::get())) + ])) + .unwrap() + ), + }) + ); + + // BOB withdraws his vote. + + assert_ok!(INV4::withdraw_vote_multisig( + RawOrigin::Signed(BOB).into(), + 0u32, + <::Hashing as Hash>::hash_of(&call2), + )); + + System::assert_has_event( + Event::MultisigVoteWithdrawn { + core_id: 0u32, + executor_account: INV4::derive_core_account(0u32), + voter: BOB, + votes_removed: Vote::Nay(CoreSeedBalance::get()), + call_hash: <::Hashing as Hash>::hash_of(&call2), + } + .into(), + ); + + assert_eq!( + INV4::multisig( + 0u32, + <::Hashing as Hash>::hash_of(&call2) + ), + Some(MultisigOperation { + actual_call: BoundedCallBytes::::try_from(call2.clone().encode()).unwrap(), + fee_asset: FeeAsset::Native, + original_caller: ALICE, + metadata: None, + tally: Tally::from_parts( + CoreSeedBalance::get(), + Zero::zero(), + BoundedBTreeMap::try_from(BTreeMap::from([( + ALICE, + Vote::Aye(CoreSeedBalance::get()) + )])) + .unwrap() + ), + }) + ); + + // ALICE also withdraws her vote. + + assert_ok!(INV4::withdraw_vote_multisig( + RawOrigin::Signed(ALICE).into(), + 0u32, + <::Hashing as Hash>::hash_of(&call2), + )); + + System::assert_has_event( + Event::MultisigVoteWithdrawn { + core_id: 0u32, + executor_account: INV4::derive_core_account(0u32), + voter: ALICE, + votes_removed: Vote::Aye(CoreSeedBalance::get()), + call_hash: <::Hashing as Hash>::hash_of(&call2), + } + .into(), + ); + + assert_eq!( + INV4::multisig( + 0u32, + <::Hashing as Hash>::hash_of(&call2) + ), + Some(MultisigOperation { + actual_call: BoundedCallBytes::::try_from(call2.clone().encode()).unwrap(), + fee_asset: FeeAsset::Native, + original_caller: ALICE, + metadata: None, + tally: Tally::from_parts(Zero::zero(), Zero::zero(), BoundedBTreeMap::new()), + }) + ); + }); +} + +#[test] +fn withdraw_vote_multisig_fails() { + ExtBuilder::default().build().execute_with(|| { + INV4::create_core( + RawOrigin::Signed(ALICE).into(), + vec![].try_into().unwrap(), + Perbill::from_percent(100), + Perbill::from_percent(100), + FeeAsset::Native, + ) + .unwrap(); + + System::set_block_number(1); + + let call1: RuntimeCall = pallet::Call::token_mint { + amount: CoreSeedBalance::get(), + target: BOB, + } + .into(); + + let call2: RuntimeCall = pallet::Call::token_mint { + amount: CoreSeedBalance::get(), + target: CHARLIE, + } + .into(); + + // Adding BOB. + + INV4::operate_multisig( + RawOrigin::Signed(ALICE).into(), + 0u32, + None, + FeeAsset::Native, + Box::new(call1.clone()), + ) + .unwrap(); + + System::set_block_number(2); + + // Adding CHARLIE + + INV4::operate_multisig( + RawOrigin::Signed(ALICE).into(), + 0u32, + None, + FeeAsset::Native, + Box::new(call2.clone()), + ) + .unwrap(); + + // BOB votes nay. + + assert_ok!(INV4::vote_multisig( + RawOrigin::Signed(BOB).into(), + 0u32, + <::Hashing as Hash>::hash_of(&call2), + false + )); + + // Multisig call not found. + assert_err!( + INV4::withdraw_vote_multisig( + RawOrigin::Signed(BOB).into(), + 0u32, + <::Hashing as Hash>::hash_of(&call1), + ), + Error::::MultisigCallNotFound + ); + + // Not a voter in this proposal. + assert_err!( + INV4::withdraw_vote_multisig( + RawOrigin::Signed(CHARLIE).into(), + 0u32, + <::Hashing as Hash>::hash_of(&call2), + ), + Error::::NotAVoter + ); + + assert_eq!( + INV4::multisig( + 0u32, + <::Hashing as Hash>::hash_of(&call2) + ), + Some(MultisigOperation { + actual_call: BoundedCallBytes::::try_from(call2.clone().encode()).unwrap(), + fee_asset: FeeAsset::Native, + original_caller: ALICE, + metadata: None, + tally: Tally::from_parts( + CoreSeedBalance::get(), + CoreSeedBalance::get(), + BoundedBTreeMap::try_from(BTreeMap::from([ + (ALICE, Vote::Aye(CoreSeedBalance::get())), + (BOB, Vote::Nay(CoreSeedBalance::get())) + ])) + .unwrap() + ), + }) + ); + }); +} + +#[test] +fn core_address_matches() { + const ACCOUNT_IN_ASSET_HUB: [u8; 32] = [ + 147, 83, 7, 98, 71, 245, 98, 15, 146, 176, 22, 221, 20, 216, 188, 203, 166, 234, 117, 86, + 56, 214, 204, 37, 238, 26, 161, 82, 2, 174, 180, 74, + ]; + + let core_account = as CoreAccountDerivation>::derive_core_account(0); + + let core_account_bytes: [u8; 32] = core_account.into(); + + assert_eq!(core_account_bytes, ACCOUNT_IN_ASSET_HUB); +} + +// SRLabs tests. +#[test] +fn vote_multisig_stack_overflow() { + ExtBuilder::default().build().execute_with(|| { + INV4::create_core( + RawOrigin::Signed(ALICE).into(), + vec![].try_into().unwrap(), + Perbill::from_percent(100), + Perbill::from_percent(100), + FeeAsset::Native, + ) + .unwrap(); + + System::set_block_number(1); + + let call1: RuntimeCall = pallet::Call::token_mint { + amount: CoreSeedBalance::get(), + target: BOB, + } + .into(); + + let mut nested_call: RuntimeCall = pallet::Call::operate_multisig { + core_id: 0u32, + metadata: None, + fee_asset: FeeAsset::Native, + call: Box::new(call1.clone()), + } + .into(); + + for _ in 0..(sp_api::MAX_EXTRINSIC_DEPTH / 4) + 1 { + nested_call = pallet::Call::operate_multisig { + core_id: 0u32, + metadata: None, + fee_asset: FeeAsset::Native, + call: Box::new(nested_call.clone()), + } + .into(); + } + + INV4::operate_multisig( + RawOrigin::Signed(ALICE).into(), + 0u32, + None, + FeeAsset::Native, + Box::new(call1.clone()), + ) + .unwrap(); + + System::set_block_number(2); + + INV4::operate_multisig( + RawOrigin::Signed(ALICE).into(), + 0u32, + None, + FeeAsset::Native, + Box::new(nested_call.clone()), + ) + .unwrap(); + + assert_eq!( + INV4::multisig( + 0u32, + <::Hashing as Hash>::hash_of(&nested_call) + ), + Some(MultisigOperation { + actual_call: BoundedCallBytes::::try_from(nested_call.clone().encode()) + .unwrap(), + fee_asset: FeeAsset::Native, + original_caller: ALICE, + metadata: None, + tally: Tally::from_parts( + CoreSeedBalance::get(), + Zero::zero(), + BoundedBTreeMap::try_from(BTreeMap::from([( + ALICE, + Vote::Aye(CoreSeedBalance::get()) + )])) + .unwrap() + ), + }) + ); + + assert_err!( + INV4::vote_multisig( + RawOrigin::Signed(BOB).into(), + 0u32, + <::Hashing as Hash>::hash_of(&nested_call), + true + ), + Error::::FailedDecodingCall + ); + }); +} diff --git a/pallets/INV4/pallet-inv4/src/voting.rs b/pallets/INV4/pallet-inv4/src/voting.rs new file mode 100644 index 00000000..23564d26 --- /dev/null +++ b/pallets/INV4/pallet-inv4/src/voting.rs @@ -0,0 +1,239 @@ +//! Voting Mechanism. +//! +//! ## Overview +//! +//! This module provides a weighted voting [`Tally`] implementation used for managing the multisig's proposals. +//! Members each have a balance in voting tokens and this balance differentiate their voting power +//! as every vote utilizes the entire `power` of the said member. +//! This empowers decision-making where certain members possess greater influence. + +use crate::{origin::INV4Origin, BalanceOf, Config, CoreStorage, Error, Multisig, Pallet}; +use codec::{Decode, Encode, HasCompact, MaxEncodedLen}; +use core::marker::PhantomData; +use frame_support::{ + pallet_prelude::{Member, RuntimeDebug}, + traits::{fungibles::Inspect, PollStatus, VoteTally}, + BoundedBTreeMap, CloneNoBound, EqNoBound, Parameter, PartialEqNoBound, RuntimeDebugNoBound, +}; +use frame_system::pallet_prelude::BlockNumberFor; +use scale_info::TypeInfo; +use sp_runtime::{ + traits::{One, Zero}, + DispatchError, Perbill, +}; +use sp_std::vec::Vec; + +pub type Votes = BalanceOf; +pub type Core = ::CoreId; + +/// Aggregated votes for an ongoing poll by members of a core. +#[derive( + CloneNoBound, + PartialEqNoBound, + EqNoBound, + RuntimeDebugNoBound, + TypeInfo, + Encode, + Decode, + MaxEncodedLen, +)] +#[scale_info(skip_type_params(T))] +#[codec(mel_bound())] +pub struct Tally { + pub ayes: Votes, + pub nays: Votes, + pub records: BoundedBTreeMap>, T::MaxCallers>, + dummy: PhantomData, +} + +impl Tally { + /// Allows for building a `Tally` manually. + pub fn from_parts( + ayes: Votes, + nays: Votes, + records: BoundedBTreeMap>, T::MaxCallers>, + ) -> Self { + Tally { + ayes, + nays, + records, + dummy: PhantomData, + } + } + + /// Check if a vote is valid and add the member's total voting token balance to the tally. + pub fn process_vote( + &mut self, + account: T::AccountId, + maybe_vote: Option>>, + ) -> Result>, DispatchError> { + let votes = if let Some(vote) = maybe_vote { + self.records + .try_insert(account, vote) + .map_err(|_| Error::::MaxCallersExceeded)?; + vote + } else { + self.records.remove(&account).ok_or(Error::::NotAVoter)? + }; + + let (ayes, nays) = self.records.values().fold( + (Zero::zero(), Zero::zero()), + |(mut ayes, mut nays): (Votes, Votes), vote| { + match vote { + Vote::Aye(v) => ayes += *v, + Vote::Nay(v) => nays += *v, + }; + (ayes, nays) + }, + ); + + self.ayes = ayes; + self.nays = nays; + + Ok(votes) + } +} + +impl VoteTally, Core> for Tally { + fn new(_: Core) -> Self { + Self { + ayes: Zero::zero(), + nays: Zero::zero(), + records: BoundedBTreeMap::default(), + dummy: PhantomData, + } + } + + fn ayes(&self, _: Core) -> Votes { + self.ayes + } + + fn support(&self, class: Core) -> Perbill { + Perbill::from_rational(self.ayes, T::AssetsProvider::total_issuance(class)) + } + + fn approval(&self, _: Core) -> Perbill { + Perbill::from_rational( + self.ayes, + as One>::one().max(self.ayes + self.nays), + ) + } + + #[cfg(feature = "runtime-benchmarks")] + fn unanimity(_: Core) -> Self { + todo!() + } + + #[cfg(feature = "runtime-benchmarks")] + fn rejection(_: Core) -> Self { + todo!() + } + + #[cfg(feature = "runtime-benchmarks")] + fn from_requirements(_: Perbill, _: Perbill, _: Core) -> Self { + todo!() + } + + #[cfg(feature = "runtime-benchmarks")] + fn setup(_: Core, _: Perbill) { + todo!() + } +} + +pub trait CustomPolling { + type Index: Ord + PartialOrd + Copy + MaxEncodedLen; + type Votes: Parameter + Ord + PartialOrd + Copy + HasCompact + MaxEncodedLen; + type Class: Parameter + Member + Ord + PartialOrd + MaxEncodedLen; + type Moment; + + // Provides a vec of values that `T` may take. + fn classes() -> Vec; + + /// `Some` if the referendum `index` can be voted on, along with the tally and class of + /// referendum. + /// + /// Don't use this if you might mutate - use `try_access_poll` instead. + fn as_ongoing(class: Self::Class, index: Self::Index) -> Option<(Tally, Self::Class)>; + + fn access_poll( + class: Self::Class, + index: Self::Index, + f: impl FnOnce(PollStatus<&mut Tally, Self::Moment, Self::Class>) -> R, + ) -> R; + + fn try_access_poll( + class: Self::Class, + index: Self::Index, + f: impl FnOnce(PollStatus<&mut Tally, Self::Moment, Self::Class>) -> Result, + ) -> Result; +} + +impl CustomPolling> for Pallet { + type Index = T::Hash; + type Votes = Votes; + type Moment = BlockNumberFor; + type Class = T::CoreId; + + fn classes() -> Vec { + CoreStorage::::iter_keys().collect() + } + + fn access_poll( + class: Self::Class, + index: Self::Index, + f: impl FnOnce(PollStatus<&mut Tally, BlockNumberFor, T::CoreId>) -> R, + ) -> R { + match Multisig::::get(class, index) { + Some(mut m) => { + let result = f(PollStatus::Ongoing(&mut m.tally, class)); + Multisig::::insert(class, index, m); + result + } + _ => f(PollStatus::None), + } + } + + fn try_access_poll( + class: Self::Class, + index: Self::Index, + f: impl FnOnce( + PollStatus<&mut Tally, BlockNumberFor, T::CoreId>, + ) -> Result, + ) -> Result { + match Multisig::::get(class, index) { + Some(mut m) => { + let result = f(PollStatus::Ongoing(&mut m.tally, class))?; + Multisig::::insert(class, index, m); + Ok(result) + } + _ => f(PollStatus::None), + } + } + + fn as_ongoing(class: Self::Class, index: Self::Index) -> Option<(Tally, T::CoreId)> { + Multisig::::get(class, index).map(|m| (m.tally, class)) + } +} + +/// Represents a proposal vote within a multisig context. +/// +/// This is both the vote and how many voting tokens it carries. +#[derive(PartialEq, Eq, Clone, Copy, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)] +pub enum Vote { + Aye(Votes), + Nay(Votes), +} + +/// Type alias for [`Vote`] with [`BalanceOf`]. +pub type VoteRecord = Vote>; + +impl Pallet +where + Result, ::RuntimeOrigin>: + From<::RuntimeOrigin>, +{ + /// Returns the minimum support and required approval thresholds of a core. + pub fn minimum_support_and_required_approval(core_id: T::CoreId) -> Option<(Perbill, Perbill)> { + CoreStorage::::get(core_id).map(|core| (core.minimum_support, core.required_approval)) + } +} diff --git a/pallets/INV4/pallet-inv4/src/weights.rs b/pallets/INV4/pallet-inv4/src/weights.rs new file mode 100644 index 00000000..d58ce1c5 --- /dev/null +++ b/pallets/INV4/pallet-inv4/src/weights.rs @@ -0,0 +1,338 @@ + +//! Autogenerated weights for `pallet_inv4` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2024-05-24, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `anny.local`, CPU: `` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` + +// Executed Command: +// ./target/release/tinkernet-collator +// benchmark +// pallet +// --chain=dev +// --wasm-execution=compiled +// --pallet=pallet_inv4 +// --extrinsic=* +// --steps +// 50 +// --repeat +// 20 +// --output=../../InvArch-Frames/INV4/pallet-inv4/src/weights.rs +// --template=../weights-template.hbs + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use core::marker::PhantomData; + +/// Weight functions needed for `pallet_inv4`. +pub trait WeightInfo { + fn create_core(m: u32, ) -> Weight; + fn set_parameters(m: u32, ) -> Weight; + fn token_mint() -> Weight; + fn token_burn() -> Weight; + fn operate_multisig(m: u32, z: u32, ) -> Weight; + fn vote_multisig() -> Weight; + fn withdraw_vote_multisig() -> Weight; + fn cancel_multisig_proposal() -> Weight; +} + +/// Weights for `pallet_inv4` using the Substrate node and recommended hardware. +pub struct SubstrateWeight(PhantomData); +impl WeightInfo for SubstrateWeight { + /// Storage: `INV4::NextCoreId` (r:1 w:1) + /// Proof: `INV4::NextCoreId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `CoreAssets::Accounts` (r:1 w:1) + /// Proof: `CoreAssets::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) + /// Storage: `CoreAssets::TotalIssuance` (r:1 w:1) + /// Proof: `CoreAssets::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `INV4::CoreByAccount` (r:0 w:1) + /// Proof: `INV4::CoreByAccount` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `INV4::CoreStorage` (r:0 w:1) + /// Proof: `INV4::CoreStorage` (`max_values`: None, `max_size`: Some(10063), added: 12538, mode: `MaxEncodedLen`) + /// Storage: `INV4::CoreMembers` (r:0 w:1) + /// Proof: `INV4::CoreMembers` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) + /// The range of component `m` is `[0, 10000]`. + fn create_core(m: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `304` + // Estimated: `6196` + // Minimum execution time: 61_000_000 picoseconds. + Weight::from_parts(61_957_455, 6196) + // Standard Error: 17 + .saturating_add(Weight::from_parts(769, 0).saturating_mul(m.into())) + .saturating_add(T::DbWeight::get().reads(6_u64)) + .saturating_add(T::DbWeight::get().writes(8_u64)) + } + /// Storage: `INV4::CoreStorage` (r:1 w:1) + /// Proof: `INV4::CoreStorage` (`max_values`: None, `max_size`: Some(10063), added: 12538, mode: `MaxEncodedLen`) + /// The range of component `m` is `[0, 10000]`. + fn set_parameters(m: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `234` + // Estimated: `13528` + // Minimum execution time: 8_000_000 picoseconds. + Weight::from_parts(8_995_089, 13528) + // Standard Error: 5 + .saturating_add(Weight::from_parts(684, 0).saturating_mul(m.into())) + .saturating_add(T::DbWeight::get().reads(1_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + /// Storage: `CoreAssets::Accounts` (r:1 w:1) + /// Proof: `CoreAssets::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) + /// Storage: `CoreAssets::TotalIssuance` (r:1 w:1) + /// Proof: `CoreAssets::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `INV4::CoreMembers` (r:0 w:1) + /// Proof: `INV4::CoreMembers` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) + fn token_mint() -> Weight { + // Proof Size summary in bytes: + // Measured: `246` + // Estimated: `3593` + // Minimum execution time: 25_000_000 picoseconds. + Weight::from_parts(26_000_000, 3593) + .saturating_add(T::DbWeight::get().reads(3_u64)) + .saturating_add(T::DbWeight::get().writes(4_u64)) + } + /// Storage: `CoreAssets::Accounts` (r:1 w:1) + /// Proof: `CoreAssets::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) + /// Storage: `CoreAssets::TotalIssuance` (r:1 w:1) + /// Proof: `CoreAssets::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `INV4::CoreMembers` (r:0 w:1) + /// Proof: `INV4::CoreMembers` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) + fn token_burn() -> Weight { + // Proof Size summary in bytes: + // Measured: `438` + // Estimated: `3593` + // Minimum execution time: 27_000_000 picoseconds. + Weight::from_parts(28_000_000, 3593) + .saturating_add(T::DbWeight::get().reads(3_u64)) + .saturating_add(T::DbWeight::get().writes(4_u64)) + } + /// Storage: `CoreAssets::Accounts` (r:1 w:0) + /// Proof: `CoreAssets::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) + /// Storage: `INV4::CoreStorage` (r:1 w:0) + /// Proof: `INV4::CoreStorage` (`max_values`: None, `max_size`: Some(10063), added: 12538, mode: `MaxEncodedLen`) + /// Storage: `CoreAssets::TotalIssuance` (r:1 w:0) + /// Proof: `CoreAssets::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `INV4::Multisig` (r:1 w:1) + /// Proof: `INV4::Multisig` (`max_values`: None, `max_size`: Some(551342), added: 553817, mode: `MaxEncodedLen`) + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// The range of component `m` is `[0, 10000]`. + /// The range of component `z` is `[0, 51190]`. + fn operate_multisig(m: u32, z: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `529` + // Estimated: `554807` + // Minimum execution time: 25_000_000 picoseconds. + Weight::from_parts(21_624_412, 554807) + // Standard Error: 15 + .saturating_add(Weight::from_parts(397, 0).saturating_mul(m.into())) + // Standard Error: 3 + .saturating_add(Weight::from_parts(1_514, 0).saturating_mul(z.into())) + .saturating_add(T::DbWeight::get().reads(5_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + /// Storage: `INV4::Multisig` (r:1 w:1) + /// Proof: `INV4::Multisig` (`max_values`: None, `max_size`: Some(551342), added: 553817, mode: `MaxEncodedLen`) + /// Storage: `CoreAssets::Accounts` (r:1 w:0) + /// Proof: `CoreAssets::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) + /// Storage: `INV4::CoreStorage` (r:1 w:0) + /// Proof: `INV4::CoreStorage` (`max_values`: None, `max_size`: Some(10063), added: 12538, mode: `MaxEncodedLen`) + /// Storage: `CoreAssets::TotalIssuance` (r:1 w:0) + /// Proof: `CoreAssets::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + fn vote_multisig() -> Weight { + // Proof Size summary in bytes: + // Measured: `780` + // Estimated: `554807` + // Minimum execution time: 25_000_000 picoseconds. + Weight::from_parts(26_000_000, 554807) + .saturating_add(T::DbWeight::get().reads(5_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + /// Storage: `INV4::Multisig` (r:1 w:1) + /// Proof: `INV4::Multisig` (`max_values`: None, `max_size`: Some(551342), added: 553817, mode: `MaxEncodedLen`) + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + fn withdraw_vote_multisig() -> Weight { + // Proof Size summary in bytes: + // Measured: `514` + // Estimated: `554807` + // Minimum execution time: 13_000_000 picoseconds. + Weight::from_parts(14_000_000, 554807) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + /// Storage: `INV4::Multisig` (r:0 w:1) + /// Proof: `INV4::Multisig` (`max_values`: None, `max_size`: Some(551342), added: 553817, mode: `MaxEncodedLen`) + fn cancel_multisig_proposal() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 6_000_000 picoseconds. + Weight::from_parts(7_000_000, 0) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } +} + +// For backwards compatibility and tests. +impl WeightInfo for () { + /// Storage: `INV4::NextCoreId` (r:1 w:1) + /// Proof: `INV4::NextCoreId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `CoreAssets::Accounts` (r:1 w:1) + /// Proof: `CoreAssets::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) + /// Storage: `CoreAssets::TotalIssuance` (r:1 w:1) + /// Proof: `CoreAssets::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `INV4::CoreByAccount` (r:0 w:1) + /// Proof: `INV4::CoreByAccount` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `INV4::CoreStorage` (r:0 w:1) + /// Proof: `INV4::CoreStorage` (`max_values`: None, `max_size`: Some(10063), added: 12538, mode: `MaxEncodedLen`) + /// Storage: `INV4::CoreMembers` (r:0 w:1) + /// Proof: `INV4::CoreMembers` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) + /// The range of component `m` is `[0, 10000]`. + fn create_core(m: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `304` + // Estimated: `6196` + // Minimum execution time: 61_000_000 picoseconds. + Weight::from_parts(61_957_455, 6196) + // Standard Error: 17 + .saturating_add(Weight::from_parts(769, 0).saturating_mul(m.into())) + .saturating_add(RocksDbWeight::get().reads(6_u64)) + .saturating_add(RocksDbWeight::get().writes(8_u64)) + } + /// Storage: `INV4::CoreStorage` (r:1 w:1) + /// Proof: `INV4::CoreStorage` (`max_values`: None, `max_size`: Some(10063), added: 12538, mode: `MaxEncodedLen`) + /// The range of component `m` is `[0, 10000]`. + fn set_parameters(m: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `234` + // Estimated: `13528` + // Minimum execution time: 8_000_000 picoseconds. + Weight::from_parts(8_995_089, 13528) + // Standard Error: 5 + .saturating_add(Weight::from_parts(684, 0).saturating_mul(m.into())) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + /// Storage: `CoreAssets::Accounts` (r:1 w:1) + /// Proof: `CoreAssets::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) + /// Storage: `CoreAssets::TotalIssuance` (r:1 w:1) + /// Proof: `CoreAssets::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `INV4::CoreMembers` (r:0 w:1) + /// Proof: `INV4::CoreMembers` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) + fn token_mint() -> Weight { + // Proof Size summary in bytes: + // Measured: `246` + // Estimated: `3593` + // Minimum execution time: 25_000_000 picoseconds. + Weight::from_parts(26_000_000, 3593) + .saturating_add(RocksDbWeight::get().reads(3_u64)) + .saturating_add(RocksDbWeight::get().writes(4_u64)) + } + /// Storage: `CoreAssets::Accounts` (r:1 w:1) + /// Proof: `CoreAssets::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) + /// Storage: `CoreAssets::TotalIssuance` (r:1 w:1) + /// Proof: `CoreAssets::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `INV4::CoreMembers` (r:0 w:1) + /// Proof: `INV4::CoreMembers` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) + fn token_burn() -> Weight { + // Proof Size summary in bytes: + // Measured: `438` + // Estimated: `3593` + // Minimum execution time: 27_000_000 picoseconds. + Weight::from_parts(28_000_000, 3593) + .saturating_add(RocksDbWeight::get().reads(3_u64)) + .saturating_add(RocksDbWeight::get().writes(4_u64)) + } + /// Storage: `CoreAssets::Accounts` (r:1 w:0) + /// Proof: `CoreAssets::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) + /// Storage: `INV4::CoreStorage` (r:1 w:0) + /// Proof: `INV4::CoreStorage` (`max_values`: None, `max_size`: Some(10063), added: 12538, mode: `MaxEncodedLen`) + /// Storage: `CoreAssets::TotalIssuance` (r:1 w:0) + /// Proof: `CoreAssets::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `INV4::Multisig` (r:1 w:1) + /// Proof: `INV4::Multisig` (`max_values`: None, `max_size`: Some(551342), added: 553817, mode: `MaxEncodedLen`) + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// The range of component `m` is `[0, 10000]`. + /// The range of component `z` is `[0, 51190]`. + fn operate_multisig(m: u32, z: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `529` + // Estimated: `554807` + // Minimum execution time: 25_000_000 picoseconds. + Weight::from_parts(21_624_412, 554807) + // Standard Error: 15 + .saturating_add(Weight::from_parts(397, 0).saturating_mul(m.into())) + // Standard Error: 3 + .saturating_add(Weight::from_parts(1_514, 0).saturating_mul(z.into())) + .saturating_add(RocksDbWeight::get().reads(5_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + /// Storage: `INV4::Multisig` (r:1 w:1) + /// Proof: `INV4::Multisig` (`max_values`: None, `max_size`: Some(551342), added: 553817, mode: `MaxEncodedLen`) + /// Storage: `CoreAssets::Accounts` (r:1 w:0) + /// Proof: `CoreAssets::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) + /// Storage: `INV4::CoreStorage` (r:1 w:0) + /// Proof: `INV4::CoreStorage` (`max_values`: None, `max_size`: Some(10063), added: 12538, mode: `MaxEncodedLen`) + /// Storage: `CoreAssets::TotalIssuance` (r:1 w:0) + /// Proof: `CoreAssets::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + fn vote_multisig() -> Weight { + // Proof Size summary in bytes: + // Measured: `780` + // Estimated: `554807` + // Minimum execution time: 25_000_000 picoseconds. + Weight::from_parts(26_000_000, 554807) + .saturating_add(RocksDbWeight::get().reads(5_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + /// Storage: `INV4::Multisig` (r:1 w:1) + /// Proof: `INV4::Multisig` (`max_values`: None, `max_size`: Some(551342), added: 553817, mode: `MaxEncodedLen`) + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + fn withdraw_vote_multisig() -> Weight { + // Proof Size summary in bytes: + // Measured: `514` + // Estimated: `554807` + // Minimum execution time: 13_000_000 picoseconds. + Weight::from_parts(14_000_000, 554807) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + /// Storage: `INV4::Multisig` (r:0 w:1) + /// Proof: `INV4::Multisig` (`max_values`: None, `max_size`: Some(551342), added: 553817, mode: `MaxEncodedLen`) + fn cancel_multisig_proposal() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 6_000_000 picoseconds. + Weight::from_parts(7_000_000, 0) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } +} diff --git a/pallets/LICENSE b/pallets/LICENSE new file mode 100644 index 00000000..f288702d --- /dev/null +++ b/pallets/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/pallets/OCIF/staking/Cargo.toml b/pallets/OCIF/staking/Cargo.toml new file mode 100644 index 00000000..4ad92454 --- /dev/null +++ b/pallets/OCIF/staking/Cargo.toml @@ -0,0 +1,77 @@ +[package] +name = 'pallet-ocif-staking' +authors = ['InvArchitects '] +description = 'FRAME pallet for OCIF staking' +edition = '2021' +homepage = 'https://invarch.network' +license = 'GPLv3' +repository = 'https://github.com/InvArch/InvArch-Pallet-Library/' +version = '0.1.0-dev' + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[dependencies] +codec = { workspace = true, default-features = false } +scale-info = { workspace = true, default-features = false } +serde = { workspace = true, optional = true } + +frame-support = { workspace = true, default-features = false } +frame-system = { workspace = true, default-features = false } +num-traits = { workspace = true, default-features = false } +pallet-balances = { workspace = true, default-features = false, optional = true } +pallet-message-queue = { workspace = true, default-features = false} +pallet-session = { workspace = true, default-features = false } +pallet-timestamp = { workspace = true, default-features = false, optional = true } +sp-arithmetic = { workspace = true, default-features = false } +sp-core = { workspace = true, default-features = false } +sp-io = { workspace = true, default-features = false } +sp-runtime = { workspace = true, default-features = false } +sp-staking = { workspace = true, default-features = false } +sp-std = { workspace = true, default-features = false } + +pallet-inv4 = { path = "../../INV4/pallet-inv4", default-features = false } + +frame-benchmarking = { workspace = true, default-features = false, optional = true } +cumulus-primitives-core = { workspace = true, default-features = false } + +[dev-dependencies] +orml-traits = { workspace = true, default-features = false } +orml-tokens = { workspace = true, default-features = false } +xcm = { workspace = true, default-features = false } + +[features] +default = ["std"] +std = [ + "serde", + "codec/std", + "scale-info/std", + "num-traits/std", + "cumulus-primitives-core/std", + "sp-core/std", + "sp-runtime/std", + "sp-arithmetic/std", + "sp-io/std", + "sp-std/std", + "frame-support/std", + "frame-system/std", + "frame-benchmarking?/std", + "xcm/std", + "pallet-balances/std", + "pallet-message-queue/std", + "pallet-session/std", + "pallet-timestamp/std", + "pallet-inv4/std", + "sp-staking/std", + "orml-traits/std", + "orml-tokens/std", +] +runtime-benchmarks = [ + "frame-benchmarking/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", + "frame-system/runtime-benchmarks", + "pallet-inv4/runtime-benchmarks", + "pallet-message-queue/runtime-benchmarks", + +] +try-runtime = ["frame-support/try-runtime"] diff --git a/pallets/OCIF/staking/README.md b/pallets/OCIF/staking/README.md new file mode 100644 index 00000000..6b214267 --- /dev/null +++ b/pallets/OCIF/staking/README.md @@ -0,0 +1,47 @@ +# OCIF Staking Pallet + +## Overview + +The OCIF Staking Pallet is a pallet designed to facilitate staking towards INV-Cores within a blockchain network. This pallet introduces a staking mechanism that allows two distinct sets of entities, namely Cores and Stakers, to participate in the distribution of tokens from a predefined pot. The allocation of rewards is determined based on the amount staked by each entity and the total stake towards each Core. + +### Cores + +Cores represent virtual accounts identified by unique IDs, which are responsible for registering themselves within the staking ecosystem. The primary role of Cores is to attract Stakers to lock tokens in their favor. The rewards allocated to Cores are proportional to the total amount staked towards them by Stakers. However, for a Core to be eligible for rewards, it must have a total stake above a predefined threshold, thereby becoming `active`. + +### Stakers + +Stakers are individual accounts that engage in locking tokens in favor of a Core. Unlike Cores, Stakers receive a fraction of the rewards based on their own stake. + +## Runtime Configuration Parameters + +- `BlocksPerEra`: Defines the duration of an era in terms of block numbers. +- `RegisterDeposit`: Specifies the deposit amount required for Core registration. +- `MaxStakersPerCore`: Limits the maximum number of Stakers that can simultaneously stake towards a single Core. +- `MinimumStakingAmount`: Sets the minimum amount required for a Staker to participate in staking. +- `UnbondingPeriod`: Determines the period, in eras, required for unbonding staked tokens. +- `RewardRatio`: Establishes the distribution ratio of rewards between Cores and Stakers. +- `StakeThresholdForActiveCore`: Sets the stake threshold required for a Core to become `active`. + +## Dispatchable Functions + +- `register_core`: Allows Cores to register themselves in the system. +- `unregister_core`: Enables Cores to unregister from the system, initiating the unbonding period for Stakers. +- `change_core_metadata`: Changes the metadata associated to a Core. +- `stake`: Allows Stakers to lock tokens in favor of a Core. +- `unstake`: Unstakes tokens previously staked to a Core, starting the unbonding period. +- `withdraw_unstaked`: Allows Stakers to withdraw tokens that have completed the unbonding period. +- `staker_claim_rewards`: Allows Stakers to claim available rewards. +- `core_claim_rewards`: Allows rewards to be claimed for Cores. +- `halt_unhalt_pallet`: Allows Root to trigger a halt of the system, eras will stop counting and rewards won't be distributed. + +## Events + +The pallet emits events such as `Staked`, `Unstaked`, `CoreRegistered`, `CoreUnregistered`, and others to signal various operations and state changes within the staking ecosystem. + +## Errors + +Errors such as `StakingNothing`, `InsufficientBalance`, `MaxStakersReached`, and others are defined to handle exceptional scenarios encountered during pallet operations. + +## Example Runtime Implementation + +For an example runtime implementation that integrates this pallet, refer to [src/testing/mock.rs](./src/testing/mock.rs). diff --git a/pallets/OCIF/staking/src/benchmarking.rs b/pallets/OCIF/staking/src/benchmarking.rs new file mode 100644 index 00000000..21fffc2f --- /dev/null +++ b/pallets/OCIF/staking/src/benchmarking.rs @@ -0,0 +1,300 @@ +#![cfg(feature = "runtime-benchmarks")] + +use super::*; +use crate::Pallet as OcifStaking; +use core::ops::Add; +use frame_benchmarking::{benchmarks, whitelisted_caller}; +use frame_support::{ + traits::{Get, OnFinalize, OnInitialize}, + BoundedVec, +}; +use frame_system::{Pallet as System, RawOrigin}; +use pallet_inv4::{ + account_derivation::CoreAccountDerivation, + origin::{INV4Origin, MultisigInternalOrigin}, +}; +use sp_runtime::traits::{Bounded, One}; +use sp_std::vec; + +fn assert_last_event(generic_event: ::RuntimeEvent) { + frame_system::Pallet::::assert_last_event(generic_event.into()); +} + +fn derive_account(core_id: ::CoreId) -> T::AccountId +where + T: pallet_inv4::Config, + T::AccountId: From<[u8; 32]>, +{ + as CoreAccountDerivation>::derive_core_account(core_id) +} + +fn advance_to_era(n: Era) { + while OcifStaking::::current_era() < n { + as OnFinalize>>::on_finalize(System::::block_number()); + System::::set_block_number(System::::block_number() + One::one()); + as OnInitialize>>::on_initialize( + System::::block_number(), + ); + } +} + +fn mock_register() -> DispatchResultWithPostInfo +where + Result, ::RuntimeOrigin>: + From<::RuntimeOrigin>, + ::RuntimeOrigin: From>, + T::AccountId: From<[u8; 32]>, +{ + ::Currency::make_free_balance_be( + &derive_account::(0u32.into()), + T::RegisterDeposit::get() + T::RegisterDeposit::get(), + ); + + OcifStaking::::register_core( + INV4Origin::Multisig(MultisigInternalOrigin::new(0u32.into())).into(), + vec![].try_into().unwrap(), + vec![].try_into().unwrap(), + vec![].try_into().unwrap(), + ) +} + +fn mock_register_2() -> DispatchResultWithPostInfo +where + Result, ::RuntimeOrigin>: + From<::RuntimeOrigin>, + ::RuntimeOrigin: From>, + T::AccountId: From<[u8; 32]>, +{ + ::Currency::make_free_balance_be( + &derive_account::(1u32.into()), + T::RegisterDeposit::get() + T::RegisterDeposit::get(), + ); + + OcifStaking::::register_core( + INV4Origin::Multisig(MultisigInternalOrigin::new(1u32.into())).into(), + vec![].try_into().unwrap(), + vec![].try_into().unwrap(), + vec![].try_into().unwrap(), + ) +} + +fn mock_stake() -> DispatchResultWithPostInfo +where + Result, ::RuntimeOrigin>: + From<::RuntimeOrigin>, + ::RuntimeOrigin: From>, + T::AccountId: From<[u8; 32]>, +{ + ::Currency::make_free_balance_be( + &whitelisted_caller(), + pallet::BalanceOf::::max_value(), + ); + + OcifStaking::::stake( + RawOrigin::Signed(whitelisted_caller()).into(), + 0u32.into(), + T::StakeThresholdForActiveCore::get() + T::StakeThresholdForActiveCore::get(), + ) +} + +fn mock_unstake() -> DispatchResultWithPostInfo +where + Result, ::RuntimeOrigin>: + From<::RuntimeOrigin>, + ::RuntimeOrigin: From>, + T::AccountId: From<[u8; 32]>, +{ + OcifStaking::::unstake( + RawOrigin::Signed(whitelisted_caller()).into(), + 0u32.into(), + T::StakeThresholdForActiveCore::get() + T::StakeThresholdForActiveCore::get(), + ) +} + +benchmarks! { + where_clause { + where + Result< + INV4Origin, + ::RuntimeOrigin, + >: From<::RuntimeOrigin>, + ::RuntimeOrigin: From>, + T::AccountId: From<[u8; 32]>, + +} + + register_core { + let n in 0 .. T::MaxNameLength::get(); + let d in 0 .. T::MaxDescriptionLength::get(); + let i in 0 .. T::MaxImageUrlLength::get(); + + let name: BoundedVec = vec![u8::MAX; n as usize].try_into().unwrap(); + let description: BoundedVec = vec![u8::MAX; d as usize].try_into().unwrap(); + let image: BoundedVec = vec![u8::MAX; i as usize].try_into().unwrap(); + + ::Currency::make_free_balance_be(&derive_account::(0u32.into()), T::RegisterDeposit::get() + T::RegisterDeposit::get()); + }: _(INV4Origin::Multisig(MultisigInternalOrigin::new(0u32.into())), name, description, image) + verify { + assert_last_event::(Event::::CoreRegistered { + core: 0u32.into() + }.into()); + } + + change_core_metadata { + let n in 0 .. T::MaxNameLength::get(); + let d in 0 .. T::MaxDescriptionLength::get(); + let i in 0 .. T::MaxImageUrlLength::get(); + + let name: BoundedVec = vec![u8::MAX; n as usize].try_into().unwrap(); + let description: BoundedVec = vec![u8::MAX; d as usize].try_into().unwrap(); + let image: BoundedVec = vec![u8::MAX; i as usize].try_into().unwrap(); + + mock_register().unwrap(); + + }: _(INV4Origin::Multisig(MultisigInternalOrigin::new(0u32.into())), name.clone(), description.clone(), image.clone()) + verify { + assert_last_event::(Event::::MetadataChanged { + core: 0u32.into(), + old_metadata: CoreMetadata { + name: vec![], + description: vec![], + image: vec![] + }, + new_metadata: CoreMetadata { + name: name.to_vec(), + description: description.to_vec(), + image: image.to_vec() + } + }.into()); + } + + unregister_core { + mock_register().unwrap(); + + }: _(INV4Origin::Multisig(MultisigInternalOrigin::new(0u32.into()))) + verify { + assert_last_event::(Event::::CoreUnregistered { + core: 0u32.into() + }.into()); + } + + stake { + mock_register().unwrap(); + + let staker = whitelisted_caller(); + let amount = T::StakeThresholdForActiveCore::get() + T::StakeThresholdForActiveCore::get(); + + ::Currency::make_free_balance_be(&staker, pallet::BalanceOf::::max_value()); + }: _(RawOrigin::Signed(staker.clone()), 0u32.into(), amount) + verify { + assert_last_event::(Event::::Staked { + staker, + core: 0u32.into(), + amount + }.into()); + } + + unstake { + mock_register().unwrap(); + mock_stake().unwrap(); + + let staker: T::AccountId = whitelisted_caller(); + let amount = T::StakeThresholdForActiveCore::get() + T::StakeThresholdForActiveCore::get(); + + }: _(RawOrigin::Signed(staker.clone()), 0u32.into(), amount) + verify { + assert_last_event::(Event::::Unstaked { + staker, + core: 0u32.into(), + amount + }.into()); + } + + withdraw_unstaked { + mock_register().unwrap(); + mock_stake().unwrap(); + mock_unstake().unwrap(); + advance_to_era::(T::UnbondingPeriod::get().add(1)); + + let staker: T::AccountId = whitelisted_caller(); + let amount = T::StakeThresholdForActiveCore::get() + T::StakeThresholdForActiveCore::get(); + + }: _(RawOrigin::Signed(staker.clone())) + verify { + assert_last_event::(Event::::Withdrawn { + staker, + amount + }.into()); + } + + staker_claim_rewards { + mock_register().unwrap(); + mock_stake().unwrap(); + advance_to_era::(One::one()); + + let staker: T::AccountId = whitelisted_caller(); + let amount = T::StakeThresholdForActiveCore::get() + T::StakeThresholdForActiveCore::get(); + + let core_stake_info = OcifStaking::::core_stake_info::<::CoreId, Era>(0u32.into(), 0u32).unwrap(); + let era_info = OcifStaking::::general_era_info::(0u32).unwrap(); + + let (_, reward) = OcifStaking::::core_stakers_split(&core_stake_info, &era_info); + + }: _(RawOrigin::Signed(staker.clone()), 0u32.into()) + verify { + assert_last_event::(Event::::StakerClaimed { + staker, + core: 0u32.into(), + era: 0u32.into(), + amount: reward + }.into()); + } + + core_claim_rewards { + mock_register().unwrap(); + mock_stake().unwrap(); + advance_to_era::(One::one()); + + let staker: T::AccountId = whitelisted_caller(); + let amount = T::StakeThresholdForActiveCore::get() + T::StakeThresholdForActiveCore::get(); + + let core_stake_info = OcifStaking::::core_stake_info::<::CoreId, Era>(0u32.into(), 0u32).unwrap(); + let era_info = OcifStaking::::general_era_info::(0u32).unwrap(); + + let (reward, _) = OcifStaking::::core_stakers_split(&core_stake_info, &era_info); + + }: _(INV4Origin::Multisig(MultisigInternalOrigin::new(0u32.into())), 0u32.into(), 0u32.into()) + verify { + assert_last_event::(Event::::CoreClaimed { + core: 0u32.into(), + destination_account: derive_account::(0u32.into()), + era: 0u32.into(), + amount: reward + }.into()); + } + + halt_unhalt_pallet {}: _(RawOrigin::Root, true) + verify { + assert_last_event::(Event::::HaltChanged { + is_halted: true + }.into()); + } + + move_stake { + mock_register().unwrap(); + mock_register_2().unwrap(); + + mock_stake().unwrap(); + + let staker: T::AccountId = whitelisted_caller(); + let amount = T::StakeThresholdForActiveCore::get() + T::StakeThresholdForActiveCore::get(); + }: _(RawOrigin::Signed(staker.clone()), 0u32.into(), amount, 1u32.into()) + verify { + assert_last_event::(Event::::StakeMoved { + staker, + from_core: 0u32.into(), + amount, + to_core: 1u32.into() + }.into()); + } +} diff --git a/pallets/OCIF/staking/src/lib.rs b/pallets/OCIF/staking/src/lib.rs new file mode 100644 index 00000000..bb713868 --- /dev/null +++ b/pallets/OCIF/staking/src/lib.rs @@ -0,0 +1,1386 @@ +//! # OCIF Staking pallet +//! A pallet for allowing INV-Cores to be staked towards. +//! +//! ## Overview +//! +//! This pallet provides functionality to allow 2 sets of entities to participate in distribution of tokens +//! available in a predefined pot account. +//! The tokens provided to the pot account are to be handled by the Runtime, +//! either directly or with the assistance of another pallet. +//! +//! The 2 entity sets will be referred to in code as Cores and Stakers: +//! +//! ### Cores +//! Cores are virtual accounts that have an ID used to derive their own account address, +//! their task in the process is to register themselves and have Stakers lock tokens in favor of a specifc Core. +//! Cores receive their fraction of the pot rewards based on the total amount staked towards them by Stakers, +//! however, a Core must have total stake above the defined threshold (making it `active`), otherwise they won't be entitled to rewards. +//! +//! ### Stakers +//! Stakers are any account existing on the chain, their task is to lock tokens in favor of a Core. +//! Unlike Cores, Stakers get their fraction of the rewards based on their own stake and regardless of +//! the `active` state of the Core they staked towards. +//! +//! ## Relevant runtime configs +//! +//! * `BlocksPerEra` - Defines how many blocks constitute an era. +//! * `RegisterDeposit` - Defines the deposit amount for a Core to register in the system. +//! * `MaxStakersPerCore` - Defines the maximum amount of Stakers allowed staking simultaneously towards the same Core. +//! * `MinimumStakingAmount` - Defines the minimum amount a Staker has to stake to participate. +//! * `UnbondingPeriod` - Defines the period, in eras, that it takes to unbond a stake. +//! * `RewardRatio` - Defines the ratio of balance from the pot to distribute to Cores and Stakers, respectively. +//! * `StakeThresholdForActiveCore` - Defines the threshold of stake a Core needs to surpass to become active. +//! +//! **Example Runtime implementation can be found in [src/testing/mock.rs](./src/testing/mock.rs)** +//! +//! ## Dispatchable Functions +//! +//! * `register_core` - Registers a Core in the system. +//! * `unregister_core` - Unregisters a Core from the system, starting the unbonding period for the Stakers. +//! * `change_core_metadata` - Changes the metadata tied to a Core. +//! * `stake` - Stakes tokens towards a Core. +//! * `unstake` - Unstakes tokens from a core and starts the unbonding period for those tokens. +//! * `withdraw_unstaked` - Withdraws tokens that have already been through the unbonding period. +//! * `staker_claim_rewards` - Claims rewards available for a Staker. +//! * `core_claim_rewards` - Claims rewards available for a Core. +//! * `halt_unhalt_pallet` - Allows Root to trigger a halt of the system, eras will stop counting and rewards won't be distributed. +//! +//! [`Call`]: ./enum.Call.html +//! [`Config`]: ./trait.Config.html + +#![cfg_attr(not(feature = "std"), no_std)] + +use frame_support::{ + dispatch::{Pays, PostDispatchInfo}, + ensure, + pallet_prelude::*, + traits::{ + Currency, ExistenceRequirement, Get, HandleMessage, Imbalance, LockIdentifier, + LockableCurrency, OnUnbalanced, ProcessMessage, QueuePausedQuery, ReservableCurrency, + WithdrawReasons, + }, + weights::{Weight, WeightToFee}, + BoundedSlice, PalletId, +}; +use frame_system::{ensure_signed, pallet_prelude::*}; +use sp_runtime::{ + traits::{AccountIdConversion, Saturating, Zero}, + Perbill, +}; +use sp_std::{ + convert::{From, TryInto}, + vec::Vec, +}; + +pub mod primitives; +use primitives::*; + +#[cfg(feature = "runtime-benchmarks")] +mod benchmarking; +#[cfg(test)] +mod testing; +pub mod weights; + +pub use weights::WeightInfo; + +/// Staking lock identifier. +const LOCK_ID: LockIdentifier = *b"ocif-stk"; + +pub use pallet::*; + +#[frame_support::pallet] +pub mod pallet { + use pallet_inv4::{ + origin::{ensure_multisig, INV4Origin}, + CoreAccountDerivation, + }; + + use pallet_message_queue::{self}; + + use super::*; + + /// The balance type of this pallet. + pub type BalanceOf = + <::Currency as Currency<::AccountId>>::Balance; + + #[pallet::pallet] + pub struct Pallet(PhantomData); + + /// The opaque token type for an imbalance. This is returned by unbalanced operations and must be dealt with. + type NegativeImbalanceOf = <::Currency as Currency< + ::AccountId, + >>::NegativeImbalance; + + /// The core metadata type of this pallet. + pub type CoreMetadataOf = CoreMetadata< + BoundedVec::MaxNameLength>, + BoundedVec::MaxDescriptionLength>, + BoundedVec::MaxImageUrlLength>, + >; + + /// The core information type, containing a core's AccountId and CoreMetadataOf. + pub type CoreInfoOf = CoreInfo<::AccountId, CoreMetadataOf>; + + /// Alias type for the era identifier type. + pub type Era = u32; + + #[pallet::config] + pub trait Config: + frame_system::Config + pallet_inv4::Config + pallet_message_queue::Config + { + /// The overarching event type. + type RuntimeEvent: From> + IsType<::RuntimeEvent>; + + /// The currency used in staking. + type Currency: LockableCurrency> + + ReservableCurrency; + + // type CoreId: Parameter + // + Member + // + AtLeast32BitUnsigned + // + Default + // + Copy + // + Display + // + MaxEncodedLen + // + Clone + // + From<::CoreId>; + + /// Number of blocks per era. + #[pallet::constant] + type BlocksPerEra: Get>; + + /// Deposit amount that will be reserved as part of new core registration. + #[pallet::constant] + type RegisterDeposit: Get>; + + /// Maximum number of unique stakers per core. + #[pallet::constant] + type MaxStakersPerCore: Get; + + /// Minimum amount user must have staked on a core. + /// User can stake less if they already have the minimum staking amount staked. + #[pallet::constant] + type MinimumStakingAmount: Get>; + + /// Account Identifier from which the internal Pot is generated. + #[pallet::constant] + type PotId: Get; + + /// The minimum amount required to keep an account open. + #[pallet::constant] + type ExistentialDeposit: Get>; + + /// Max number of unlocking chunks per account Id <-> core Id pairing. + /// If value is zero, unlocking becomes impossible. + #[pallet::constant] + type MaxUnlocking: Get; + + /// Number of eras that need to pass until unstaked value can be withdrawn. + /// When set to `0`, it's equal to having no unbonding period. + #[pallet::constant] + type UnbondingPeriod: Get; + + /// Max number of unique `EraStake` values that can exist for a `(staker, core)` pairing. + /// + /// When stakers claims rewards, they will either keep the number of `EraStake` values the same or they will reduce them by one. + /// Stakers cannot add an additional `EraStake` value by calling `bond&stake` or `unbond&unstake` if they've reached the max number of values. + /// + /// This ensures that history doesn't grow indefinitely - if there are too many chunks, stakers should first claim their former rewards + /// before adding additional `EraStake` values. + #[pallet::constant] + type MaxEraStakeValues: Get; + + /// Reward ratio of the pot to be distributed between the core and stakers, respectively. + #[pallet::constant] + type RewardRatio: Get<(u32, u32)>; + + /// Threshold of staked tokens necessary for a core to become active. + #[pallet::constant] + type StakeThresholdForActiveCore: Get>; + + /// Maximum length of a core's name. + #[pallet::constant] + type MaxNameLength: Get; + + /// Maximum length of a core's description. + #[pallet::constant] + type MaxDescriptionLength: Get; + + /// Maximum length of a core's image URL. + #[pallet::constant] + type MaxImageUrlLength: Get; + + /// Weight information for extrinsics in this pallet. + type WeightInfo: WeightInfo; + + /// Message queue interface. + type StakingMessage: HandleMessage; + + /// Weight to fee conversion provider, from pallet_transaction_payment. + type WeightToFee: WeightToFee>; + + /// Fee charghing interface. + type OnUnbalanced: OnUnbalanced>; + } + + /// General information about the staker. + #[pallet::storage] + #[pallet::getter(fn ledger)] + pub type Ledger = + StorageMap<_, Blake2_128Concat, T::AccountId, AccountLedger>, ValueQuery>; + + /// The current era index. + #[pallet::storage] + #[pallet::getter(fn current_era)] + pub type CurrentEra = StorageValue<_, Era, ValueQuery>; + + /// Accumulator for block rewards during an era. It is reset at every new era. + #[pallet::storage] + #[pallet::getter(fn reward_accumulator)] + pub type RewardAccumulator = StorageValue<_, RewardInfo>, ValueQuery>; + + /// Stores the block number of when the next era starts. + #[pallet::storage] + #[pallet::getter(fn next_era_starting_block)] + pub type NextEraStartingBlock = StorageValue<_, BlockNumberFor, ValueQuery>; + + /// Simple map where CoreId points to the respective core information. + #[pallet::storage] + #[pallet::getter(fn core_info)] + pub(crate) type RegisteredCore = + StorageMap<_, Blake2_128Concat, T::CoreId, CoreInfoOf>; + + /// General information about an era. + #[pallet::storage] + #[pallet::getter(fn general_era_info)] + pub type GeneralEraInfo = StorageMap<_, Twox64Concat, Era, EraInfo>>; + + /// Staking information about a core in a particular era. + #[pallet::storage] + #[pallet::getter(fn core_stake_info)] + pub type CoreEraStake = StorageDoubleMap< + _, + Blake2_128Concat, + T::CoreId, + Twox64Concat, + Era, + CoreStakeInfo>, + >; + + /// Info about staker's stakes on a particular core. + #[pallet::storage] + #[pallet::getter(fn staker_info)] + pub type GeneralStakerInfo = StorageDoubleMap< + _, + Blake2_128Concat, + T::CoreId, + Blake2_128Concat, + T::AccountId, + StakerInfo>, + ValueQuery, + >; + + /// Denotes whether the pallet is halted (disabled). + #[pallet::storage] + #[pallet::getter(fn is_halted)] + pub type Halted = StorageValue<_, bool, ValueQuery>; + + /// Placeholder for the core being unregistered and its stake info. + #[pallet::storage] + #[pallet::getter(fn core_unregistering_staker_info)] + pub type UnregisteredCoreStakeInfo = + StorageMap<_, Blake2_128Concat, T::CoreId, CoreStakeInfo>, OptionQuery>; + + /// Placeholder for the core being unregistered and its stakers. + #[pallet::storage] + #[pallet::getter(fn core_unregistering_staker_list)] + pub type UnregisteredCoreStakers = StorageMap< + _, + Blake2_128Concat, + T::CoreId, + BoundedVec, + OptionQuery, + >; + + #[pallet::event] + #[pallet::generate_deposit(pub(crate) fn deposit_event)] + pub enum Event { + /// Account has staked funds to a core. + Staked { + staker: T::AccountId, + core: T::CoreId, + amount: BalanceOf, + }, + + /// Account has unstaked funds from a core. + Unstaked { + staker: T::AccountId, + core: T::CoreId, + amount: BalanceOf, + }, + + /// Account has withdrawn unbonded funds. + Withdrawn { + staker: T::AccountId, + amount: BalanceOf, + }, + + /// New core registered for staking. + CoreRegistered { core: T::CoreId }, + + /// Core unregistered. + CoreUnregistered { core: T::CoreId }, + + /// Beginning of a new era. + NewEra { era: u32 }, + + /// Staker claimed rewards. + StakerClaimed { + staker: T::AccountId, + core: T::CoreId, + era: u32, + amount: BalanceOf, + }, + + /// Rewards claimed for core. + CoreClaimed { + core: T::CoreId, + destination_account: T::AccountId, + era: u32, + amount: BalanceOf, + }, + + /// Halt status changed. + HaltChanged { is_halted: bool }, + + /// Core metadata changed. + MetadataChanged { + core: T::CoreId, + old_metadata: CoreMetadata, Vec, Vec>, + new_metadata: CoreMetadata, Vec, Vec>, + }, + + /// Staker moved an amount of stake to another core. + StakeMoved { + staker: T::AccountId, + from_core: T::CoreId, + to_core: T::CoreId, + amount: BalanceOf, + }, + /// Core is being unregistered. + CoreUnregistrationQueueStarted { core: T::CoreId }, + /// Core ungregistration chunk was processed. + CoreUnregistrationChunksProcessed { + core: T::CoreId, + accounts_processed_in_this_chunk: u64, + accounts_left: u64, + }, + /// Sharded execution of the core unregistration process finished. + CoreUnregistrationQueueFinished { core: T::CoreId }, + } + + #[pallet::error] + pub enum Error { + /// Staking nothing. + StakingNothing, + /// Attempted to stake less than the minimum amount. + InsufficientBalance, + /// Maximum number of stakers reached. + MaxStakersReached, + /// Core not found. + CoreNotFound, + /// No stake available for withdrawal. + NoStakeAvailable, + /// Core is not unregistered. + NotUnregisteredCore, + /// Unclaimed rewards available. + UnclaimedRewardsAvailable, + /// Unstaking nothing. + UnstakingNothing, + /// Nothing available for withdrawal. + NothingToWithdraw, + /// Core already registered. + CoreAlreadyRegistered, + /// Unknown rewards for era. + UnknownEraReward, + /// Unexpected stake info for era. + UnexpectedStakeInfoEra, + /// Too many unlocking chunks. + TooManyUnlockingChunks, + /// Reward already claimed. + RewardAlreadyClaimed, + /// Incorrect era. + IncorrectEra, + /// Too many era stake values. + TooManyEraStakeValues, + /// Not a staker. + NotAStaker, + /// No permission. + NoPermission, + /// Name exceeds maximum length. + MaxNameExceeded, + /// Description exceeds maximum length. + MaxDescriptionExceeded, + /// Image URL exceeds maximum length. + MaxImageExceeded, + /// Core not registered. + NotRegistered, + /// Halted. + Halted, + /// No halt change. + NoHaltChange, + /// Attempted to move stake to the same core. + MoveStakeToSameCore, + } + + #[pallet::hooks] + impl Hooks> for Pallet { + fn on_initialize(now: BlockNumberFor) -> Weight { + // If the pallet is halted we don't process a new era. + if Self::is_halted() { + return T::DbWeight::get().reads(1); + } + + let previous_era = Self::current_era(); + let next_era_starting_block = Self::next_era_starting_block(); + + // Process a new era if past the start block of next era or if this is the first ever era. + if now >= next_era_starting_block || previous_era.is_zero() { + let blocks_per_era = T::BlocksPerEra::get(); + let next_era = previous_era + 1; + CurrentEra::::put(next_era); + + NextEraStartingBlock::::put(now + blocks_per_era); + + let reward = RewardAccumulator::::take(); + let (consumed_weight, new_active_stake) = Self::rotate_staking_info(previous_era); + Self::reward_balance_snapshot(previous_era, reward, new_active_stake); + + Self::deposit_event(Event::::NewEra { era: next_era }); + + consumed_weight + T::DbWeight::get().reads_writes(5, 3) + } else { + T::DbWeight::get().reads(3) + } + } + } + + #[pallet::call] + impl Pallet + where + Result, ::RuntimeOrigin>: + From<::RuntimeOrigin>, + T::AccountId: From<[u8; 32]>, + { + /// Used to register core for staking. + /// + /// The origin has to be the core origin. + /// + /// As part of this call, `RegisterDeposit` will be reserved from the core account. + /// + /// - `name`: Name of the core. + /// - `description`: Description of the core. + /// - `image`: Image URL of the core. + #[pallet::call_index(0)] + #[pallet::weight( + ::WeightInfo::register_core( + name.len() as u32, + description.len() as u32, + image.len() as u32 + ) + )] + pub fn register_core( + origin: OriginFor, + name: BoundedVec, + description: BoundedVec, + image: BoundedVec, + ) -> DispatchResultWithPostInfo { + Self::ensure_not_halted()?; + + let core = ensure_multisig::>(origin)?; + let core_account = core.to_account_id(); + let core_id = core.id; + + ensure!( + !RegisteredCore::::contains_key(core_id), + Error::::CoreAlreadyRegistered, + ); + + let metadata: CoreMetadataOf = CoreMetadata { + name, + description, + image, + }; + + ::Currency::reserve(&core_account, T::RegisterDeposit::get())?; + + RegisteredCore::::insert( + core_id, + CoreInfo { + account: core_account, + metadata, + }, + ); + + Self::deposit_event(Event::::CoreRegistered { core: core_id }); + + Ok(PostDispatchInfo { + actual_weight: None, + pays_fee: Pays::No, + }) + } + + /// Unregister existing core for staking, making it ineligible for rewards from current era onwards and + /// starts the unbonding period for the stakers. + /// + /// The origin has to be the core origin. + /// + /// Deposit is returned to the core account. + /// + /// - `core_id`: Id of the core to be unregistered. + #[pallet::call_index(1)] + #[pallet::weight( + ::WeightInfo::unregister_core() + )] + pub fn unregister_core(origin: OriginFor) -> DispatchResultWithPostInfo { + Self::ensure_not_halted()?; + + let core = ensure_multisig::>(origin.clone())?; + let core_account = core.to_account_id(); + let core_id = core.id; + + ensure!( + RegisteredCore::::get(core_id).is_some(), + Error::::NotRegistered + ); + + let current_era = Self::current_era(); + + let all_stakers: BoundedVec = + BoundedVec::truncate_from( + GeneralStakerInfo::::iter_key_prefix(core_id).collect::>(), + ); + + let all_fee = ::WeightToFee::weight_to_fee( + &(all_stakers.len() as u32 * ::WeightInfo::unstake()), + ); + + UnregisteredCoreStakers::::insert(core_id, all_stakers); + + let mut core_stake_info = + Self::core_stake_info(core_id, current_era).unwrap_or_default(); + UnregisteredCoreStakeInfo::::insert(core_id, core_stake_info.clone()); + GeneralEraInfo::::mutate(current_era, |value| { + if let Some(x) = value { + x.staked = x.staked.saturating_sub(core_stake_info.total); + } + }); + core_stake_info.total = Zero::zero(); + CoreEraStake::::insert(core_id, current_era, core_stake_info.clone()); + + let reserve_deposit = T::RegisterDeposit::get(); + ::Currency::unreserve(&core_account, reserve_deposit); + + T::OnUnbalanced::on_unbalanced(::Currency::withdraw( + &core_account, + reserve_deposit.min(all_fee), + WithdrawReasons::TRANSACTION_PAYMENT, + ExistenceRequirement::KeepAlive, + )?); + + RegisteredCore::::remove(core_id); + + let total_stakers = core_stake_info.number_of_stakers; + + let message = primitives::UnregisterMessage:: { + core_id, + era: current_era, + stakers_to_unstake: total_stakers, + } + .encode(); + + T::StakingMessage::handle_message(BoundedSlice::truncate_from(message.as_slice())); + + Self::deposit_event(Event::::CoreUnregistrationQueueStarted { core: core_id }); + + Self::deposit_event(Event::::CoreUnregistered { core: core_id }); + + Ok(Some(::WeightInfo::unregister_core()).into()) + } + + /// Used to change the metadata of a core. + /// + /// The origin has to be the core origin. + /// + /// - `name`: Name of the core. + /// - `description`: Description of the core. + /// - `image`: Image URL of the core. + #[pallet::call_index(2)] + #[pallet::weight( + ::WeightInfo::change_core_metadata( + name.len() as u32, + description.len() as u32, + image.len() as u32 + ) + )] + pub fn change_core_metadata( + origin: OriginFor, + name: BoundedVec, + description: BoundedVec, + image: BoundedVec, + ) -> DispatchResultWithPostInfo { + Self::ensure_not_halted()?; + + let core_origin = ensure_multisig::>(origin)?; + let core_id = core_origin.id; + + RegisteredCore::::try_mutate(core_id, |core| { + let mut new_core = core.take().ok_or(Error::::NotRegistered)?; + + let new_metadata: CoreMetadataOf = CoreMetadata { + name: name.clone(), + description: description.clone(), + image: image.clone(), + }; + + let old_metadata = new_core.metadata; + + new_core.metadata = new_metadata; + + *core = Some(new_core); + + Self::deposit_event(Event::::MetadataChanged { + core: core_id, + old_metadata: CoreMetadata { + name: old_metadata.name.into_inner(), + description: old_metadata.description.into_inner(), + image: old_metadata.image.into_inner(), + }, + new_metadata: CoreMetadata { + name: name.to_vec(), + description: description.to_vec(), + image: image.to_vec(), + }, + }); + + Ok(().into()) + }) + } + + /// Lock up and stake balance of the origin account. + /// + /// `value` must be more than the `minimum_stake` specified by `MinimumStakingAmount` + /// unless account already has bonded value equal or more than 'minimum_stake'. + /// + /// The dispatch origin for this call must be _Signed_ by the staker's account. + /// + /// - `core_id`: Id of the core to stake towards. + /// - `value`: Amount to stake. + #[pallet::call_index(3)] + #[pallet::weight(::WeightInfo::stake())] + pub fn stake( + origin: OriginFor, + core_id: T::CoreId, + #[pallet::compact] value: BalanceOf, + ) -> DispatchResultWithPostInfo { + Self::ensure_not_halted()?; + + let staker = ensure_signed(origin)?; + + ensure!( + Self::core_info(core_id).is_some(), + Error::::NotRegistered + ); + + let mut ledger = Self::ledger(&staker); + let available_balance = Self::available_staking_balance(&staker, &ledger); + let value_to_stake = value.min(available_balance); + + ensure!(value_to_stake > Zero::zero(), Error::::StakingNothing); + + let current_era = Self::current_era(); + let mut staking_info = Self::core_stake_info(core_id, current_era).unwrap_or_default(); + let mut staker_info = Self::staker_info(core_id, &staker); + + Self::internal_stake( + &mut staker_info, + &mut staking_info, + value_to_stake, + current_era, + )?; + + ledger.locked = ledger.locked.saturating_add(value_to_stake); + + GeneralEraInfo::::mutate(current_era, |value| { + if let Some(x) = value { + x.staked = x.staked.saturating_add(value_to_stake); + x.locked = x.locked.saturating_add(value_to_stake); + } + }); + + Self::update_ledger(&staker, ledger); + Self::update_staker_info(&staker, core_id, staker_info); + CoreEraStake::::insert(core_id, current_era, staking_info); + + Self::deposit_event(Event::::Staked { + staker, + core: core_id, + amount: value_to_stake, + }); + Ok(().into()) + } + + /// Start unbonding process and unstake balance from the core. + /// + /// The unstaked amount will no longer be eligible for rewards but still won't be unlocked. + /// User needs to wait for the unbonding period to finish before being able to withdraw + /// the funds via `withdraw_unstaked` call. + /// + /// In case remaining staked balance is below minimum staking amount, + /// entire stake will be unstaked. + /// + /// - `core_id`: Id of the core to unstake from. + #[pallet::call_index(4)] + #[pallet::weight(::WeightInfo::unstake())] + pub fn unstake( + origin: OriginFor, + core_id: T::CoreId, + #[pallet::compact] value: BalanceOf, + ) -> DispatchResultWithPostInfo { + Self::ensure_not_halted()?; + + let staker = ensure_signed(origin)?; + + ensure!(value > Zero::zero(), Error::::UnstakingNothing); + ensure!( + Self::core_info(core_id).is_some(), + Error::::NotRegistered + ); + + let current_era = Self::current_era(); + let mut staker_info = Self::staker_info(core_id, &staker); + let mut core_stake_info = + Self::core_stake_info(core_id, current_era).unwrap_or_default(); + + let value_to_unstake = + Self::internal_unstake(&mut staker_info, &mut core_stake_info, value, current_era)?; + + let mut ledger = Self::ledger(&staker); + ledger.unbonding_info.add(UnlockingChunk { + amount: value_to_unstake, + unlock_era: current_era + T::UnbondingPeriod::get(), + }); + + ensure!( + ledger.unbonding_info.len() <= T::MaxUnlocking::get(), + Error::::TooManyUnlockingChunks + ); + + Self::update_ledger(&staker, ledger); + + GeneralEraInfo::::mutate(current_era, |value| { + if let Some(x) = value { + x.staked = x.staked.saturating_sub(value_to_unstake); + } + }); + Self::update_staker_info(&staker, core_id, staker_info); + CoreEraStake::::insert(core_id, current_era, core_stake_info); + + Self::deposit_event(Event::::Unstaked { + staker, + core: core_id, + amount: value_to_unstake, + }); + + Ok(().into()) + } + + /// Withdraw all funds that have completed the unbonding process. + /// + /// If there are unbonding chunks which will be fully unbonded in future eras, + /// they will remain and can be withdrawn later. + /// + /// The dispatch origin for this call must be _Signed_ by the staker's account. + #[pallet::call_index(5)] + #[pallet::weight(::WeightInfo::withdraw_unstaked())] + pub fn withdraw_unstaked(origin: OriginFor) -> DispatchResultWithPostInfo { + Self::ensure_not_halted()?; + + let staker = ensure_signed(origin)?; + + let mut ledger = Self::ledger(&staker); + let current_era = Self::current_era(); + + let (valid_chunks, future_chunks) = ledger.unbonding_info.partition(current_era); + let withdraw_amount = valid_chunks.sum(); + + ensure!(!withdraw_amount.is_zero(), Error::::NothingToWithdraw); + + ledger.locked = ledger.locked.saturating_sub(withdraw_amount); + ledger.unbonding_info = future_chunks; + + Self::update_ledger(&staker, ledger); + GeneralEraInfo::::mutate(current_era, |value| { + if let Some(x) = value { + x.locked = x.locked.saturating_sub(withdraw_amount) + } + }); + + Self::deposit_event(Event::::Withdrawn { + staker, + amount: withdraw_amount, + }); + + Ok(().into()) + } + + /// Claim the staker's rewards. + /// + /// In case reward cannot be claimed or was already claimed, an error is raised. + /// + /// The dispatch origin for this call must be _Signed_ by the staker's account. + /// + /// - `core_id`: Id of the core to claim rewards from. + #[pallet::call_index(6)] + #[pallet::weight(::WeightInfo::staker_claim_rewards())] + pub fn staker_claim_rewards( + origin: OriginFor, + core_id: T::CoreId, + ) -> DispatchResultWithPostInfo { + Self::ensure_not_halted()?; + + let staker = ensure_signed(origin)?; + + let mut staker_info = Self::staker_info(core_id, &staker); + let (era, staked) = staker_info.claim(); + ensure!(staked > Zero::zero(), Error::::NoStakeAvailable); + + let current_era = Self::current_era(); + ensure!(era < current_era, Error::::IncorrectEra); + + let staking_info = Self::core_stake_info(core_id, era).unwrap_or_default(); + + let mut staker_reward = Zero::zero(); + + if staking_info.total > Zero::zero() { + let reward_and_stake = + Self::general_era_info(era).ok_or(Error::::UnknownEraReward)?; + + let (_, stakers_joint_reward) = + Self::core_stakers_split(&staking_info, &reward_and_stake); + staker_reward = + Perbill::from_rational(staked, staking_info.total) * stakers_joint_reward; + + let reward_imbalance = ::Currency::withdraw( + &Self::account_id(), + staker_reward, + WithdrawReasons::TRANSFER, + ExistenceRequirement::AllowDeath, + )?; + + ::Currency::resolve_creating(&staker, reward_imbalance); + Self::update_staker_info(&staker, core_id, staker_info); + } + + Self::deposit_event(Event::::StakerClaimed { + staker, + core: core_id, + era, + amount: staker_reward, + }); + + Ok(().into()) + } + + /// Claim core reward for the specified era. + /// + /// In case reward cannot be claimed or was already claimed, an error is raised. + /// + /// - `core_id`: Id of the core to claim rewards from. + /// - `era`: Era for which rewards are to be claimed. + #[pallet::call_index(7)] + #[pallet::weight(::WeightInfo::core_claim_rewards())] + pub fn core_claim_rewards( + origin: OriginFor, + core_id: T::CoreId, + #[pallet::compact] era: Era, + ) -> DispatchResultWithPostInfo { + Self::ensure_not_halted()?; + + ensure_signed(origin)?; + + let current_era = Self::current_era(); + ensure!(era < current_era, Error::::IncorrectEra); + + let mut core_stake_info = Self::core_stake_info(core_id, era).unwrap_or_default(); + ensure!( + !core_stake_info.reward_claimed, + Error::::RewardAlreadyClaimed, + ); + ensure!( + core_stake_info.total > Zero::zero(), + Error::::NoStakeAvailable, + ); + + let reward_and_stake = + Self::general_era_info(era).ok_or(Error::::UnknownEraReward)?; + + let (reward, _) = Self::core_stakers_split(&core_stake_info, &reward_and_stake); + + let reward_imbalance = ::Currency::withdraw( + &Self::account_id(), + reward, + WithdrawReasons::TRANSFER, + ExistenceRequirement::AllowDeath, + )?; + + let core_account = + as CoreAccountDerivation>::derive_core_account(core_id); + + ::Currency::resolve_creating(&core_account, reward_imbalance); + Self::deposit_event(Event::::CoreClaimed { + core: core_id, + destination_account: core_account, + era, + amount: reward, + }); + + core_stake_info.reward_claimed = true; + CoreEraStake::::insert(core_id, era, core_stake_info); + + Ok(().into()) + } + + /// Halt or unhalt the pallet. + /// + /// The dispatch origin for this call must be _Root_. + /// + /// - `halt`: `true` to halt, `false` to unhalt. + #[pallet::call_index(8)] + #[pallet::weight((::WeightInfo::halt_unhalt_pallet(), Pays::No))] + pub fn halt_unhalt_pallet(origin: OriginFor, halt: bool) -> DispatchResultWithPostInfo { + ensure_root(origin)?; + + let is_halted = Self::is_halted(); + + ensure!(is_halted ^ halt, Error::::NoHaltChange); + + Self::internal_halt_unhalt(halt); + + Self::deposit_event(Event::::HaltChanged { is_halted: halt }); + + Ok(().into()) + } + + /// Move stake from one core to another. + /// + /// The dispatch origin for this call must be _Signed_ by the staker's account. + /// + /// - `from_core`: Id of the core to move stake from. + /// - `amount`: Amount to move. + /// - `to_core`: Id of the core to move stake to. + #[pallet::call_index(9)] + #[pallet::weight(::WeightInfo::move_stake())] + pub fn move_stake( + origin: OriginFor, + from_core: T::CoreId, + #[pallet::compact] amount: BalanceOf, + to_core: T::CoreId, + ) -> DispatchResultWithPostInfo { + Self::ensure_not_halted()?; + + let staker = ensure_signed(origin)?; + + ensure!(from_core != to_core, Error::::MoveStakeToSameCore); + ensure!( + Self::core_info(to_core).is_some(), + Error::::NotRegistered + ); + + let current_era = Self::current_era(); + let mut from_staker_info = Self::staker_info(from_core, &staker); + let mut from_core_info = + Self::core_stake_info(from_core, current_era).unwrap_or_default(); + + let unstaked_amount = Self::internal_unstake( + &mut from_staker_info, + &mut from_core_info, + amount, + current_era, + )?; + + let mut to_staker_info = Self::staker_info(to_core, &staker); + let mut to_core_info = Self::core_stake_info(to_core, current_era).unwrap_or_default(); + + Self::internal_stake( + &mut to_staker_info, + &mut to_core_info, + unstaked_amount, + current_era, + )?; + + CoreEraStake::::insert(from_core, current_era, from_core_info); + Self::update_staker_info(&staker, from_core, from_staker_info); + + CoreEraStake::::insert(to_core, current_era, to_core_info); + Self::update_staker_info(&staker, to_core, to_staker_info); + + Self::deposit_event(Event::::StakeMoved { + staker, + from_core, + to_core, + amount: unstaked_amount, + }); + + Ok(().into()) + } + } + + impl Pallet { + /// Internal function responsible for validating a stake and updating in-place + /// both the staker's and core staking info. + fn internal_stake( + staker_info: &mut StakerInfo>, + staking_info: &mut CoreStakeInfo>, + amount: BalanceOf, + current_era: Era, + ) -> Result<(), Error> { + ensure!( + !staker_info.latest_staked_value().is_zero() + || staking_info.number_of_stakers < T::MaxStakersPerCore::get(), + Error::::MaxStakersReached + ); + if staker_info.latest_staked_value().is_zero() { + staking_info.number_of_stakers = staking_info.number_of_stakers.saturating_add(1); + } + + staker_info + .stake(current_era, amount) + .map_err(|_| Error::::UnexpectedStakeInfoEra)?; + ensure!( + staker_info.len() < T::MaxEraStakeValues::get(), + Error::::TooManyEraStakeValues + ); + ensure!( + staker_info.latest_staked_value() >= T::MinimumStakingAmount::get(), + Error::::InsufficientBalance, + ); + + let new_total = staking_info.total.saturating_add(amount); + + staking_info.total = new_total; + + Ok(()) + } + + /// Internal function responsible for validating an unstake and updating in-place + /// both the staker's and core staking info. + fn internal_unstake( + staker_info: &mut StakerInfo>, + core_stake_info: &mut CoreStakeInfo>, + amount: BalanceOf, + current_era: Era, + ) -> Result, Error> { + let staked_value = staker_info.latest_staked_value(); + ensure!(staked_value > Zero::zero(), Error::::NoStakeAvailable); + + let remaining = staked_value.saturating_sub(amount); + let value_to_unstake = if remaining < T::MinimumStakingAmount::get() { + core_stake_info.number_of_stakers = + core_stake_info.number_of_stakers.saturating_sub(1); + staked_value + } else { + amount + }; + + let new_total = core_stake_info.total.saturating_sub(value_to_unstake); + + core_stake_info.total = new_total; + + ensure!( + value_to_unstake > Zero::zero(), + Error::::UnstakingNothing + ); + + staker_info + .unstake(current_era, value_to_unstake) + .map_err(|_| Error::::UnexpectedStakeInfoEra)?; + ensure!( + staker_info.len() < T::MaxEraStakeValues::get(), + Error::::TooManyEraStakeValues + ); + + Ok(value_to_unstake) + } + + pub(crate) fn account_id() -> T::AccountId { + T::PotId::get().into_account_truncating() + } + + /// Update the ledger for a staker. This will also update the stash lock. + /// This lock will lock the entire funds except paying for further transactions. + fn update_ledger(staker: &T::AccountId, ledger: AccountLedger>) { + if ledger.is_empty() { + Ledger::::remove(staker); + ::Currency::remove_lock(LOCK_ID, staker); + } else { + ::Currency::set_lock( + LOCK_ID, + staker, + ledger.locked, + WithdrawReasons::all(), + ); + Ledger::::insert(staker, ledger); + } + } + + /// The block rewards are accumulated on the pallet's account during an era. + /// This function takes a snapshot of the pallet's balance accrued during current era + /// and stores it for future distribution + /// + /// This is called just at the beginning of an era. + fn reward_balance_snapshot( + era: Era, + rewards: RewardInfo>, + new_active_stake: BalanceOf, + ) { + let mut era_info = Self::general_era_info(era).unwrap_or_default(); + + GeneralEraInfo::::insert( + era + 1, + EraInfo { + rewards: Default::default(), + staked: era_info.staked, + active_stake: new_active_stake, + locked: era_info.locked, + }, + ); + + era_info.rewards = rewards; + era_info.active_stake = new_active_stake; + + GeneralEraInfo::::insert(era, era_info); + } + + /// Adds `stakers` and `cores` rewards to the reward pool. + /// + /// - `inflation`: Total inflation for the era. + pub fn rewards(inflation: NegativeImbalanceOf) { + let (core_part, stakers_part) = ::RewardRatio::get(); + + let (core, stakers) = inflation.ration(core_part, stakers_part); + + RewardAccumulator::::mutate(|accumulated_reward| { + accumulated_reward.core = accumulated_reward.core.saturating_add(core.peek()); + accumulated_reward.stakers = + accumulated_reward.stakers.saturating_add(stakers.peek()); + }); + + ::Currency::resolve_creating( + &Self::account_id(), + stakers.merge(core), + ); + } + + /// Updates staker info for a core. + fn update_staker_info( + staker: &T::AccountId, + core_id: T::CoreId, + staker_info: StakerInfo>, + ) { + if staker_info.is_empty() { + GeneralStakerInfo::::remove(core_id, staker) + } else { + GeneralStakerInfo::::insert(core_id, staker, staker_info) + } + } + + /// Returns available staking balance for the potential staker. + fn available_staking_balance( + staker: &T::AccountId, + ledger: &AccountLedger>, + ) -> BalanceOf { + let free_balance = ::Currency::free_balance(staker) + .saturating_sub(::ExistentialDeposit::get()); + + free_balance.saturating_sub(ledger.locked) + } + + /// Returns total value locked by staking. + /// + /// Note that this can differ from _total staked value_ since some funds might be undergoing the unbonding period. + pub fn tvl() -> BalanceOf { + let current_era = Self::current_era(); + if let Some(era_info) = Self::general_era_info(current_era) { + era_info.locked + } else { + Zero::zero() + } + } + + /// Calculate reward split between core and stakers. + /// + /// Returns (core reward, joint stakers reward) + pub(crate) fn core_stakers_split( + core_info: &CoreStakeInfo>, + era_info: &EraInfo>, + ) -> (BalanceOf, BalanceOf) { + let core_stake_portion = if core_info.active { + Perbill::from_rational(core_info.total, era_info.active_stake) + } else { + Perbill::zero() + }; + let stakers_stake_portion = Perbill::from_rational(core_info.total, era_info.staked); + + let core_reward_part = core_stake_portion * era_info.rewards.core; + let stakers_joint_reward = stakers_stake_portion * era_info.rewards.stakers; + + (core_reward_part, stakers_joint_reward) + } + + /// Used to copy all `CoreStakeInfo` from the ending era over to the next era. + fn rotate_staking_info(current_era: Era) -> (Weight, BalanceOf) { + let next_era = current_era + 1; + + let mut consumed_weight = Weight::zero(); + + let mut new_active_stake: BalanceOf = Zero::zero(); + + for core_id in RegisteredCore::::iter_keys() { + consumed_weight = consumed_weight.saturating_add(T::DbWeight::get().reads(1)); + + if let Some(mut staking_info) = Self::core_stake_info(core_id, current_era) { + if staking_info.total >= ::StakeThresholdForActiveCore::get() { + staking_info.active = true; + new_active_stake += staking_info.total; + } else { + staking_info.active = false; + } + + staking_info.reward_claimed = false; + CoreEraStake::::insert(core_id, next_era, staking_info); + + consumed_weight = + consumed_weight.saturating_add(T::DbWeight::get().reads_writes(1, 1)); + } else { + consumed_weight = consumed_weight.saturating_add(T::DbWeight::get().reads(1)); + } + } + + (consumed_weight, new_active_stake) + } + + /// Sets the halt state of the pallet. + pub fn internal_halt_unhalt(halt: bool) { + Halted::::put(halt); + } + + /// Ensure the pallet is not halted. + pub fn ensure_not_halted() -> Result<(), Error> { + if Self::is_halted() { + Err(Error::::Halted) + } else { + Ok(()) + } + } + + /// Sharded execution of the core unregistration process. + /// + /// This function is called by the [`ProcessMessage`] trait implemented in [`primitives::ProcessUnregistrationMessages`] + pub(crate) fn process_core_unregistration_shard( + stakers: u32, + core_id: T::CoreId, + start_era: Era, + chunk_size: u64, + ) -> DispatchResultWithPostInfo { + let mut staker_info_prefix = + Self::core_unregistering_staker_list(core_id).unwrap_or_default(); + + let mut corrected_staker_length_fee = Zero::zero(); + + let mut core_stake_info = + Self::core_unregistering_staker_info(core_id).unwrap_or_default(); + + let mut unsteked_count: u64 = 0; + while let Some(staker) = staker_info_prefix.pop() { + let mut staker_info = Self::staker_info(core_id, &staker); + + let latest_staked_value = staker_info.latest_staked_value(); + + if let Ok(value_to_unstake) = Self::internal_unstake( + &mut staker_info, + &mut core_stake_info, + latest_staked_value, + start_era, + ) { + UnregisteredCoreStakeInfo::::insert(core_id, core_stake_info.clone()); + let mut ledger = Self::ledger(&staker); + ledger.unbonding_info.add(UnlockingChunk { + amount: value_to_unstake, + unlock_era: start_era + T::UnbondingPeriod::get(), + }); + + ensure!( + ledger.unbonding_info.len() <= T::MaxUnlocking::get(), + Error::::TooManyUnlockingChunks + ); + + Self::update_ledger(&staker, ledger); + + Self::update_staker_info(&staker, core_id, staker_info); + + Self::deposit_event(Event::::Unstaked { + staker: staker.clone(), + core: core_id, + amount: value_to_unstake, + }); + corrected_staker_length_fee += ::WeightInfo::unstake(); + } else { + // if the staker has moved or already unstaked `internal_unstake` will do one read and return err. + corrected_staker_length_fee += T::DbWeight::get().reads(1); + } + + unsteked_count += 1; + + if unsteked_count >= chunk_size { + let total_remaning_stakers = stakers.saturating_sub(unsteked_count as u32); + let message: Vec = primitives::UnregisterMessage:: { + core_id, + stakers_to_unstake: total_remaning_stakers, + era: start_era, + } + .encode(); + + T::StakingMessage::handle_message(BoundedSlice::truncate_from( + message.as_slice(), + )); + + Self::deposit_event(Event::::CoreUnregistrationChunksProcessed { + core: core_id, + accounts_processed_in_this_chunk: unsteked_count, + accounts_left: total_remaning_stakers as u64, + }); + UnregisteredCoreStakeInfo::::insert(core_id, core_stake_info.clone()); + UnregisteredCoreStakers::::insert(core_id, staker_info_prefix); + + return Ok(Some(corrected_staker_length_fee).into()); + } + } + + Self::deposit_event(Event::::CoreUnregistrationQueueFinished { core: core_id }); + UnregisteredCoreStakers::::remove(core_id); + UnregisteredCoreStakeInfo::::remove(core_id); + + Ok(Some(corrected_staker_length_fee).into()) + } + } +} + +impl QueuePausedQuery for Pallet { + fn is_paused(_origin: &T) -> bool { + Pallet::::is_halted() + } +} + +pub type MessageOriginOf = + <::MessageProcessor as ProcessMessage>::Origin; diff --git a/pallets/OCIF/staking/src/primitives.rs b/pallets/OCIF/staking/src/primitives.rs new file mode 100644 index 00000000..22b350f8 --- /dev/null +++ b/pallets/OCIF/staking/src/primitives.rs @@ -0,0 +1,481 @@ +//! Provides supporting types and traits for the staking pallet. +//! +//! ## Overview +//! +//! Primitives provides the foundational types and traits for a staking pallet. +//! +//! ## Types overview: +//! +//! - `BalanceOf` - A type alias for the balance of a currency in the system. +//! - `CoreMetadata` - A struct that holds metadata for a core entity in the system. +//! - `CoreInfo` - A struct that holds information about a core entity, including its account ID and metadata. +//! - `RewardInfo` - A struct that holds information about rewards, including the balance for stakers and the core. +//! - `EraInfo` - A struct that holds information about a specific era, including rewards, staked balance, active stake, and locked balance. +//! - `CoreStakeInfo` - A struct that holds information about a core's stake, including the total balance, +//! number of stakers, and whether a reward has been claimed. +//! - `EraStake` - A struct that holds information about the stake for a specific era. +//! - `StakerInfo` - A struct that holds information about a staker's stakes across different eras. +//! - `UnlockingChunk` - A struct that holds information about an unlocking chunk of balance. +//! - `UnbondingInfo` - A struct that holds information about unbonding chunks of balance. +//! - `AccountLedger` - A struct that holds information about an account's locked balance and unbonding information. + +use codec::{Decode, Encode, FullCodec, HasCompact, MaxEncodedLen}; +use cumulus_primitives_core::{AggregateMessageOrigin, MultiLocation, ParaId}; +use frame_support::{ + pallet_prelude::Weight, + traits::{Currency, ProcessMessage, QueueFootprint, QueuePausedQuery}, +}; +use pallet_message_queue::OnQueueChanged; +use scale_info::{prelude::marker::PhantomData, TypeInfo}; +use sp_runtime::{ + traits::{AtLeast32BitUnsigned, Zero}, + Perbill, RuntimeDebug, +}; +use sp_std::{fmt::Debug, ops::Add, prelude::*}; + +pub use crate::pallet::*; +use crate::weights::WeightInfo; + +/// The balance type of this pallet. +pub type BalanceOf = + <::Currency as Currency<::AccountId>>::Balance; + +const MAX_ASSUMED_VEC_LEN: u32 = 10; + +/// Metadata for a core entity in the system. +#[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)] +pub struct CoreMetadata { + pub name: Name, + pub description: Description, + pub image: Image, +} + +/// Information about a core entity, including its account ID and metadata. +#[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)] +pub struct CoreInfo { + pub account: AccountId, + pub metadata: Metadata, +} + +/// Information about rewards, including the balance for stakers and the core. +#[derive(PartialEq, Eq, Clone, Default, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)] +pub struct RewardInfo { + #[codec(compact)] + pub(crate) stakers: Balance, + #[codec(compact)] + pub(crate) core: Balance, +} + +/// Information about a specific era, including rewards, staked balance, active stake, and locked balance. +#[derive(PartialEq, Eq, Clone, Default, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)] +pub struct EraInfo { + pub(crate) rewards: RewardInfo, + #[codec(compact)] + pub(crate) staked: Balance, + #[codec(compact)] + pub(crate) active_stake: Balance, + #[codec(compact)] + pub(crate) locked: Balance, +} + +/// Information about a core's stake, including the total balance, number of stakers, and whether a reward has been claimed. +#[derive(Clone, PartialEq, Eq, Encode, Decode, Default, RuntimeDebug, TypeInfo, MaxEncodedLen)] +pub struct CoreStakeInfo { + #[codec(compact)] + pub(crate) total: Balance, + #[codec(compact)] + pub(crate) number_of_stakers: u32, + pub(crate) reward_claimed: bool, + pub(crate) active: bool, +} + +/// Information about the stake for a specific era. +#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] +pub(crate) struct EraStake { + #[codec(compact)] + pub(crate) staked: Balance, + #[codec(compact)] + pub(crate) era: Era, +} + +/// Information about a staker's stakes across different eras. +#[derive(Encode, Decode, Clone, Default, PartialEq, Eq, RuntimeDebug, TypeInfo)] +pub struct StakerInfo { + pub(crate) stakes: Vec>, +} + +impl MaxEncodedLen for StakerInfo { + fn max_encoded_len() -> usize { + codec::Compact(MAX_ASSUMED_VEC_LEN) + .encoded_size() + .saturating_add( + (MAX_ASSUMED_VEC_LEN as usize) + .saturating_mul(EraStake::::max_encoded_len()), + ) + } +} + +impl StakerInfo { + pub(crate) fn is_empty(&self) -> bool { + self.stakes.is_empty() + } + + pub(crate) fn len(&self) -> u32 { + self.stakes.len() as u32 + } + + /// Stakes the given value in the current era, mutates StakerInfo in-place. + pub(crate) fn stake(&mut self, current_era: Era, value: Balance) -> Result<(), &str> { + if let Some(era_stake) = self.stakes.last_mut() { + if era_stake.era > current_era { + return Err("Unexpected era"); + } + + let new_stake_value = era_stake.staked.saturating_add(value); + + if current_era == era_stake.era { + *era_stake = EraStake { + staked: new_stake_value, + era: current_era, + } + } else { + self.stakes.push(EraStake { + staked: new_stake_value, + era: current_era, + }) + } + } else { + self.stakes.push(EraStake { + staked: value, + era: current_era, + }); + } + + Ok(()) + } + + /// Unstakes the given value in the current era, mutates StakerInfo in-place. + pub(crate) fn unstake(&mut self, current_era: Era, value: Balance) -> Result<(), &str> { + if let Some(era_stake) = self.stakes.last_mut() { + if era_stake.era > current_era { + return Err("Unexpected era"); + } + + let new_stake_value = era_stake.staked.saturating_sub(value); + if current_era == era_stake.era { + *era_stake = EraStake { + staked: new_stake_value, + era: current_era, + } + } else { + self.stakes.push(EraStake { + staked: new_stake_value, + era: current_era, + }) + } + + if !self.stakes.is_empty() && self.stakes[0].staked.is_zero() { + self.stakes.remove(0); + } + } + + Ok(()) + } + + /// Claims the stake for the current era, mutates StakerInfo in-place. + /// Returns the era and the staked balance. + pub(crate) fn claim(&mut self) -> (Era, Balance) { + if let Some(era_stake) = self.stakes.first() { + let era_stake = *era_stake; + + // this checks if the last claim was from an older era or if the latest staking info is from + // a newer era compared to the last claim, allowing the user to increase their stake while not losing + // or messing with their stake from the previous eras. + if self.stakes.len() == 1 || self.stakes[1].era > era_stake.era + 1 { + self.stakes[0] = EraStake { + staked: era_stake.staked, + era: era_stake.era.saturating_add(1), + } + } else { + self.stakes.remove(0); + } + + if !self.stakes.is_empty() && self.stakes[0].staked.is_zero() { + self.stakes.remove(0); + } + + (era_stake.era, era_stake.staked) + } else { + (0, Zero::zero()) + } + } + + /// Returns the latest staked balance. + pub(crate) fn latest_staked_value(&self) -> Balance { + self.stakes.last().map_or(Zero::zero(), |x| x.staked) + } +} + +/// A chunk of balance that is unlocking until a specific era. +#[derive( + Clone, PartialEq, Eq, Copy, Encode, Decode, Default, RuntimeDebug, TypeInfo, MaxEncodedLen, +)] +pub(crate) struct UnlockingChunk { + #[codec(compact)] + pub(crate) amount: Balance, + #[codec(compact)] + pub(crate) unlock_era: Era, +} + +impl UnlockingChunk +where + Balance: Add + Copy + MaxEncodedLen, +{ + /// Adds the given amount to the chunk's amount. + pub(crate) fn add_amount(&mut self, amount: Balance) { + self.amount = self.amount + amount + } +} + +/// Information about unbonding chunks of balance. +#[derive(Clone, PartialEq, Eq, Encode, Decode, Default, RuntimeDebug, TypeInfo)] +pub(crate) struct UnbondingInfo { + pub(crate) unlocking_chunks: Vec>, +} + +impl MaxEncodedLen + for UnbondingInfo +{ + fn max_encoded_len() -> usize { + codec::Compact(MAX_ASSUMED_VEC_LEN) + .encoded_size() + .saturating_add( + (MAX_ASSUMED_VEC_LEN as usize) + .saturating_mul(UnlockingChunk::::max_encoded_len()), + ) + } +} + +impl UnbondingInfo +where + Balance: AtLeast32BitUnsigned + Default + Copy + MaxEncodedLen, +{ + pub(crate) fn len(&self) -> u32 { + self.unlocking_chunks.len() as u32 + } + + pub(crate) fn is_empty(&self) -> bool { + self.unlocking_chunks.is_empty() + } + + /// Returns the total amount of the unlocking chunks. + pub(crate) fn sum(&self) -> Balance { + self.unlocking_chunks + .iter() + .map(|chunk| chunk.amount) + .reduce(|c1, c2| c1 + c2) + .unwrap_or_default() + } + + /// Adds the given chunk to the unbonding info. + pub(crate) fn add(&mut self, chunk: UnlockingChunk) { + match self + .unlocking_chunks + .binary_search_by(|x| x.unlock_era.cmp(&chunk.unlock_era)) + { + Ok(pos) => self.unlocking_chunks[pos].add_amount(chunk.amount), + Err(pos) => self.unlocking_chunks.insert(pos, chunk), + } + } + + /// returns the chucks before and after a given era. + pub(crate) fn partition(self, era: Era) -> (Self, Self) { + let (matching_chunks, other_chunks): ( + Vec>, + Vec>, + ) = self + .unlocking_chunks + .iter() + .partition(|chunk| chunk.unlock_era <= era); + + ( + Self { + unlocking_chunks: matching_chunks, + }, + Self { + unlocking_chunks: other_chunks, + }, + ) + } +} + +/// Information about an account's locked balance and unbonding information. +#[derive(Clone, PartialEq, Eq, Encode, Decode, Default, RuntimeDebug, TypeInfo, MaxEncodedLen)] +pub struct AccountLedger { + #[codec(compact)] + pub(crate) locked: Balance, + pub(crate) unbonding_info: UnbondingInfo, +} + +impl AccountLedger { + pub(crate) fn is_empty(&self) -> bool { + self.locked.is_zero() && self.unbonding_info.is_empty() + } +} + +#[derive(Encode, Decode, MaxEncodedLen, Clone, Eq, PartialEq, TypeInfo, Debug)] +pub enum CustomAggregateMessageOrigin { + Aggregate(XcmOrigin), + UnregisterMessageOrigin, +} + +/// Custom Convert a sibling `ParaId` to an `AggregateMessageOrigin`. +pub struct CustomParaIdToSibling; +impl sp_runtime::traits::Convert> + for CustomParaIdToSibling +{ + fn convert(para_id: ParaId) -> CustomAggregateMessageOrigin { + CustomAggregateMessageOrigin::Aggregate(AggregateMessageOrigin::Sibling(para_id)) + } +} + +pub struct CustomNarrowOriginToSibling(PhantomData<(Inner, T)>); +impl, T: Config> + QueuePausedQuery> + for CustomNarrowOriginToSibling +{ + fn is_paused(origin: &CustomAggregateMessageOrigin) -> bool { + match origin { + CustomAggregateMessageOrigin::Aggregate(AggregateMessageOrigin::Sibling(id)) => { + Inner::is_paused(id) + } + CustomAggregateMessageOrigin::Aggregate(_) => false, + CustomAggregateMessageOrigin::UnregisterMessageOrigin => Pallet::::is_halted(), + } + } +} + +impl, T: Config> + OnQueueChanged> + for CustomNarrowOriginToSibling +{ + fn on_queue_changed( + origin: CustomAggregateMessageOrigin, + fp: QueueFootprint, + ) { + match origin { + CustomAggregateMessageOrigin::Aggregate(AggregateMessageOrigin::Sibling(id)) => { + Inner::on_queue_changed(id, fp) + } + CustomAggregateMessageOrigin::Aggregate(_) => (), + CustomAggregateMessageOrigin::UnregisterMessageOrigin => (), + } + } +} + +pub struct CustomMessageProcessor( + PhantomData<(Origin, XcmOrigin, XcmProcessor, C, T)>, +); + +impl ProcessMessage + for CustomMessageProcessor +where + Origin: Into> + + FullCodec + + MaxEncodedLen + + Clone + + Eq + + PartialEq + + TypeInfo + + Debug, + XcmOrigin: + Into + FullCodec + MaxEncodedLen + Clone + Eq + PartialEq + TypeInfo + Debug, + XcmProcessor: ProcessMessage, + T: Config, +{ + type Origin = Origin; + fn process_message( + message: &[u8], + _origin: Self::Origin, + meter: &mut frame_support::weights::WeightMeter, + _id: &mut [u8; 32], + ) -> Result { + match _origin.into() { + CustomAggregateMessageOrigin::Aggregate(o) => { + XcmProcessor::process_message(message, o, meter, _id) + } + CustomAggregateMessageOrigin::UnregisterMessageOrigin => { + let call: UnregisterMessage = UnregisterMessage::::decode(&mut &message[..]) + .map_err(|_| frame_support::traits::ProcessMessageError::Corrupt)?; + + let unstake_weight = ::WeightInfo::unstake(); + + let meter_limit = meter.limit(); + + let thirdy_of_limit = Perbill::from_percent(30) * meter_limit; + + let meter_remaining = meter.remaining(); + + let min_desired = { + // if a third of the proofsize is > 1/2 MB then we use a 1/2 MB for the proofsize weight. + if thirdy_of_limit.proof_size() >= 524288 { + Weight::from_parts(thirdy_of_limit.ref_time(), 524288) + } else { + thirdy_of_limit + } + }; + + // only use less than 30% of all the weight the message queue can provide. + if !meter_remaining.all_gte(Perbill::from_percent(70) * meter_limit) { + return Err(frame_support::traits::ProcessMessageError::Yield); + } + + let max_calls = { + match min_desired.checked_div_per_component(&unstake_weight) { + Some(x) if x > 0 => x.min(100), + _ => return Err(frame_support::traits::ProcessMessageError::Yield), + } + }; + + let max_weight = max_calls * unstake_weight; + + let chunk_result = crate::pallet::Pallet::::process_core_unregistration_shard( + call.stakers_to_unstake, + call.core_id, + call.era, + max_calls, + ); + + match chunk_result { + Ok(weight) => { + if let Some(actual_weight) = weight.actual_weight { + meter.try_consume(actual_weight).map_err(|_| { + frame_support::traits::ProcessMessageError::Overweight( + actual_weight, + ) + })?; + } else { + meter.try_consume(max_weight).map_err(|_| { + frame_support::traits::ProcessMessageError::Overweight(max_weight) + })?; + } + Ok(true) + } + Err(_) => { + meter.try_consume(max_weight).map_err(|_| { + frame_support::traits::ProcessMessageError::Overweight(max_weight) + })?; + Ok(false) + } + } + } + } + } +} + +#[derive(Clone, PartialEq, Eq, Encode, Decode, Default, RuntimeDebug, TypeInfo, MaxEncodedLen)] +pub struct UnregisterMessage { + pub(crate) core_id: T::CoreId, + pub(crate) era: Era, + pub(crate) stakers_to_unstake: u32, +} diff --git a/pallets/OCIF/staking/src/testing/mock.rs b/pallets/OCIF/staking/src/testing/mock.rs new file mode 100644 index 00000000..20b33b60 --- /dev/null +++ b/pallets/OCIF/staking/src/testing/mock.rs @@ -0,0 +1,454 @@ +use crate::{self as pallet_ocif_staking, CustomAggregateMessageOrigin, CustomMessageProcessor}; +use codec::{Decode, Encode}; +use core::convert::{TryFrom, TryInto}; +use cumulus_primitives_core::AggregateMessageOrigin; +use frame_support::{ + construct_runtime, derive_impl, + dispatch::DispatchClass, + parameter_types, + traits::{ + fungibles::Credit, ConstU128, ConstU32, Contains, Currency, OnFinalize, OnInitialize, + }, + weights::{ + constants::{BlockExecutionWeight, ExtrinsicBaseWeight, WEIGHT_REF_TIME_PER_SECOND}, + ConstantMultiplier, Weight, + }, + PalletId, +}; +use pallet_inv4::CoreAccountDerivation; +use scale_info::TypeInfo; +use sp_core::H256; +use sp_io::TestExternalities; +use sp_runtime::{ + traits::{BlakeTwo256, IdentityLookup}, + AccountId32, BuildStorage, Perbill, +}; + +pub(crate) type AccountId = AccountId32; +pub(crate) type BlockNumber = u64; +pub(crate) type Balance = u128; +pub(crate) type EraIndex = u32; + +type Block = frame_system::mocking::MockBlock; + +pub(crate) const EXISTENTIAL_DEPOSIT: Balance = 2; +pub(crate) const MAX_NUMBER_OF_STAKERS: u32 = 4; +pub(crate) const _MAX_NUMBER_OF_STAKERS_TINKERNET: u32 = 10000; +pub(crate) const MINIMUM_STAKING_AMOUNT: Balance = 10; +pub(crate) const MAX_UNLOCKING: u32 = 4; +pub(crate) const UNBONDING_PERIOD: EraIndex = 3; +pub(crate) const MAX_ERA_STAKE_VALUES: u32 = 8; +pub(crate) const BLOCKS_PER_ERA: BlockNumber = 3; +pub(crate) const REGISTER_DEPOSIT: Balance = 10; +const MICROUNIT: Balance = 1_000_000; + +construct_runtime!( + pub struct Test { + System: frame_system, + Balances: pallet_balances, + Timestamp: pallet_timestamp, + OcifStaking: pallet_ocif_staking, + CoreAssets: orml_tokens, + INV4: pallet_inv4, + MessageQueue: pallet_message_queue, + } +); + +parameter_types! { + pub const BlockHashCount: u64 = 250; + pub BlockWeights: frame_system::limits::BlockWeights = + frame_system::limits::BlockWeights::simple_max(Weight::from_parts(1024, 0)); +} + +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +impl frame_system::Config for Test { + type BaseCallFilter = frame_support::traits::Everything; + type RuntimeTask = RuntimeTask; + type RuntimeOrigin = RuntimeOrigin; + type Nonce = u64; + type RuntimeCall = RuntimeCall; + type Block = Block; + type Hash = H256; + type Hashing = BlakeTwo256; + type AccountId = AccountId; + type Lookup = IdentityLookup; + type RuntimeEvent = RuntimeEvent; + type BlockHashCount = BlockHashCount; + type DbWeight = (); + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = pallet_balances::AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = (); + type OnSetCode = (); + type MaxConsumers = frame_support::traits::ConstU32<16>; +} + +parameter_types! { + pub const MaxLocks: u32 = 4; + pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT; +} + +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig as pallet_balances::DefaultConfig)] +impl pallet_balances::Config for Test { + type MaxLocks = MaxLocks; + type MaxReserves = (); + type ReserveIdentifier = [u8; 8]; + type Balance = Balance; + type RuntimeEvent = RuntimeEvent; + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type AccountStore = System; + type WeightInfo = (); + type FreezeIdentifier = [u8; 8]; + type MaxFreezes = (); +} + +parameter_types! { + pub const MinimumPeriod: u64 = 3; +} + +impl pallet_timestamp::Config for Test { + type Moment = u64; + type OnTimestampSet = (); + type MinimumPeriod = MinimumPeriod; + type WeightInfo = (); +} + +parameter_types! { + pub const RegisterDeposit: Balance = REGISTER_DEPOSIT; + pub const BlockPerEra: BlockNumber = BLOCKS_PER_ERA; + pub const MaxStakersPerCore: u32 = MAX_NUMBER_OF_STAKERS; + pub const MinimumStakingAmount: Balance = MINIMUM_STAKING_AMOUNT; + pub const PotId: PalletId = PalletId(*b"ocif-pot"); + pub const MaxUnlocking: u32 = MAX_UNLOCKING; + pub const UnbondingPeriod: EraIndex = UNBONDING_PERIOD; + pub const MaxEraStakeValues: u32 = MAX_ERA_STAKE_VALUES; + pub const RewardRatio: (u32, u32) = (50, 50); +} + +pub type CoreId = u32; + +pub const THRESHOLD: u128 = 50; + +parameter_types! { + pub const MaxMetadata: u32 = 100; + pub const MaxCallers: u32 = 100; + pub const CoreSeedBalance: u32 = 1000000; + pub const CoreCreationFee: u128 = 1000000000000; + pub const GenesisHash: ::Hash = H256([ + 212, 46, 150, 6, 169, 149, 223, 228, 51, 220, 121, 85, 220, 42, 112, 244, 149, 243, 80, + 243, 115, 218, 162, 0, 9, 138, 232, 68, 55, 129, 106, 210, + ]); + pub const RelayAssetId: u32 = 9999; + pub const UnregisterOrigin: CustomAggregateMessageOrigin = CustomAggregateMessageOrigin::UnregisterMessageOrigin; +} + +#[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo, Debug)] +pub struct FeeCharger; + +impl pallet_inv4::fee_handling::MultisigFeeHandler for FeeCharger { + type Pre = ( + // tip + Balance, + // who paid the fee + AccountId, + // imbalance resulting from withdrawing the fee + (), + // asset_id for the transaction payment + Option, + ); + + fn pre_dispatch( + fee_asset: &pallet_inv4::fee_handling::FeeAsset, + who: &AccountId, + _call: &RuntimeCall, + _info: &sp_runtime::traits::DispatchInfoOf, + _len: usize, + ) -> Result { + Ok(( + 0u128, + who.clone(), + (), + match fee_asset { + pallet_inv4::fee_handling::FeeAsset::Native => None, + pallet_inv4::fee_handling::FeeAsset::Relay => Some(1u32), + }, + )) + } + + fn post_dispatch( + _fee_asset: &pallet_inv4::fee_handling::FeeAsset, + _pre: Option, + _info: &sp_runtime::traits::DispatchInfoOf, + _post_info: &sp_runtime::traits::PostDispatchInfoOf, + _len: usize, + _result: &sp_runtime::DispatchResult, + ) -> Result<(), frame_support::unsigned::TransactionValidityError> { + Ok(()) + } + + fn handle_creation_fee( + _imbalance: pallet_inv4::fee_handling::FeeAssetNegativeImbalance< + >::NegativeImbalance, + Credit, + >, + ) { + } +} + +pub struct DustRemovalWhitelist; +impl Contains for DustRemovalWhitelist { + fn contains(_: &AccountId) -> bool { + true + } +} + +pub type Amount = i128; + +orml_traits::parameter_type_with_key! { + pub ExistentialDeposits: |_currency_id: u32| -> Balance { + ExistentialDeposit::get() + }; +} + +impl orml_tokens::Config for Test { + type RuntimeEvent = RuntimeEvent; + type Balance = Balance; + type Amount = Amount; + type CurrencyId = u32; + type WeightInfo = (); + type ExistentialDeposits = ExistentialDeposits; + type MaxLocks = MaxLocks; + type DustRemovalWhitelist = DustRemovalWhitelist; + type MaxReserves = MaxCallers; + type ReserveIdentifier = [u8; 8]; + type CurrencyHooks = (); +} + +impl pallet_inv4::Config for Test { + type MaxMetadata = MaxMetadata; + type CoreId = u32; + type RuntimeEvent = RuntimeEvent; + type Currency = Balances; + type RuntimeCall = RuntimeCall; + type MaxCallers = MaxCallers; + type CoreSeedBalance = CoreSeedBalance; + type AssetsProvider = CoreAssets; + type RuntimeOrigin = RuntimeOrigin; + type CoreCreationFee = CoreCreationFee; + type FeeCharger = FeeCharger; + type WeightInfo = pallet_inv4::weights::SubstrateWeight; + + type Tokens = CoreAssets; + type RelayAssetId = RelayAssetId; + type RelayCoreCreationFee = CoreCreationFee; + type MaxCallSize = ConstU32<51200>; + + type ParaId = ConstU32<2125>; + type LengthToFee = ConstantMultiplier; +} + +impl pallet_ocif_staking::Config for Test { + type RuntimeEvent = RuntimeEvent; + type Currency = Balances; + type BlocksPerEra = BlockPerEra; + type RegisterDeposit = RegisterDeposit; + type MaxStakersPerCore = MaxStakersPerCore; + type MinimumStakingAmount = MinimumStakingAmount; + type PotId = PotId; + type ExistentialDeposit = ExistentialDeposit; + type MaxUnlocking = MaxUnlocking; + type UnbondingPeriod = UnbondingPeriod; + type MaxEraStakeValues = MaxEraStakeValues; + type MaxDescriptionLength = ConstU32<300>; + type MaxNameLength = ConstU32<20>; + type MaxImageUrlLength = ConstU32<60>; + type RewardRatio = RewardRatio; + type StakeThresholdForActiveCore = ConstU128; + type WeightInfo = crate::weights::SubstrateWeight; + type StakingMessage = frame_support::traits::EnqueueWithOrigin; + type WeightToFee = ConstantMultiplier; + type OnUnbalanced = (); +} + +/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used by +/// `Operational` extrinsics. (from tinkernet) +const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); + +/// We allow for 0.5 of a second of compute with a 12 second average block time. +const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts( + WEIGHT_REF_TIME_PER_SECOND.saturating_div(2), + cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64, +); + +/// We assume that ~5% of the block weight is consumed by `on_initialize` handlers. +/// This is used to limit the maximal weight of a single extrinsic. +const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(5); + +parameter_types! { + pub RuntimeBlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights::builder() + .base_block(BlockExecutionWeight::get()) + .for_class(DispatchClass::all(), |weights| { + weights.base_extrinsic = ExtrinsicBaseWeight::get(); + }) + .for_class(DispatchClass::Normal, |weights| { + weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT); + }) + .for_class(DispatchClass::Operational, |weights| { + weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT); + // Operational transactions have some extra reserved space, so that they + // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`. + weights.reserved = Some( + MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT + ); + }) + .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO) + .build_or_panic(); + pub MessageQueueServiceWeight: Weight = Perbill::from_percent(35) * RuntimeBlockWeights::get().max_block; + pub const MessageQueueMaxStale: u32 = 8; + pub const MessageQueueHeapSize: u32 = 128 * 1048; + pub const TransactionByteFee: Balance = 10 * MICROUNIT; + pub const ZeroFee: Balance = 0; +} + +impl pallet_message_queue::Config for Test { + type RuntimeEvent = RuntimeEvent; + type WeightInfo = pallet_message_queue::weights::SubstrateWeight; + #[cfg(feature = "runtime-benchmarks")] + type MessageProcessor = pallet_message_queue::mock_helpers::NoopMessageProcessor< + CustomAggregateMessageOrigin, + >; + #[cfg(not(feature = "runtime-benchmarks"))] + type MessageProcessor = CustomMessageProcessor< + CustomAggregateMessageOrigin, + AggregateMessageOrigin, + pallet_message_queue::mock_helpers::NoopMessageProcessor, + RuntimeCall, + Test, + >; + type Size = u32; + type QueueChangeHandler = (); + type QueuePausedQuery = (); + type HeapSize = MessageQueueHeapSize; + type MaxStale = MessageQueueMaxStale; + type ServiceWeight = MessageQueueServiceWeight; +} +pub struct ExternalityBuilder; + +pub fn account(core: CoreId) -> AccountId { + INV4::derive_core_account(core) +} + +pub const A: CoreId = 0; +pub const B: CoreId = 1; +pub const C: CoreId = 2; +pub const D: CoreId = 3; +pub const E: CoreId = 4; +pub const F: CoreId = 5; +pub const G: CoreId = 6; +pub const H: CoreId = 7; +pub const I: CoreId = 8; +pub const J: CoreId = 9; +pub const K: CoreId = 10; +pub const L: CoreId = 11; +pub const M: CoreId = 12; +pub const N: CoreId = 13; + +impl ExternalityBuilder { + pub fn build() -> TestExternalities { + let storage = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); + + let mut ext = TestExternalities::from(storage); + + ext.execute_with(|| { + Balances::resolve_creating(&account(A), Balances::issue(9000)); + Balances::resolve_creating(&account(B), Balances::issue(800)); + Balances::resolve_creating(&account(C), Balances::issue(10000)); + Balances::resolve_creating(&account(D), Balances::issue(4900)); + Balances::resolve_creating(&account(E), Balances::issue(3800)); + Balances::resolve_creating(&account(F), Balances::issue(10)); + Balances::resolve_creating(&account(G), Balances::issue(1000)); + Balances::resolve_creating(&account(H), Balances::issue(2000)); + Balances::resolve_creating(&account(I), Balances::issue(10000)); + Balances::resolve_creating(&account(J), Balances::issue(300)); + Balances::resolve_creating(&account(K), Balances::issue(400)); + Balances::resolve_creating(&account(L), Balances::issue(10)); + Balances::resolve_creating(&account(M), Balances::issue(EXISTENTIAL_DEPOSIT)); + Balances::resolve_creating(&account(N), Balances::issue(1_000_000_000_000)); + }); + + ext.execute_with(|| System::set_block_number(1)); + + ext + } +} + +pub const ISSUE_PER_BLOCK: Balance = 1000000; + +pub const ISSUE_PER_ERA: Balance = ISSUE_PER_BLOCK * BLOCKS_PER_ERA as u128; + +pub fn run_to_block(n: u64) { + while System::block_number() < n { + OcifStaking::on_finalize(System::block_number()); + System::set_block_number(System::block_number() + 1); + + OcifStaking::rewards(Balances::issue(ISSUE_PER_BLOCK)); + + OcifStaking::on_initialize(System::block_number()); + MessageQueue::on_initialize(System::block_number()); + } +} + +pub fn run_to_block_no_rewards(n: u64) { + while System::block_number() < n { + OcifStaking::on_finalize(System::block_number()); + System::set_block_number(System::block_number() + 1); + OcifStaking::on_initialize(System::block_number()); + MessageQueue::on_initialize(System::block_number()); + } +} + +pub fn issue_rewards(amount: Balance) { + OcifStaking::rewards(Balances::issue(amount)); +} + +pub fn run_for_blocks(n: u64) { + run_to_block(System::block_number() + n); +} + +pub fn run_for_blocks_no_rewards(n: u64) { + run_to_block_no_rewards(System::block_number() + n); +} + +pub fn advance_to_era(n: EraIndex) { + while OcifStaking::current_era() < n { + run_for_blocks(1); + } +} + +pub fn advance_to_era_no_rewards(n: EraIndex) { + while OcifStaking::current_era() < n { + run_for_blocks_no_rewards(1); + } +} + +pub fn initialize_first_block() { + assert_eq!(System::block_number(), 1 as BlockNumber); + + OcifStaking::on_initialize(System::block_number()); + MessageQueue::on_initialize(System::block_number()); + run_to_block(2); +} + +pub fn split_reward_amount(amount: Balance) -> (Balance, Balance) { + let percent = Perbill::from_percent(RewardRatio::get().0); + + let amount_for_core = percent * amount; + + (amount_for_core, amount - amount_for_core) +} diff --git a/pallets/OCIF/staking/src/testing/mod.rs b/pallets/OCIF/staking/src/testing/mod.rs new file mode 100644 index 00000000..7d42b371 --- /dev/null +++ b/pallets/OCIF/staking/src/testing/mod.rs @@ -0,0 +1,454 @@ +use crate::{testing::mock::*, Config, Event, *}; +use frame_support::assert_ok; +use pallet_inv4::CoreAccountDerivation; + +pub mod mock; +pub mod test; + +pub(crate) struct MemorySnapshot { + era_info: EraInfo, + staker_info: StakerInfo, + core_stake_info: CoreStakeInfo, + free_balance: Balance, + ledger: AccountLedger, +} + +impl MemorySnapshot { + pub(crate) fn all(era: EraIndex, core: &CoreId, account: AccountId) -> Self { + Self { + era_info: OcifStaking::general_era_info(era).unwrap(), + staker_info: GeneralStakerInfo::::get(core, &account), + core_stake_info: OcifStaking::core_stake_info(core, era).unwrap_or_default(), + ledger: OcifStaking::ledger(&account), + free_balance: ::Currency::free_balance(&account), + } + } +} + +pub(crate) fn assert_register(core: mock::CoreId) { + let account = INV4::derive_core_account(core); + + let init_reserved_balance = ::Currency::reserved_balance(&account); + + assert!(!RegisteredCore::::contains_key(core)); + + assert_ok!(OcifStaking::register_core( + pallet_inv4::Origin::Multisig(pallet_inv4::origin::MultisigInternalOrigin::new(core)) + .into(), + vec![].try_into().unwrap(), + vec![].try_into().unwrap(), + vec![].try_into().unwrap() + )); + + let core_info = RegisteredCore::::get(core).unwrap(); + assert_eq!(core_info.account, account); + + let final_reserved_balance = ::Currency::reserved_balance(&account); + assert_eq!( + final_reserved_balance, + init_reserved_balance + ::RegisterDeposit::get() + ); +} + +pub(crate) fn short_stake(staker: AccountId, core_id: &CoreId, value: Balance) { + assert_ok!(OcifStaking::stake( + RuntimeOrigin::signed(staker.clone()), + core_id.clone(), + value + )); + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::Staked { + staker, + core: core_id.clone(), + amount: value, + })); +} + +pub(crate) fn assert_stake(staker: AccountId, core: &CoreId, value: Balance) { + let current_era = OcifStaking::current_era(); + let init_state = MemorySnapshot::all(current_era, &core, staker.clone()); + + let available_for_staking = init_state.free_balance + - init_state.ledger.locked + - ::ExistentialDeposit::get(); + let staking_value = available_for_staking.min(value); + + assert_ok!(OcifStaking::stake( + RuntimeOrigin::signed(staker.clone()), + core.clone(), + value + )); + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::Staked { + staker: staker.clone(), + core: core.clone(), + amount: staking_value, + })); + + let final_state = MemorySnapshot::all(current_era, &core, staker.clone()); + + if init_state.staker_info.latest_staked_value() == 0 { + assert!(GeneralStakerInfo::::contains_key( + core, + &staker.clone() + )); + assert_eq!( + final_state.core_stake_info.number_of_stakers, + init_state.core_stake_info.number_of_stakers + 1 + ); + } + + assert_eq!( + final_state.era_info.staked, + init_state.era_info.staked + staking_value + ); + assert_eq!( + final_state.era_info.locked, + init_state.era_info.locked + staking_value + ); + assert_eq!( + final_state.core_stake_info.total, + init_state.core_stake_info.total + staking_value + ); + assert_eq!( + final_state.staker_info.latest_staked_value(), + init_state.staker_info.latest_staked_value() + staking_value + ); + assert_eq!( + final_state.ledger.locked, + init_state.ledger.locked + staking_value + ); +} + +pub(crate) fn assert_unstake(staker: AccountId, core: &CoreId, value: Balance) { + let current_era = OcifStaking::current_era(); + let init_state = MemorySnapshot::all(current_era, &core, staker.clone()); + + let remaining_staked = init_state + .staker_info + .latest_staked_value() + .saturating_sub(value); + let expected_unbond_amount = if remaining_staked < MINIMUM_STAKING_AMOUNT { + init_state.staker_info.latest_staked_value() + } else { + value + }; + let remaining_staked = init_state.staker_info.latest_staked_value() - expected_unbond_amount; + + assert_ok!(OcifStaking::unstake( + RuntimeOrigin::signed(staker.clone()), + core.clone(), + value + )); + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::Unstaked { + staker: staker.clone(), + core: core.clone(), + amount: expected_unbond_amount, + })); + + let final_state = MemorySnapshot::all(current_era, &core, staker.clone()); + let expected_unlock_era = current_era + UNBONDING_PERIOD; + match init_state + .ledger + .unbonding_info + .unlocking_chunks + .binary_search_by(|x| x.unlock_era.cmp(&expected_unlock_era)) + { + Ok(_) => assert_eq!( + init_state.ledger.unbonding_info.len(), + final_state.ledger.unbonding_info.len() + ), + Err(_) => assert_eq!( + init_state.ledger.unbonding_info.len() + 1, + final_state.ledger.unbonding_info.len() + ), + } + assert_eq!( + init_state.ledger.unbonding_info.sum() + expected_unbond_amount, + final_state.ledger.unbonding_info.sum() + ); + + let mut unbonding_info = init_state.ledger.unbonding_info.clone(); + unbonding_info.add(UnlockingChunk { + amount: expected_unbond_amount, + unlock_era: current_era + UNBONDING_PERIOD, + }); + assert_eq!(unbonding_info, final_state.ledger.unbonding_info); + + assert_eq!(init_state.ledger.locked, final_state.ledger.locked); + if final_state.ledger.is_empty() { + assert!(!Ledger::::contains_key(&staker.clone())); + } + + assert_eq!( + init_state.core_stake_info.total - expected_unbond_amount, + final_state.core_stake_info.total + ); + assert_eq!( + init_state.staker_info.latest_staked_value() - expected_unbond_amount, + final_state.staker_info.latest_staked_value() + ); + + let delta = if remaining_staked > 0 { 0 } else { 1 }; + assert_eq!( + init_state.core_stake_info.number_of_stakers - delta, + final_state.core_stake_info.number_of_stakers + ); + + assert_eq!( + init_state.era_info.staked - expected_unbond_amount, + final_state.era_info.staked + ); + assert_eq!(init_state.era_info.locked, final_state.era_info.locked); +} + +pub(crate) fn assert_withdraw_unbonded(staker: AccountId) { + let current_era = OcifStaking::current_era(); + + let init_era_info = GeneralEraInfo::::get(current_era).unwrap(); + let init_ledger = Ledger::::get(&staker); + + let (valid_info, remaining_info) = init_ledger.unbonding_info.partition(current_era); + let expected_unbond_amount = valid_info.sum(); + + assert_ok!(OcifStaking::withdraw_unstaked(RuntimeOrigin::signed( + staker.clone() + ),)); + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::Withdrawn { + staker: staker.clone(), + amount: expected_unbond_amount, + })); + + let final_ledger = Ledger::::get(&staker.clone()); + assert_eq!(remaining_info, final_ledger.unbonding_info); + if final_ledger.unbonding_info.is_empty() && final_ledger.locked == 0 { + assert!(!Ledger::::contains_key(&staker)); + } + + let final_rewards_and_stakes = GeneralEraInfo::::get(current_era).unwrap(); + assert_eq!(final_rewards_and_stakes.staked, init_era_info.staked); + assert_eq!( + final_rewards_and_stakes.locked, + init_era_info.locked - expected_unbond_amount + ); + assert_eq!( + final_ledger.locked, + init_ledger.locked - expected_unbond_amount + ); +} + +pub(crate) fn assert_unregister(core: CoreId) { + let init_reserved_balance = ::Currency::reserved_balance(&account(core)); + + assert_ok!(OcifStaking::unregister_core( + pallet_inv4::Origin::Multisig(pallet_inv4::origin::MultisigInternalOrigin::new(core)) + .into() + )); + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::CoreUnregistered { + core, + })); + + // println!("storage info{:#?}", MessageQueue::storage_info()); + // println!("get queue info{:#?}", MessageQueue::debug_info()); + // println!( + // "footprint: {:#?}", + // MessageQueue::footprint(UnregisterMessageOrigin) + // ); + run_for_blocks(1); + // println!("get queue info{:#?}", MessageQueue::debug_info()); + + let final_reserved_balance = ::Currency::reserved_balance(&account(core)); + assert_eq!( + final_reserved_balance, + init_reserved_balance - ::RegisterDeposit::get() + ); +} + +pub(crate) fn assert_claim_staker(claimer: AccountId, core: CoreId) { + let (claim_era, _) = OcifStaking::staker_info(core, &claimer).claim(); + let current_era = OcifStaking::current_era(); + + System::reset_events(); + + let init_state_claim_era = MemorySnapshot::all(claim_era, &core, claimer.clone()); + let init_state_current_era = MemorySnapshot::all(current_era, &core, claimer.clone()); + + let (_, stakers_joint_reward) = OcifStaking::core_stakers_split( + &init_state_claim_era.core_stake_info, + &init_state_claim_era.era_info, + ); + + let (claim_era, staked) = init_state_claim_era.staker_info.clone().claim(); + + let calculated_reward = + Perbill::from_rational(staked, init_state_claim_era.core_stake_info.total) + * stakers_joint_reward; + let issuance_before_claim = ::Currency::total_issuance(); + + assert_ok!(OcifStaking::staker_claim_rewards( + RuntimeOrigin::signed(claimer.clone()), + core + )); + + let final_state_current_era = MemorySnapshot::all(current_era, &core, claimer.clone()); + + assert_reward( + &init_state_current_era, + &final_state_current_era, + calculated_reward, + ); + + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::StakerClaimed { + staker: claimer.clone(), + core, + era: claim_era, + amount: calculated_reward, + })); + + let (new_era, _) = final_state_current_era.staker_info.clone().claim(); + if final_state_current_era.staker_info.is_empty() { + assert!(new_era.is_zero()); + assert!(!GeneralStakerInfo::::contains_key( + core, + &claimer.clone() + )); + } else { + assert!(new_era > claim_era); + } + assert!(new_era.is_zero() || new_era > claim_era); + + let issuance_after_claim = ::Currency::total_issuance(); + assert_eq!(issuance_before_claim, issuance_after_claim); + + let final_state_claim_era = MemorySnapshot::all(claim_era, &core, claimer); + assert_eq!( + init_state_claim_era.core_stake_info, + final_state_claim_era.core_stake_info + ); +} + +pub(crate) fn assert_claim_core(core: CoreId, claim_era: EraIndex) { + let init_state = MemorySnapshot::all(claim_era, &core, account(core)); + assert!(!init_state.core_stake_info.reward_claimed); + + let (calculated_reward, _) = + OcifStaking::core_stakers_split(&init_state.core_stake_info, &init_state.era_info); + + assert_ok!(OcifStaking::core_claim_rewards( + RuntimeOrigin::signed(account(core)), + core, + claim_era, + )); + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::CoreClaimed { + core, + destination_account: account(core), + era: claim_era, + amount: calculated_reward, + })); + + let final_state = MemorySnapshot::all(claim_era, &core, account(core)); + assert_eq!( + init_state.free_balance + calculated_reward, + final_state.free_balance + ); + + assert!(final_state.core_stake_info.reward_claimed); + + assert_eq!(init_state.staker_info, final_state.staker_info); + assert_eq!(init_state.ledger, final_state.ledger); +} + +fn assert_reward( + init_state_current_era: &MemorySnapshot, + final_state_current_era: &MemorySnapshot, + reward: Balance, +) { + assert_eq!( + init_state_current_era.free_balance + reward, + final_state_current_era.free_balance + ); + assert_eq!( + init_state_current_era.era_info.staked, + final_state_current_era.era_info.staked + ); + assert_eq!( + init_state_current_era.era_info.locked, + final_state_current_era.era_info.locked + ); + assert_eq!( + init_state_current_era.core_stake_info, + final_state_current_era.core_stake_info + ); +} + +pub(crate) fn assert_move_stake( + staker: AccountId, + from_core: &CoreId, + to_core: &CoreId, + amount: Balance, +) { + let current_era = OcifStaking::current_era(); + let from_init_state = MemorySnapshot::all(current_era, &from_core, staker.clone()); + let to_init_state = MemorySnapshot::all(current_era, &to_core, staker.clone()); + + let init_staked_value = from_init_state.staker_info.latest_staked_value(); + let expected_transfer_amount = if init_staked_value - amount >= MINIMUM_STAKING_AMOUNT { + amount + } else { + init_staked_value + }; + + assert_ok!(OcifStaking::move_stake( + RuntimeOrigin::signed(staker.clone()), + from_core.clone(), + amount, + to_core.clone() + )); + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::StakeMoved { + staker: staker.clone(), + from_core: from_core.clone(), + amount: expected_transfer_amount, + to_core: to_core.clone(), + })); + + let from_final_state = MemorySnapshot::all(current_era, &from_core, staker.clone()); + let to_final_state = MemorySnapshot::all(current_era, &to_core, staker.clone()); + + assert_eq!( + from_final_state.staker_info.latest_staked_value(), + init_staked_value - expected_transfer_amount + ); + assert_eq!( + to_final_state.staker_info.latest_staked_value(), + to_init_state.staker_info.latest_staked_value() + expected_transfer_amount + ); + + assert_eq!( + from_final_state.core_stake_info.total, + from_init_state.core_stake_info.total - expected_transfer_amount + ); + assert_eq!( + to_final_state.core_stake_info.total, + to_init_state.core_stake_info.total + expected_transfer_amount + ); + + let from_core_fully_unstaked = init_staked_value == expected_transfer_amount; + if from_core_fully_unstaked { + assert_eq!( + from_final_state.core_stake_info.number_of_stakers + 1, + from_init_state.core_stake_info.number_of_stakers + ); + } + + let no_init_stake_on_to_core = to_init_state.staker_info.latest_staked_value().is_zero(); + if no_init_stake_on_to_core { + assert_eq!( + to_final_state.core_stake_info.number_of_stakers, + to_init_state.core_stake_info.number_of_stakers + 1 + ); + } + + let fully_unstaked_and_nothing_to_claim = + from_core_fully_unstaked && to_final_state.staker_info.clone().claim() == (0, 0); + if fully_unstaked_and_nothing_to_claim { + assert!(!GeneralStakerInfo::::contains_key(&to_core, &staker)); + } +} diff --git a/pallets/OCIF/staking/src/testing/test.rs b/pallets/OCIF/staking/src/testing/test.rs new file mode 100644 index 00000000..d6fa54bd --- /dev/null +++ b/pallets/OCIF/staking/src/testing/test.rs @@ -0,0 +1,2378 @@ +use crate::{ + pallet::{CoreMetadataOf, Error, Event}, + testing::*, + *, +}; +use frame_support::{assert_noop, assert_ok, traits::Currency}; +use mock::Balances; +use sp_runtime::{traits::Zero, Perbill}; + +#[test] +fn on_initialize_when_core_staking_enabled_in_mid_of_an_era_is_ok() { + ExternalityBuilder::build().execute_with(|| { + System::set_block_number(2); + + assert_eq!(0u32, OcifStaking::current_era()); + + OcifStaking::on_initialize(System::block_number()); + assert_eq!(1u32, OcifStaking::current_era()); + }) +} + +#[test] +fn rewards_is_ok() { + ExternalityBuilder::build().execute_with(|| { + assert_eq!(RewardAccumulator::::get(), Default::default()); + assert!(Balances::free_balance(&OcifStaking::account_id()).is_zero()); + + let total_reward = 22344; + OcifStaking::rewards(Balances::issue(total_reward)); + + assert_eq!( + total_reward, + Balances::free_balance(&OcifStaking::account_id()) + ); + let reward_accumulator = RewardAccumulator::::get(); + + let (core_reward, stakers_reward) = split_reward_amount(total_reward); + + assert_eq!(reward_accumulator.stakers, stakers_reward); + assert_eq!(reward_accumulator.core, core_reward); + + OcifStaking::on_initialize(System::block_number()); + assert_eq!(RewardAccumulator::::get(), Default::default()); + assert_eq!( + total_reward, + Balances::free_balance(&OcifStaking::account_id()) + ); + }) +} + +#[test] +fn on_initialize_is_ok() { + ExternalityBuilder::build().execute_with(|| { + assert!(OcifStaking::current_era().is_zero()); + + initialize_first_block(); + let current_era = OcifStaking::current_era(); + assert_eq!(1, current_era); + + let previous_era = current_era; + advance_to_era(previous_era + 10); + + let current_era = OcifStaking::current_era(); + for era in 1..current_era { + let reward_info = GeneralEraInfo::::get(era).unwrap().rewards; + assert_eq!(ISSUE_PER_ERA, reward_info.stakers + reward_info.core); + } + let era_rewards = GeneralEraInfo::::get(current_era).unwrap(); + assert_eq!(0, era_rewards.staked); + assert_eq!(era_rewards.rewards, Default::default()); + }) +} + +#[test] +fn new_era_length_is_always_blocks_per_era() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + let blocks_per_era = mock::BLOCKS_PER_ERA; + + advance_to_era(mock::OcifStaking::current_era() + 1); + + let start_era = mock::OcifStaking::current_era(); + let starting_block_number = System::block_number(); + + advance_to_era(mock::OcifStaking::current_era() + 1); + let ending_block_number = System::block_number(); + + assert_eq!(mock::OcifStaking::current_era(), start_era + 1); + assert_eq!(ending_block_number - starting_block_number, blocks_per_era); + }) +} + +#[test] +fn new_era_is_ok() { + ExternalityBuilder::build().execute_with(|| { + advance_to_era(OcifStaking::current_era() + 10); + let starting_era = OcifStaking::current_era(); + + assert_eq!(OcifStaking::reward_accumulator(), Default::default()); + + run_for_blocks(1); + let current_era = OcifStaking::current_era(); + assert_eq!(starting_era, current_era); + + let block_reward = OcifStaking::reward_accumulator(); + assert_eq!(ISSUE_PER_BLOCK, block_reward.stakers + block_reward.core); + + let staker = account(C); + let staked_amount = 100; + assert_register(A); + assert_stake(staker, &A, staked_amount); + + advance_to_era(OcifStaking::current_era() + 1); + + let current_era = OcifStaking::current_era(); + assert_eq!(starting_era + 1, current_era); + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::NewEra { + era: starting_era + 1, + })); + + let block_reward = OcifStaking::reward_accumulator(); + assert_eq!(block_reward, Default::default()); + + let expected_era_reward = ISSUE_PER_ERA; + + let (expected_core_reward, expected_stakers_reward) = split_reward_amount(ISSUE_PER_ERA); + + let era_rewards = GeneralEraInfo::::get(starting_era).unwrap(); + assert_eq!(staked_amount, era_rewards.staked); + assert_eq!( + expected_era_reward, + era_rewards.rewards.core + era_rewards.rewards.stakers + ); + assert_eq!(expected_core_reward, era_rewards.rewards.core); + assert_eq!(expected_stakers_reward, era_rewards.rewards.stakers); + }) +} + +#[test] +fn general_staker_info_is_ok() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + assert_register(A); + + assert_register(B); + + let (staker_1, staker_2, staker_3) = (account(C), account(D), account(E)); + let amount = 100; + + let starting_era = 3; + advance_to_era(starting_era); + assert_stake(staker_1.clone(), &A, amount); + assert_stake(staker_2.clone(), &A, amount); + + let mid_era = 7; + advance_to_era(mid_era); + assert_unstake(staker_2.clone(), &A, amount); + assert_stake(staker_3.clone(), &A, amount); + assert_stake(staker_3.clone(), &B, amount); + + let final_era = 12; + advance_to_era(final_era); + + let mut first_staker_info = OcifStaking::staker_info(&A, &staker_1.clone()); + let mut second_staker_info = OcifStaking::staker_info(&A, &staker_2.clone()); + let mut third_staker_info = OcifStaking::staker_info(&A, &staker_3.clone()); + + for era in starting_era..mid_era { + let core_info = OcifStaking::core_stake_info(&A, era).unwrap(); + assert_eq!(2, core_info.number_of_stakers); + + assert_eq!((era, amount), first_staker_info.claim()); + assert_eq!((era, amount), second_staker_info.claim()); + + assert!(!CoreEraStake::::contains_key(&B, era)); + } + + for era in mid_era..=final_era { + let first_core_info = OcifStaking::core_stake_info(&A, era).unwrap(); + assert_eq!(2, first_core_info.number_of_stakers); + + assert_eq!((era, amount), first_staker_info.claim()); + assert_eq!((era, amount), third_staker_info.claim()); + + assert_eq!( + OcifStaking::core_stake_info(&B, era) + .unwrap() + .number_of_stakers, + 1 + ); + } + + assert!(!CoreEraStake::::contains_key(&A, starting_era - 1)); + assert!(!CoreEraStake::::contains_key(&B, starting_era - 1)); + }) +} + +#[test] +fn register_is_ok() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + assert!(::Currency::reserved_balance(&account(A)).is_zero()); + assert_register(A); + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::CoreRegistered { + core: A, + })); + + assert_eq!( + RegisterDeposit::get(), + ::Currency::reserved_balance(&account(A)) + ); + }) +} + +#[test] +fn register_twice_with_same_account_fails() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + assert_register(A); + + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::CoreRegistered { + core: A, + })); + + assert_noop!( + OcifStaking::register_core( + pallet_inv4::Origin::Multisig(pallet_inv4::origin::MultisigInternalOrigin::new(A)) + .into(), + Vec::default().try_into().unwrap(), + Vec::default().try_into().unwrap(), + Vec::default().try_into().unwrap() + ), + Error::::CoreAlreadyRegistered + ); + }) +} + +#[test] +fn change_metadata() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let core_id = A; + + assert_register(core_id); + + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::CoreRegistered { + core: core_id, + })); + + assert_eq!( + OcifStaking::core_info(core_id), + Some(CoreInfo { + account: account(core_id), + metadata: CoreMetadata { + name: BoundedVec::default(), + description: BoundedVec::default(), + image: BoundedVec::default() + } + }) + ); + + let new_metadata: CoreMetadataOf = CoreMetadata { + name: b"Test CORE".to_vec().try_into().unwrap(), + description: b"Description of the test CORE".to_vec().try_into().unwrap(), + image: b"https://test.core".to_vec().try_into().unwrap(), + }; + + assert_ok!(OcifStaking::change_core_metadata( + pallet_inv4::Origin::Multisig(pallet_inv4::origin::MultisigInternalOrigin::new( + core_id + )) + .into(), + b"Test CORE".to_vec().try_into().unwrap(), + b"Description of the test CORE".to_vec().try_into().unwrap(), + b"https://test.core".to_vec().try_into().unwrap(), + )); + + assert_eq!( + OcifStaking::core_info(core_id), + Some(CoreInfo { + account: account(core_id), + metadata: new_metadata + }) + ); + }) +} + +#[test] +fn unregister_after_register_is_ok() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + assert_register(A); + assert_unregister(A); + + assert!(::Currency::reserved_balance(&account(A)).is_zero()); + + assert_noop!( + OcifStaking::unregister_core( + pallet_inv4::Origin::Multisig(pallet_inv4::origin::MultisigInternalOrigin::new(A)) + .into() + ), + Error::::NotRegistered + ); + }) +} + +#[test] +fn unregister_stake_and_unstake_is_not_ok() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let staker = account(C); + + assert_register(A); + assert_stake(staker.clone(), &A, 100); + assert_unstake(staker.clone(), &A, 10); + + assert_unregister(A); + + assert_noop!( + OcifStaking::stake(RuntimeOrigin::signed(staker.clone()), A, 100), + Error::::NotRegistered + ); + assert_noop!( + OcifStaking::unstake(RuntimeOrigin::signed(staker.clone()), A, 100), + Error::::NotRegistered + ); + }) +} + +#[test] +fn withdraw_from_unregistered_is_ok() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let staker_1 = account(D); + let staker_2 = account(E); + let staked_value_1 = 150; + let staked_value_2 = 330; + let core_id = A; + let dummy_core_id = B; + + assert_register(core_id); + assert_register(dummy_core_id); + assert_stake(staker_1.clone(), &core_id, staked_value_1); + assert_stake(staker_2.clone(), &core_id, staked_value_2); + + assert_stake(staker_1.clone(), &dummy_core_id, staked_value_1); + + advance_to_era(5); + + assert_unregister(core_id); + + for era in 1..OcifStaking::current_era() { + assert_claim_staker(staker_1.clone(), core_id); + assert_claim_staker(staker_2.clone(), core_id); + + assert_claim_core(core_id, era); + } + + assert_noop!( + OcifStaking::staker_claim_rewards(RuntimeOrigin::signed(staker_1.clone()), core_id), + Error::::NoStakeAvailable + ); + assert_noop!( + OcifStaking::staker_claim_rewards(RuntimeOrigin::signed(staker_2.clone()), core_id), + Error::::NoStakeAvailable + ); + assert_noop!( + OcifStaking::core_claim_rewards( + RuntimeOrigin::signed(account(core_id)), + core_id, + OcifStaking::current_era() + ), + Error::::IncorrectEra + ); + + advance_to_era(8); + + assert_withdraw_unbonded(staker_1); + assert_withdraw_unbonded(staker_2); + }) +} + +#[test] +fn bond_and_stake_different_eras_is_ok() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let staker_id = account(B); + let core_id = A; + assert_register(core_id); + + let current_era = OcifStaking::current_era(); + assert!(OcifStaking::core_stake_info(&core_id, current_era).is_none()); + + assert_stake(staker_id.clone(), &core_id, 100); + + advance_to_era(current_era + 2); + + assert_stake(staker_id, &core_id, 300); + }) +} + +#[test] +fn bond_and_stake_two_different_core_is_ok() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let staker_id = account(B); + let first_core_id = A; + let second_core_id = C; + + assert_register(first_core_id); + assert_register(second_core_id); + + assert_stake(staker_id.clone(), &first_core_id, 100); + assert_stake(staker_id, &second_core_id, 300); + }) +} + +#[test] +fn bond_and_stake_two_stakers_one_core_is_ok() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let first_staker_id = account(B); + let second_staker_id = account(C); + let first_stake_value = 50; + let second_stake_value = 235; + let core_id = A; + + assert_register(core_id); + + assert_stake(first_staker_id, &core_id, first_stake_value); + assert_stake(second_staker_id, &core_id, second_stake_value); + }) +} + +#[test] +fn bond_and_stake_different_value_is_ok() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let staker_id = account(B); + let core_id = A; + + assert_register(core_id); + + let staker_free_balance = + Balances::free_balance(&staker_id).saturating_sub(EXISTENTIAL_DEPOSIT); + assert_stake(staker_id.clone(), &core_id, staker_free_balance - 1); + + assert_stake(staker_id.clone(), &core_id, 1); + + let staker_id = account(C); + let staker_free_balance = Balances::free_balance(&staker_id); + assert_stake(staker_id.clone(), &core_id, staker_free_balance + 1); + + let transferable_balance = + Balances::free_balance(&staker_id.clone()) - Ledger::::get(staker_id).locked; + assert_eq!(EXISTENTIAL_DEPOSIT, transferable_balance); + + let staker_id = account(D); + let staker_free_balance = + Balances::free_balance(&staker_id).saturating_sub(EXISTENTIAL_DEPOSIT); + assert_stake(staker_id.clone(), &core_id, staker_free_balance - 200); + + assert_stake(staker_id.clone(), &core_id, 500); + }) +} + +#[test] +fn bond_and_stake_on_unregistered_core_fails() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let staker_id = account(B); + let stake_value = 100; + + let core_id = A; + assert_noop!( + OcifStaking::stake(RuntimeOrigin::signed(staker_id), core_id, stake_value), + Error::::NotRegistered + ); + }) +} + +#[test] +fn bond_and_stake_insufficient_value() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + let staker_id = account(B); + let core_id = A; + + assert_register(core_id); + + assert_noop!( + OcifStaking::stake( + RuntimeOrigin::signed(staker_id.clone()), + core_id, + MINIMUM_STAKING_AMOUNT - 1 + ), + Error::::InsufficientBalance + ); + + let staker_free_balance = Balances::free_balance(&staker_id.clone()); + assert_stake(staker_id.clone(), &core_id, staker_free_balance); + + assert_noop!( + OcifStaking::stake(RuntimeOrigin::signed(staker_id.clone()), core_id, 1), + Error::::StakingNothing + ); + }) +} + +#[test] +fn bond_and_stake_too_many_stakers_per_core() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let core_id = A; + assert_register(core_id); + + for staker_id in 1..=MAX_NUMBER_OF_STAKERS { + assert_stake(account(staker_id.into()), &core_id, 100); + } + + assert_noop!( + OcifStaking::stake( + RuntimeOrigin::signed(account((1 + MAX_NUMBER_OF_STAKERS).into())), + core_id, + 100 + ), + Error::::MaxStakersReached + ); + }) +} + +#[test] +fn bond_and_stake_too_many_era_stakes() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let staker_id = account(B); + let core_id = A; + assert_register(core_id); + + let start_era = OcifStaking::current_era(); + for offset in 1..MAX_ERA_STAKE_VALUES { + assert_stake(staker_id.clone(), &core_id, 100); + advance_to_era(start_era + offset); + } + + assert_noop!( + OcifStaking::stake(RuntimeOrigin::signed(staker_id.into()), core_id, 100), + Error::::TooManyEraStakeValues + ); + }) +} + +#[test] +fn unbond_and_unstake_multiple_time_is_ok() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let staker_id = account(B); + let core_id = A; + let original_staked_value = 300 + EXISTENTIAL_DEPOSIT; + let old_era = OcifStaking::current_era(); + + assert_register(core_id); + assert_stake(staker_id.clone(), &core_id, original_staked_value); + advance_to_era(old_era + 1); + + let unstaked_value = 100; + assert_unstake(staker_id.clone(), &core_id, unstaked_value); + + let unstaked_value = 50; + assert_unstake(staker_id.clone(), &core_id, unstaked_value); + }) +} + +#[test] +fn unbond_and_unstake_value_below_staking_threshold() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let staker_id = account(B); + let core_id = A; + let first_value_to_unstake = 300; + let staked_value = first_value_to_unstake + MINIMUM_STAKING_AMOUNT; + + assert_register(core_id); + assert_stake(staker_id.clone(), &core_id, staked_value); + + assert_unstake(staker_id.clone(), &core_id, first_value_to_unstake); + + assert_unstake(staker_id.clone(), &core_id, 1); + }) +} + +#[test] +fn unbond_and_unstake_in_different_eras() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let (first_staker_id, second_staker_id) = (account(B), account(C)); + let core_id = A; + let staked_value = 500; + + assert_register(core_id); + assert_stake(first_staker_id.clone(), &core_id, staked_value); + assert_stake(second_staker_id.clone(), &core_id, staked_value); + + advance_to_era(OcifStaking::current_era() + 10); + let current_era = OcifStaking::current_era(); + assert_unstake(first_staker_id.clone(), &core_id, 100); + + advance_to_era(current_era + 10); + assert_unstake(second_staker_id.clone(), &core_id, 333); + }) +} + +#[test] +fn unbond_and_unstake_calls_in_same_era_can_exceed_max_chunks() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let core_id = A; + assert_register(core_id); + + let staker = account(B); + assert_stake(staker.clone(), &core_id, 200 * MAX_UNLOCKING as Balance); + + for _ in 0..MAX_UNLOCKING * 2 { + assert_unstake(staker.clone(), &core_id, 10); + assert_eq!(1, Ledger::::get(&staker.clone()).unbonding_info.len()); + } + }) +} + +#[test] +fn unbond_and_unstake_with_zero_value_is_not_ok() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let core_id = A; + assert_register(core_id); + + assert_noop!( + OcifStaking::unstake(RuntimeOrigin::signed(account(B)), core_id, 0), + Error::::UnstakingNothing + ); + }) +} + +#[test] +fn unbond_and_unstake_on_not_registered_core_is_not_ok() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let core_id = A; + assert_noop!( + OcifStaking::unstake(RuntimeOrigin::signed(account(B)), core_id, 100), + Error::::NotRegistered + ); + }) +} + +#[test] +fn unbond_and_unstake_too_many_unlocking_chunks_is_not_ok() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let core_id = A; + assert_register(core_id); + + let staker = account(B); + let unstake_amount = 10; + let stake_amount = MINIMUM_STAKING_AMOUNT * 10 + unstake_amount * MAX_UNLOCKING as Balance; + + assert_stake(staker.clone(), &core_id, stake_amount); + + for _ in 0..MAX_UNLOCKING { + advance_to_era(OcifStaking::current_era() + 1); + assert_unstake(staker.clone(), &core_id, unstake_amount); + } + + assert_eq!( + MAX_UNLOCKING, + OcifStaking::ledger(&staker).unbonding_info.len() + ); + assert_unstake(staker.clone(), &core_id, unstake_amount); + + advance_to_era(OcifStaking::current_era() + 1); + assert_noop!( + OcifStaking::unstake( + RuntimeOrigin::signed(staker.clone()), + core_id.clone(), + unstake_amount + ), + Error::::TooManyUnlockingChunks, + ); + }) +} + +#[test] +fn unbond_and_unstake_on_not_staked_core_is_not_ok() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let core_id = A; + assert_register(core_id); + + assert_noop!( + OcifStaking::unstake(RuntimeOrigin::signed(account(B)), core_id, 10), + Error::::NoStakeAvailable, + ); + }) +} + +#[test] +fn unbond_and_unstake_too_many_era_stakes() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let staker_id = account(B); + let core_id = A; + assert_register(core_id); + + let start_era = OcifStaking::current_era(); + for offset in 1..MAX_ERA_STAKE_VALUES { + assert_stake(staker_id.clone(), &core_id, 100); + advance_to_era(start_era + offset); + } + + assert_noop!( + OcifStaking::unstake(RuntimeOrigin::signed(staker_id), core_id, 10), + Error::::TooManyEraStakeValues + ); + }) +} + +#[test] +fn withdraw_unbonded_is_ok() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let core_id = A; + assert_register(core_id); + + let staker_id = account(B); + assert_stake(staker_id.clone(), &core_id, 1000); + + let first_unbond_value = 75; + let second_unbond_value = 39; + let initial_era = OcifStaking::current_era(); + + assert_unstake(staker_id.clone(), &core_id, first_unbond_value); + + advance_to_era(initial_era + 1); + assert_unstake(staker_id.clone(), &core_id, second_unbond_value); + + advance_to_era(initial_era + UNBONDING_PERIOD - 1); + assert_noop!( + OcifStaking::withdraw_unstaked(RuntimeOrigin::signed(staker_id.clone())), + Error::::NothingToWithdraw + ); + + advance_to_era(OcifStaking::current_era() + 1); + assert_ok!(OcifStaking::withdraw_unstaked(RuntimeOrigin::signed( + staker_id.clone() + ),)); + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::Withdrawn { + staker: staker_id.clone(), + amount: first_unbond_value, + })); + + advance_to_era(OcifStaking::current_era() + 1); + assert_ok!(OcifStaking::withdraw_unstaked(RuntimeOrigin::signed( + staker_id.clone() + ),)); + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::Withdrawn { + staker: staker_id.clone(), + amount: second_unbond_value, + })); + + advance_to_era(initial_era + UNBONDING_PERIOD - 1); + assert_noop!( + OcifStaking::withdraw_unstaked(RuntimeOrigin::signed(staker_id.clone())), + Error::::NothingToWithdraw + ); + }) +} + +#[test] +fn withdraw_unbonded_full_vector_is_ok() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let core_id = A; + assert_register(core_id); + + let staker_id = account(B); + assert_stake(staker_id.clone(), &core_id, 1000); + + let init_unbonding_amount = 15; + for x in 1..=MAX_UNLOCKING { + assert_unstake( + staker_id.clone(), + &core_id, + init_unbonding_amount * x as u128, + ); + advance_to_era(OcifStaking::current_era() + 1); + } + + assert_withdraw_unbonded(staker_id.clone()); + + assert!(!Ledger::::get(&staker_id.clone()) + .unbonding_info + .is_empty()); + + while !Ledger::::get(&staker_id.clone()) + .unbonding_info + .is_empty() + { + advance_to_era(OcifStaking::current_era() + 1); + assert_withdraw_unbonded(staker_id.clone()); + } + }) +} + +#[test] +fn withdraw_unbonded_no_value_is_not_ok() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + assert_noop!( + OcifStaking::withdraw_unstaked(RuntimeOrigin::signed(account(B))), + Error::::NothingToWithdraw, + ); + }) +} + +#[test] +fn claim_not_staked_core() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let staker = account(B); + let core_id = A; + + assert_register(core_id); + + assert_noop!( + OcifStaking::staker_claim_rewards(RuntimeOrigin::signed(staker), core_id), + Error::::NoStakeAvailable + ); + + advance_to_era(OcifStaking::current_era() + 1); + assert_noop!( + OcifStaking::core_claim_rewards(RuntimeOrigin::signed(account(core_id)), core_id, 1), + Error::::NoStakeAvailable + ); + }) +} + +#[test] +fn claim_not_registered_core() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let staker = account(B); + let core_id = A; + + assert_register(core_id); + assert_stake(staker.clone(), &core_id, 100); + + advance_to_era(OcifStaking::current_era() + 1); + assert_unregister(core_id); + + assert_claim_staker(staker.clone(), core_id); + assert_noop!( + OcifStaking::staker_claim_rewards(RuntimeOrigin::signed(staker.clone()), core_id), + Error::::NoStakeAvailable + ); + + assert_claim_core(core_id, 1); + assert_noop!( + OcifStaking::core_claim_rewards(RuntimeOrigin::signed(account(core_id)), core_id, 2), + Error::::IncorrectEra + ); + }) +} + +#[test] +fn claim_invalid_era() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let staker = account(B); + let core_id = A; + + let start_era = OcifStaking::current_era(); + assert_register(core_id); + assert_stake(staker.clone(), &core_id, 100); + advance_to_era(start_era + 5); + + for era in start_era..OcifStaking::current_era() { + assert_claim_staker(staker.clone(), core_id); + assert_claim_core(core_id, era); + } + + assert_noop!( + OcifStaking::staker_claim_rewards(RuntimeOrigin::signed(staker), core_id), + Error::::IncorrectEra + ); + assert_noop!( + OcifStaking::core_claim_rewards( + RuntimeOrigin::signed(account(core_id)), + core_id, + OcifStaking::current_era() + ), + Error::::IncorrectEra + ); + }) +} + +#[test] +fn claim_core_same_era_twice() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let staker = account(B); + let core_id = A; + + let start_era = OcifStaking::current_era(); + assert_register(core_id); + assert_stake(staker, &core_id, 100); + advance_to_era(start_era + 1); + + assert_claim_core(core_id, start_era); + assert_noop!( + OcifStaking::core_claim_rewards( + RuntimeOrigin::signed(account(core_id)), + core_id, + start_era + ), + Error::::RewardAlreadyClaimed + ); + }) +} + +#[test] +fn claim_is_ok() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let first_staker = account(D); + let second_staker = account(E); + let first_core_id = A; + let second_core_id = B; + + let start_era = OcifStaking::current_era(); + + assert_register(first_core_id); + assert_register(second_core_id); + assert_stake(first_staker.clone(), &first_core_id, 100); + assert_stake(second_staker.clone(), &first_core_id, 45); + + assert_stake(first_staker.clone(), &second_core_id, 33); + assert_stake(second_staker.clone(), &second_core_id, 22); + + let eras_advanced = 3; + advance_to_era(start_era + eras_advanced); + + for x in 0..eras_advanced.into() { + assert_stake(first_staker.clone(), &first_core_id, 20 + x * 3); + assert_stake(second_staker.clone(), &first_core_id, 5 + x * 5); + advance_to_era(OcifStaking::current_era() + 1); + } + + let current_era = OcifStaking::current_era(); + for era in start_era..current_era { + assert_claim_staker(first_staker.clone(), first_core_id); + assert_claim_core(first_core_id, era); + assert_claim_staker(second_staker.clone(), first_core_id); + } + + assert_noop!( + OcifStaking::staker_claim_rewards( + RuntimeOrigin::signed(first_staker), + first_core_id.clone() + ), + Error::::IncorrectEra + ); + assert_noop!( + OcifStaking::core_claim_rewards( + RuntimeOrigin::signed(account(first_core_id)), + first_core_id, + current_era + ), + Error::::IncorrectEra + ); + }) +} + +#[test] +fn claim_check_amount() { + ExternalityBuilder::build().execute_with(|| { + assert_eq!(System::block_number(), 1 as BlockNumber); + + OcifStaking::on_initialize(System::block_number()); + + let first_staker = account(C); + let second_staker = account(D); + let first_core_id = A; + let second_core_id = B; + + assert_eq!(OcifStaking::current_era(), 1); + + // Make sure current block is 1. + assert_eq!(System::block_number(), 1); + + assert_register(first_core_id); + assert_register(second_core_id); + + // 130 for stakers, 130 for Core. + issue_rewards(260); + + run_to_block_no_rewards(2); + + // Make sure current block is 2. + assert_eq!(System::block_number(), 2); + + // User stakes in the middle of era 1, their stake should not account for era 1. + assert_stake(first_staker.clone(), &first_core_id, 100); + assert_stake(second_staker.clone(), &second_core_id, 30); + + advance_to_era_no_rewards(2); + + // Make sure current era is 2. + assert_eq!(OcifStaking::current_era(), 2); + + // 130 for stakers, 130 for Core. + issue_rewards(260); + + // Nothing else happens in era 2. + advance_to_era_no_rewards(3); + + assert_eq!( + OcifStaking::core_stake_info(first_core_id, 1), + Some(CoreStakeInfo { + total: 100, + number_of_stakers: 1, + reward_claimed: false, + active: false + }) + ); + + assert_eq!( + OcifStaking::core_stake_info(second_core_id, 1), + Some(CoreStakeInfo { + total: 30, + number_of_stakers: 1, + reward_claimed: false, + active: false + }) + ); + + assert_eq!( + OcifStaking::general_era_info(1), + Some(EraInfo { + rewards: RewardInfo { + stakers: 130, + core: 130 + }, + staked: 130, + active_stake: 100, + locked: 130 + }) + ); + + assert_eq!( + OcifStaking::core_stake_info(first_core_id, 2), + Some(CoreStakeInfo { + total: 100, + number_of_stakers: 1, + reward_claimed: false, + active: true + }) + ); + + assert_eq!( + OcifStaking::core_stake_info(second_core_id, 2), + Some(CoreStakeInfo { + total: 30, + number_of_stakers: 1, + reward_claimed: false, + active: false + }) + ); + + assert_eq!( + OcifStaking::general_era_info(2), + Some(EraInfo { + rewards: RewardInfo { + stakers: 130, + core: 130 + }, + staked: 130, + active_stake: 100, + locked: 130 + }) + ); + + // Let's try claiming rewards for era 1 for the first core... + assert_ok!(OcifStaking::core_claim_rewards( + RuntimeOrigin::signed(account(first_core_id)), + first_core_id, + 1 + )); + + // ...there should be nothing. + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::CoreClaimed { + core: first_core_id, + destination_account: account(first_core_id), + era: 1, + amount: 0, + })); + + // Let's try claiming rewards for era 1 for the second core... + assert_ok!(OcifStaking::core_claim_rewards( + RuntimeOrigin::signed(account(second_core_id)), + second_core_id, + 1 + )); + + // ...there should be nothing. + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::CoreClaimed { + core: second_core_id, + destination_account: account(second_core_id), + era: 1, + amount: 0, + })); + + // Now let's try claiming rewards for era 2 for the first core... + assert_ok!(OcifStaking::core_claim_rewards( + RuntimeOrigin::signed(account(first_core_id)), + first_core_id, + 2 + )); + + // ...there should be 130 since it's 50% of the issue 260 and the second core shouldn't be active yet. + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::CoreClaimed { + core: first_core_id, + destination_account: account(first_core_id), + era: 2, + amount: 130, + })); + + // Now let's try claiming rewards for era 2 for the second core... + assert_ok!(OcifStaking::core_claim_rewards( + RuntimeOrigin::signed(account(second_core_id)), + second_core_id, + 2 + )); + + // ...there should be 0 since the current stake is 30, which is below the active threshold. + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::CoreClaimed { + core: second_core_id, + destination_account: account(second_core_id), + era: 2, + amount: 0, + })); + + // User stakes in the middle of era 3, their stake should not account for era 3. + assert_stake(first_staker.clone(), &second_core_id, 20); + + advance_to_era_no_rewards(4); + + // Make sure current era is 4. + assert_eq!(OcifStaking::current_era(), 4); + + // 150 for stakers, 150 for Core. + issue_rewards(300); + + // Nothing else happens in era 4. + advance_to_era_no_rewards(5); + + assert_eq!( + OcifStaking::core_stake_info(first_core_id, 4), + Some(CoreStakeInfo { + total: 100, + number_of_stakers: 1, + reward_claimed: false, + active: true + }) + ); + + assert_eq!( + OcifStaking::core_stake_info(second_core_id, 4), + Some(CoreStakeInfo { + total: 50, + number_of_stakers: 2, + reward_claimed: false, + active: true + }) + ); + + assert_eq!( + OcifStaking::general_era_info(4), + Some(EraInfo { + rewards: RewardInfo { + stakers: 150, + core: 150 + }, + staked: 150, + active_stake: 150, + locked: 150 + }) + ); + + // Let's try claiming rewards for era 4 for the first core... + assert_ok!(OcifStaking::core_claim_rewards( + RuntimeOrigin::signed(account(first_core_id)), + first_core_id, + 4 + )); + + // ...there should be 100 out of the 150, because the second core should be active now. + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::CoreClaimed { + core: first_core_id, + destination_account: account(first_core_id), + era: 4, + amount: 100, + })); + + // Let's try claiming rewards for era 4 for the second core... + assert_ok!(OcifStaking::core_claim_rewards( + RuntimeOrigin::signed(account(second_core_id)), + second_core_id, + 4 + )); + + // ...there should be 50 out of the 150, because the second core should be active now. + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::CoreClaimed { + core: second_core_id, + destination_account: account(second_core_id), + era: 4, + amount: 50, + })); + + // Now let's check the same stuff for the stakers instead of the core. + + assert_eq!( + OcifStaking::staker_info(first_core_id, first_staker.clone()), + StakerInfo { + stakes: vec![EraStake { + staked: 100, + era: 1 + }] + } + ); + + assert_eq!( + OcifStaking::staker_info(second_core_id, first_staker.clone()), + StakerInfo { + stakes: vec![EraStake { staked: 20, era: 3 }] + } + ); + + assert_eq!( + OcifStaking::staker_info(second_core_id, second_staker.clone()), + StakerInfo { + stakes: vec![EraStake { staked: 30, era: 1 }] + } + ); + + assert_eq!( + OcifStaking::staker_info(first_core_id, second_staker.clone()), + StakerInfo { stakes: vec![] } + ); + + // Era 1: + + // Let's try claiming rewards for the first staker in the first core... + assert_ok!(OcifStaking::staker_claim_rewards( + RuntimeOrigin::signed(first_staker.clone()), + first_core_id, + )); + + // ...there should be 100 out of the 130, because the second staker had 30 staked in era 1. + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::StakerClaimed { + staker: first_staker.clone(), + core: first_core_id, + era: 1, + amount: 100, + })); + + // Let's try claiming rewards for the second staker in the second core... + assert_ok!(OcifStaking::staker_claim_rewards( + RuntimeOrigin::signed(second_staker.clone()), + second_core_id, + )); + + // ...there should be 30 out of the 130, because the first staker had 100 staked in era 1. + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::StakerClaimed { + staker: second_staker.clone(), + core: second_core_id, + era: 1, + amount: 30, + })); + + // Era 2: + + // Let's try claiming rewards for the first staker in the first core... + assert_ok!(OcifStaking::staker_claim_rewards( + RuntimeOrigin::signed(first_staker.clone()), + first_core_id, + )); + + // ...there should be 100 out of the 130, because the second staker had 30 staked in era 2. + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::StakerClaimed { + staker: first_staker.clone(), + core: first_core_id, + era: 2, + amount: 100, + })); + + // Let's try claiming rewards for the second staker in the second core... + assert_ok!(OcifStaking::staker_claim_rewards( + RuntimeOrigin::signed(second_staker.clone()), + second_core_id, + )); + + // ...there should be 30 out of the 130, because the first staker had 100 staked in era 2. + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::StakerClaimed { + staker: second_staker.clone(), + core: second_core_id, + era: 2, + amount: 30, + })); + + // Era 3: + + // Let's try claiming rewards for the first staker in the first core... + assert_ok!(OcifStaking::staker_claim_rewards( + RuntimeOrigin::signed(first_staker.clone()), + first_core_id, + )); + + // ...there should be nothing, because no rewards were issue in era 3. + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::StakerClaimed { + staker: first_staker.clone(), + core: first_core_id, + era: 3, + amount: 0, + })); + + // Let's try claiming rewards for the first staker in the second core... + assert_ok!(OcifStaking::staker_claim_rewards( + RuntimeOrigin::signed(first_staker.clone()), + second_core_id, + )); + + // ...there should be nothing, because no rewards were issue in era 3. + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::StakerClaimed { + staker: first_staker.clone(), + core: second_core_id, + era: 3, + amount: 0, + })); + + // Let's try claiming rewards for the second staker in the second core... + assert_ok!(OcifStaking::staker_claim_rewards( + RuntimeOrigin::signed(second_staker.clone()), + second_core_id, + )); + + // ...there should be nothing, because no rewards were issue in era 3. + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::StakerClaimed { + staker: second_staker.clone(), + core: second_core_id, + era: 3, + amount: 0, + })); + + // Era 4: + + // Let's try claiming rewards for the first staker in the first core... + assert_ok!(OcifStaking::staker_claim_rewards( + RuntimeOrigin::signed(first_staker.clone()), + first_core_id, + )); + + // ...there should be 100 out of the 150, because the second staker had 30 staked in era 4 and first staker had 20 in the second core. + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::StakerClaimed { + staker: first_staker.clone(), + core: first_core_id, + era: 4, + amount: 100, + })); + + // Let's try claiming rewards for the first staker in the second core... + assert_ok!(OcifStaking::staker_claim_rewards( + RuntimeOrigin::signed(first_staker.clone()), + second_core_id, + )); + + // ...there should be 20 out of the 150, because the second staker had 30 staked in era 4 and first staker had 100 in the first core. + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::StakerClaimed { + staker: first_staker, + core: second_core_id, + era: 4, + amount: 20, + })); + + // Let's try claiming rewards for the second staker in the second core... + assert_ok!(OcifStaking::staker_claim_rewards( + RuntimeOrigin::signed(second_staker.clone()), + second_core_id, + )); + + // ...there should be 30 out of the 150, because the first staker had 120 staked in era 4. + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::StakerClaimed { + staker: second_staker, + core: second_core_id, + era: 4, + amount: 30, + })); + }) +} + +#[test] +fn claim_after_unregister_is_ok() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let staker = account(B); + let core_id = A; + + let start_era = OcifStaking::current_era(); + assert_register(core_id); + let stake_value = 100; + assert_stake(staker.clone(), &core_id, stake_value); + + advance_to_era(start_era + 5); + assert_unstake(staker.clone(), &core_id, stake_value); + let full_unstake_era = OcifStaking::current_era(); + let number_of_staking_eras = full_unstake_era - start_era; + + advance_to_era(OcifStaking::current_era() + 3); + let stake_value = 75; + let restake_era = OcifStaking::current_era(); + assert_stake(staker.clone(), &core_id, stake_value); + + advance_to_era(OcifStaking::current_era() + 3); + assert_unregister(core_id); + let unregister_era = OcifStaking::current_era(); + let number_of_staking_eras = number_of_staking_eras + unregister_era - restake_era; + advance_to_era(OcifStaking::current_era() + 2); + + for _ in 0..number_of_staking_eras { + assert_claim_staker(staker.clone(), core_id); + } + assert_noop!( + OcifStaking::staker_claim_rewards(RuntimeOrigin::signed(staker), core_id.clone()), + Error::::NoStakeAvailable + ); + + for era in start_era..unregister_era { + if era >= full_unstake_era && era < restake_era { + assert_noop!( + OcifStaking::core_claim_rewards( + RuntimeOrigin::signed(account(A)), + core_id.clone(), + era + ), + Error::::NoStakeAvailable + ); + } else { + assert_claim_core(core_id, era); + } + } + }) +} + +#[test] +fn claim_only_payout_is_ok() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let staker = account(B); + let core_id = A; + + let start_era = OcifStaking::current_era(); + assert_register(core_id); + let stake_value = 100; + assert_stake(staker.clone(), &core_id, stake_value); + + advance_to_era(start_era + 1); + + assert_claim_staker(staker, core_id); + }) +} + +#[test] +fn claim_with_zero_staked_is_ok() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let staker = account(B); + let core_id = A; + let start_era = OcifStaking::current_era(); + assert_register(core_id); + + let stake_value = 100; + assert_stake(staker.clone(), &core_id, stake_value); + advance_to_era(start_era + 1); + + assert_unstake(staker.clone(), &core_id, stake_value); + + assert_claim_staker(staker, core_id); + }) +} + +#[test] +fn claim_core_with_zero_stake_periods_is_ok() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let staker = account(B); + let core_id = A; + + let start_era = OcifStaking::current_era(); + assert_register(core_id); + let stake_value = 100; + assert_stake(staker.clone(), &core_id, stake_value); + + advance_to_era(start_era + 5); + let first_full_unstake_era = OcifStaking::current_era(); + assert_unstake(staker.clone(), &core_id, stake_value); + + advance_to_era(OcifStaking::current_era() + 7); + let restake_era = OcifStaking::current_era(); + assert_stake(staker.clone(), &core_id, stake_value); + + advance_to_era(OcifStaking::current_era() + 4); + let second_full_unstake_era = OcifStaking::current_era(); + assert_unstake(staker.clone(), &core_id, stake_value); + advance_to_era(OcifStaking::current_era() + 10); + + for era in start_era..first_full_unstake_era { + assert_claim_core(core_id, era); + } + + for era in first_full_unstake_era..restake_era { + assert_noop!( + OcifStaking::core_claim_rewards( + RuntimeOrigin::signed(account(core_id)), + core_id.clone(), + era + ), + Error::::NoStakeAvailable + ); + } + + for era in restake_era..second_full_unstake_era { + assert_claim_core(core_id, era); + } + + assert_noop!( + OcifStaking::core_claim_rewards( + RuntimeOrigin::signed(account(core_id)), + core_id.clone(), + second_full_unstake_era + ), + Error::::NoStakeAvailable + ); + + let last_claim_era = OcifStaking::current_era(); + assert_stake(staker, &core_id, stake_value); + advance_to_era(last_claim_era + 1); + assert_claim_core(core_id, last_claim_era); + }) +} + +#[test] +fn core_stakers_split_util() { + let core_rewards = 420; + let stakers_rewards = 1337; + let staked_on_core = 123456; + let total_staked = staked_on_core * 2; + + let staking_points_active = CoreStakeInfo:: { + total: staked_on_core, + number_of_stakers: 10, + reward_claimed: false, + active: true, + }; + + let staking_points_inactive = CoreStakeInfo:: { + total: staked_on_core, + number_of_stakers: 10, + reward_claimed: false, + active: false, + }; + + let era_info = EraInfo:: { + rewards: RewardInfo { + core: core_rewards, + stakers: stakers_rewards, + }, + staked: total_staked, + locked: total_staked, + active_stake: staked_on_core, + }; + + let (core_reward, stakers_reward) = + OcifStaking::core_stakers_split(&staking_points_active, &era_info); + + let core_stake_ratio = Perbill::from_rational(staked_on_core, total_staked); + let calculated_stakers_reward = core_stake_ratio * stakers_rewards; + assert_eq!(core_rewards, core_reward); + assert_eq!(calculated_stakers_reward, stakers_reward); + + assert_eq!( + calculated_stakers_reward + core_rewards, + core_reward + stakers_reward + ); + + let (core_reward, stakers_reward) = + OcifStaking::core_stakers_split(&staking_points_inactive, &era_info); + + let core_stake_ratio = Perbill::from_rational(staked_on_core, total_staked); + let calculated_stakers_reward = core_stake_ratio * stakers_rewards; + assert_eq!(Balance::zero(), core_reward); + assert_eq!(calculated_stakers_reward, stakers_reward); + + assert_eq!(calculated_stakers_reward, core_reward + stakers_reward); +} + +#[test] +pub fn tvl_util_test() { + ExternalityBuilder::build().execute_with(|| { + assert!(OcifStaking::tvl().is_zero()); + initialize_first_block(); + assert!(OcifStaking::tvl().is_zero()); + + let core_id = A; + assert_register(core_id); + + let iterations = 10; + let stake_value = 100; + for x in 1..=iterations { + assert_stake(account(core_id), &core_id, stake_value); + assert_eq!(OcifStaking::tvl(), stake_value * x); + } + + advance_to_era(5); + assert_eq!(OcifStaking::tvl(), stake_value * iterations); + }) +} + +#[test] +fn unbonding_info_test() { + let mut unbonding_info = UnbondingInfo::::default(); + + assert!(unbonding_info.is_empty()); + assert!(unbonding_info.len().is_zero()); + let (first_info, second_info) = unbonding_info.clone().partition(2); + assert!(first_info.is_empty()); + assert!(second_info.is_empty()); + + let count = 5; + let base_amount: Balance = 100; + let base_unlock_era = 4 * count; + let mut chunks = vec![]; + for x in 1_u32..=count as u32 { + chunks.push(UnlockingChunk { + amount: base_amount * x as Balance, + unlock_era: base_unlock_era - 3 * x, + }); + } + + unbonding_info.add(chunks[0 as usize]); + + assert!(!unbonding_info.is_empty()); + assert_eq!(1, unbonding_info.len()); + assert_eq!(chunks[0 as usize].amount, unbonding_info.sum()); + + let (first_info, second_info) = unbonding_info.clone().partition(base_unlock_era); + assert_eq!(1, first_info.len()); + assert_eq!(chunks[0 as usize].amount, first_info.sum()); + assert!(second_info.is_empty()); + + for x in unbonding_info.len() as usize..chunks.len() { + unbonding_info.add(chunks[x]); + assert!(unbonding_info + .unlocking_chunks + .windows(2) + .all(|w| w[0].unlock_era <= w[1].unlock_era)); + } + assert_eq!(chunks.len(), unbonding_info.len() as usize); + let total: Balance = chunks.iter().map(|c| c.amount).sum(); + assert_eq!(total, unbonding_info.sum()); + + let partition_era = chunks[2].unlock_era + 1; + let (first_info, second_info) = unbonding_info.clone().partition(partition_era); + assert_eq!(3, first_info.len()); + assert_eq!(2, second_info.len()); + assert_eq!(unbonding_info.sum(), first_info.sum() + second_info.sum()); +} + +#[test] +fn staker_info_basic() { + let staker_info = StakerInfo::::default(); + + assert!(staker_info.is_empty()); + assert_eq!(staker_info.len(), 0); + assert_eq!(staker_info.latest_staked_value(), 0); +} + +#[test] +fn staker_info_stake_ops() { + let mut staker_info = StakerInfo::::default(); + + let first_era = 1; + let first_stake = 100; + assert_ok!(staker_info.stake(first_era, first_stake)); + assert!(!staker_info.is_empty()); + assert_eq!(staker_info.len(), 1); + assert_eq!(staker_info.latest_staked_value(), first_stake); + + let second_era = first_era + 1; + let second_stake = 200; + assert_ok!(staker_info.stake(second_era, second_stake)); + assert_eq!(staker_info.len(), 2); + assert_eq!( + staker_info.latest_staked_value(), + first_stake + second_stake + ); + + let third_era = second_era + 2; + let third_stake = 333; + assert_ok!(staker_info.stake(third_era, third_stake)); + assert_eq!( + staker_info.latest_staked_value(), + first_stake + second_stake + third_stake + ); + assert_eq!(staker_info.len(), 3); + + let fourth_era = third_era; + let fourth_stake = 444; + assert_ok!(staker_info.stake(fourth_era, fourth_stake)); + assert_eq!(staker_info.len(), 3); + assert_eq!( + staker_info.latest_staked_value(), + first_stake + second_stake + third_stake + fourth_stake + ); +} + +#[test] +fn staker_info_stake_error() { + let mut staker_info = StakerInfo::::default(); + assert_ok!(staker_info.stake(5, 100)); + if let Err(_) = staker_info.stake(4, 100) { + } else { + panic!("Mustn't be able to stake with past era."); + } +} + +#[test] +fn staker_info_unstake_ops() { + let mut staker_info = StakerInfo::::default(); + + assert!(staker_info.is_empty()); + assert_ok!(staker_info.unstake(1, 100)); + assert!(staker_info.is_empty()); + + let (first_era, second_era) = (1, 3); + let (first_stake, second_stake) = (110, 222); + let total_staked = first_stake + second_stake; + assert_ok!(staker_info.stake(first_era, first_stake)); + assert_ok!(staker_info.stake(second_era, second_stake)); + + let first_unstake_era = second_era; + let first_unstake = 55; + assert_ok!(staker_info.unstake(first_unstake_era, first_unstake)); + assert_eq!(staker_info.len(), 2); + assert_eq!( + staker_info.latest_staked_value(), + total_staked - first_unstake + ); + let total_staked = total_staked - first_unstake; + + let second_unstake_era = first_unstake_era + 2; + let second_unstake = 37; + assert_ok!(staker_info.unstake(second_unstake_era, second_unstake)); + assert_eq!(staker_info.len(), 3); + assert_eq!( + staker_info.latest_staked_value(), + total_staked - second_unstake + ); + let total_staked = total_staked - second_unstake; + + let temp_staker_info = staker_info.clone(); + + assert_ok!(staker_info.unstake(second_unstake_era, total_staked)); + assert_eq!(staker_info.len(), 3); + assert_eq!(staker_info.latest_staked_value(), 0); + + let mut staker_info = temp_staker_info; + assert_ok!(staker_info.unstake(second_unstake_era + 1, total_staked)); + assert_eq!(staker_info.len(), 4); + assert_eq!(staker_info.latest_staked_value(), 0); +} + +#[test] +fn stake_after_full_unstake() { + let mut staker_info = StakerInfo::::default(); + + let first_era = 1; + let first_stake = 100; + assert_ok!(staker_info.stake(first_era, first_stake)); + assert_eq!(staker_info.latest_staked_value(), first_stake); + + let unstake_era = first_era + 1; + assert_ok!(staker_info.unstake(unstake_era, first_stake)); + assert!(staker_info.latest_staked_value().is_zero()); + assert_eq!(staker_info.len(), 2); + + let restake_era = unstake_era + 2; + let restake_value = 57; + assert_ok!(staker_info.stake(restake_era, restake_value)); + assert_eq!(staker_info.latest_staked_value(), restake_value); + assert_eq!(staker_info.len(), 3); +} + +#[test] +fn staker_info_unstake_error() { + let mut staker_info = StakerInfo::::default(); + assert_ok!(staker_info.stake(5, 100)); + if let Err(_) = staker_info.unstake(4, 100) { + } else { + panic!("Mustn't be able to unstake with past era."); + } +} + +#[test] +fn staker_info_claim_ops_basic() { + let mut staker_info = StakerInfo::::default(); + + assert!(staker_info.is_empty()); + assert_eq!(staker_info.claim(), (0, 0)); + assert!(staker_info.is_empty()); + + assert_ok!(staker_info.stake(1, 100)); + assert_ok!(staker_info.unstake(1, 100)); + assert!(staker_info.is_empty()); + assert_eq!(staker_info.claim(), (0, 0)); + assert!(staker_info.is_empty()); + + staker_info = StakerInfo::::default(); + let stake_era = 1; + let stake_value = 123; + assert_ok!(staker_info.stake(stake_era, stake_value)); + assert_eq!(staker_info.len(), 1); + assert_eq!(staker_info.claim(), (stake_era, stake_value)); + assert_eq!(staker_info.len(), 1); +} + +#[test] +fn staker_info_claim_ops_advanced() { + let mut staker_info = StakerInfo::::default(); + + let (first_stake_era, second_stake_era, third_stake_era) = (1, 2, 4); + let (first_stake_value, second_stake_value, third_stake_value) = (123, 456, 789); + + assert_ok!(staker_info.stake(first_stake_era, first_stake_value)); + assert_ok!(staker_info.stake(second_stake_era, second_stake_value)); + assert_ok!(staker_info.stake(third_stake_era, third_stake_value)); + + assert_eq!(staker_info.len(), 3); + assert_eq!(staker_info.claim(), (first_stake_era, first_stake_value)); + assert_eq!(staker_info.len(), 2); + + assert_eq!( + staker_info.claim(), + (second_stake_era, first_stake_value + second_stake_value) + ); + assert_eq!(staker_info.len(), 2); + + assert_eq!( + staker_info.claim(), + (3, first_stake_value + second_stake_value) + ); + assert_eq!(staker_info.len(), 1); + + let total_staked = first_stake_value + second_stake_value + third_stake_value; + assert_ok!(staker_info.unstake(5, total_staked)); + assert_eq!(staker_info.len(), 2); + + let fourth_era = 7; + let fourth_stake_value = 147; + assert_ok!(staker_info.stake(fourth_era, fourth_stake_value)); + assert_eq!(staker_info.len(), 3); + + assert_eq!(staker_info.claim(), (third_stake_era, total_staked)); + assert_eq!(staker_info.len(), 1); + + assert_eq!(staker_info.claim(), (fourth_era, fourth_stake_value)); + assert_eq!(staker_info.len(), 1); + assert_eq!(staker_info.latest_staked_value(), fourth_stake_value); + + for x in 1..10 { + assert_eq!(staker_info.claim(), (fourth_era + x, fourth_stake_value)); + assert_eq!(staker_info.len(), 1); + assert_eq!(staker_info.latest_staked_value(), fourth_stake_value); + } +} + +#[test] +fn new_era_is_handled_with_halt_enabled() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + assert_ok!(OcifStaking::halt_unhalt_pallet(RuntimeOrigin::root(), true)); + assert!(Halted::::exists()); + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::HaltChanged { + is_halted: true, + })); + + run_for_blocks(BLOCKS_PER_ERA * 3); + + assert!(System::block_number() > OcifStaking::next_era_starting_block()); + assert_eq!(OcifStaking::current_era(), 1); + + assert_ok!(OcifStaking::halt_unhalt_pallet( + RuntimeOrigin::root(), + false + )); + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::HaltChanged { + is_halted: false, + })); + + run_for_blocks(BLOCKS_PER_ERA); + + assert_eq!(System::block_number(), (4 * BLOCKS_PER_ERA) + 2); // 2 from initialization, advanced 4 eras worth of blocks + + assert_eq!(OcifStaking::current_era(), 2); + assert_eq!(OcifStaking::next_era_starting_block(), (5 * BLOCKS_PER_ERA)); + }) +} + +#[test] +fn pallet_halt_is_ok() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + assert_ok!(OcifStaking::ensure_not_halted()); + assert!(!Halted::::exists()); + + assert_ok!(OcifStaking::halt_unhalt_pallet(RuntimeOrigin::root(), true)); + assert!(Halted::::exists()); + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::HaltChanged { + is_halted: true, + })); + + let staker_account = account(B); + let core_id = A; + + assert_noop!( + OcifStaking::register_core( + pallet_inv4::Origin::Multisig(pallet_inv4::origin::MultisigInternalOrigin::new( + core_id + )) + .into(), + Vec::default().try_into().unwrap(), + Vec::default().try_into().unwrap(), + Vec::default().try_into().unwrap() + ), + Error::::Halted + ); + + assert_noop!( + OcifStaking::unregister_core( + pallet_inv4::Origin::Multisig(pallet_inv4::origin::MultisigInternalOrigin::new( + core_id + )) + .into() + ), + Error::::Halted + ); + + assert_noop!( + OcifStaking::change_core_metadata( + pallet_inv4::Origin::Multisig(pallet_inv4::origin::MultisigInternalOrigin::new( + core_id + )) + .into(), + Vec::default().try_into().unwrap(), + Vec::default().try_into().unwrap(), + Vec::default().try_into().unwrap() + ), + Error::::Halted + ); + + assert_noop!( + OcifStaking::withdraw_unstaked(RuntimeOrigin::signed(staker_account.clone())), + Error::::Halted + ); + + assert_noop!( + OcifStaking::stake(RuntimeOrigin::signed(staker_account.clone()), core_id, 100), + Error::::Halted + ); + + assert_noop!( + OcifStaking::unstake(RuntimeOrigin::signed(staker_account.clone()), core_id, 100), + Error::::Halted + ); + + assert_noop!( + OcifStaking::core_claim_rewards(RuntimeOrigin::signed(account(core_id)), core_id, 5), + Error::::Halted + ); + + assert_noop!( + OcifStaking::staker_claim_rewards(RuntimeOrigin::signed(staker_account), core_id), + Error::::Halted + ); + + assert_eq!(OcifStaking::on_initialize(3), Weight::zero()); + + assert_ok!(OcifStaking::halt_unhalt_pallet( + RuntimeOrigin::root(), + false + )); + System::assert_last_event(mock::RuntimeEvent::OcifStaking(Event::HaltChanged { + is_halted: false, + })); + + assert_register(core_id); + }) +} + +#[test] +fn halted_no_change() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + assert_ok!(OcifStaking::ensure_not_halted()); + assert_noop!( + OcifStaking::halt_unhalt_pallet(RuntimeOrigin::root(), false), + Error::::NoHaltChange + ); + + assert_ok!(OcifStaking::halt_unhalt_pallet(RuntimeOrigin::root(), true)); + assert_noop!( + OcifStaking::halt_unhalt_pallet(RuntimeOrigin::root(), true), + Error::::NoHaltChange + ); + }) +} + +#[test] +fn move_stake_is_ok() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let staker = account(B); + let core_id_a = A; + let core_id_b = C; + + assert_register(core_id_a); + assert_register(core_id_b); + let stake_value = 100; + assert_stake(staker.clone(), &core_id_a, stake_value); + + assert_move_stake(staker.clone(), &core_id_a, &core_id_b, stake_value / 2); + assert!(!GeneralStakerInfo::::get(&core_id_a, &staker.clone()) + .latest_staked_value() + .is_zero()); + + assert_move_stake(staker.clone(), &core_id_a, &core_id_b, stake_value / 2); + assert!(GeneralStakerInfo::::get(&core_id_a, &staker) + .latest_staked_value() + .is_zero()); + }) +} + +#[test] +fn move_stake_to_same_contract_err() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let staker = account(B); + let core_id_a = A; + + assert_register(core_id_a); + let stake_value = 100; + assert_stake(staker.clone(), &core_id_a, stake_value); + + assert_noop!( + OcifStaking::move_stake( + RuntimeOrigin::signed(staker), + core_id_a, + stake_value, + core_id_a, + ), + Error::::MoveStakeToSameCore + ); + }) +} + +#[test] +fn move_stake_to_unregistered_core_err() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let staker = account(B); + let core_id_a = A; + let core_id_b = C; + let core_id_c = D; + + assert_register(core_id_a); + let stake_value = 100; + assert_stake(staker.clone(), &core_id_a, stake_value); + + assert_noop!( + OcifStaking::move_stake( + RuntimeOrigin::signed(staker.clone()), + core_id_b, + stake_value, + core_id_c, + ), + Error::::NotRegistered + ); + + assert_noop!( + OcifStaking::move_stake( + RuntimeOrigin::signed(staker.clone()), + core_id_a, + stake_value, + core_id_b, + ), + Error::::NotRegistered + ); + + assert_noop!( + OcifStaking::move_stake( + RuntimeOrigin::signed(staker), + core_id_b, + stake_value, + core_id_a, + ), + Error::::NoStakeAvailable + ); + }) +} + +#[test] +fn move_stake_not_staking_err() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let staker = account(B); + let core_id_a = A; + let core_id_b = C; + + assert_register(core_id_a); + assert_register(core_id_b); + let stake_value = 100; + + assert_noop!( + OcifStaking::move_stake( + RuntimeOrigin::signed(staker), + core_id_a, + stake_value, + core_id_b + ), + Error::::NoStakeAvailable + ); + }) +} + +#[test] +fn move_stake_with_no_amount_err() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let staker = account(B); + let core_id_a = A; + let core_id_b = C; + + assert_register(core_id_a); + assert_register(core_id_b); + let stake_value = 100; + assert_stake(staker.clone(), &core_id_a, stake_value); + + assert_noop!( + OcifStaking::move_stake( + RuntimeOrigin::signed(staker), + core_id_a, + Zero::zero(), + core_id_b + ), + Error::::UnstakingNothing + ); + }) +} + +#[test] +fn move_stake_with_insufficient_amount_err() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let staker = account(B); + let core_id_a = A; + let core_id_b = C; + + assert_register(core_id_a); + assert_register(core_id_b); + let stake_value = 100; + assert_stake(staker.clone(), &core_id_a, stake_value); + + assert_noop!( + OcifStaking::move_stake( + RuntimeOrigin::signed(staker), + core_id_a, + MINIMUM_STAKING_AMOUNT - 1, + core_id_b + ), + Error::::InsufficientBalance + ); + }) +} + +#[test] +fn move_stake_core_has_too_many_era_stake_err() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let staker = account(B); + let core_id_a = A; + let core_id_b = C; + + assert_register(core_id_a); + assert_register(core_id_b); + + for _ in 1..MAX_ERA_STAKE_VALUES { + assert_stake(staker.clone(), &core_id_a, MINIMUM_STAKING_AMOUNT); + advance_to_era(OcifStaking::current_era() + 1); + } + assert_noop!( + OcifStaking::stake(RuntimeOrigin::signed(staker.clone()), core_id_a, 15), + Error::::TooManyEraStakeValues + ); + + assert_noop!( + OcifStaking::move_stake( + RuntimeOrigin::signed(staker.clone()), + core_id_a, + 15, + core_id_b + ), + Error::::TooManyEraStakeValues + ); + + assert_stake(staker.clone(), &core_id_b, 15); + assert_noop!( + OcifStaking::move_stake(RuntimeOrigin::signed(staker), core_id_b, 15, core_id_a), + Error::::TooManyEraStakeValues + ); + }) +} + +#[test] +fn move_stake_max_number_of_stakers_exceeded_err() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let staker_a = account(B); + let staker_b = account(D); + let core_id_a = A; + let core_id_b = C; + + assert_register(core_id_a); + assert_register(core_id_b); + + assert_stake(staker_a.clone(), &core_id_a, 23); + assert_stake(staker_b.clone(), &core_id_b, 37); + assert_stake(staker_b, &core_id_b, 41); + + for temp_staker in (4u32)..(MAX_NUMBER_OF_STAKERS as u32 + 3u32) { + let staker = account(temp_staker); + Balances::resolve_creating(&staker, Balances::issue(100)); + assert_stake(staker, &core_id_b, 13); + } + + assert_noop!( + OcifStaking::stake(RuntimeOrigin::signed(staker_a.clone()), core_id_b, 19), + Error::::MaxStakersReached + ); + + assert_noop!( + OcifStaking::move_stake(RuntimeOrigin::signed(staker_a), core_id_a, 19, core_id_b,), + Error::::MaxStakersReached + ); + }) +} + +#[test] +fn claim_stake_after_unregistering_core_mid_era_changes_is_ok() { + ExternalityBuilder::build().execute_with(|| { + initialize_first_block(); + + let core_id_b = C; + + assert_register(core_id_b); + + let mut stakers: Vec = Vec::new(); + + for temp_staker in 0..4 { + let staker = account(temp_staker + 100); + stakers.push(staker.clone()); + Balances::resolve_creating(&staker, Balances::issue(1000)); + short_stake(staker, &core_id_b, 20); + } + + println!("finished stake preparation"); + + let era = OcifStaking::current_era(); + + let era_to_claim = era + 4; + + let block_at_era_to_claim = System::block_number(); + + advance_to_era(era_to_claim); + + run_to_block(block_at_era_to_claim + 2); + + assert!(era_to_claim == OcifStaking::current_era()); + + assert_unregister(core_id_b); + + System::reset_events(); + + for _ in 0..10 { + println!( + "***** running to block {:?} *****", + System::block_number() + 1 + ); + run_for_blocks(1); + } + + for _ in era..era_to_claim { + for staker in stakers.iter() { + assert_claim_staker(staker.clone(), core_id_b); + } + } + + println!("finished claiming"); + + assert_noop!( + OcifStaking::staker_claim_rewards(RuntimeOrigin::signed(stakers[0].clone()), core_id_b), + Error::::NoStakeAvailable + ); + }); +} diff --git a/pallets/OCIF/staking/src/weights.rs b/pallets/OCIF/staking/src/weights.rs new file mode 100644 index 00000000..21106a88 --- /dev/null +++ b/pallets/OCIF/staking/src/weights.rs @@ -0,0 +1,494 @@ + +//! Autogenerated weights for `pallet_ocif_staking` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2024-06-18, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `anny.local`, CPU: `` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` + +// Executed Command: +// ./target/release/tinkernet-collator +// benchmark +// pallet +// --chain=dev +// --wasm-execution=compiled +// --pallet=pallet-ocif-staking +// --extrinsic=* +// --steps +// 50 +// --repeat +// 20 +// --output=../../InvArch-Frames/OCIF/staking/src/weights.rs +// --template=../weights-template.hbs + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use core::marker::PhantomData; + +/// Weight functions needed for `pallet_ocif_staking`. +pub trait WeightInfo { + fn register_core(n: u32, d: u32, i: u32, ) -> Weight; + fn change_core_metadata(n: u32, d: u32, i: u32, ) -> Weight; + fn unregister_core() -> Weight; + fn stake() -> Weight; + fn unstake() -> Weight; + fn withdraw_unstaked() -> Weight; + fn staker_claim_rewards() -> Weight; + fn core_claim_rewards() -> Weight; + fn halt_unhalt_pallet() -> Weight; + fn move_stake() -> Weight; +} + +/// Weights for `pallet_ocif_staking` using the Substrate node and recommended hardware. +pub struct SubstrateWeight(PhantomData); +impl WeightInfo for SubstrateWeight { + /// Storage: `OcifStaking::Halted` (r:1 w:0) + /// Proof: `OcifStaking::Halted` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::RegisteredCore` (r:1 w:1) + /// Proof: `OcifStaking::RegisteredCore` (`max_values`: None, `max_size`: Some(477), added: 2952, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `n` is `[0, 20]`. + /// The range of component `d` is `[0, 300]`. + /// The range of component `i` is `[0, 100]`. + fn register_core(_n: u32, _d: u32, _i: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `213` + // Estimated: `3942` + // Minimum execution time: 22_000_000 picoseconds. + Weight::from_parts(24_293_021, 3942) + .saturating_add(T::DbWeight::get().reads(4_u64)) + .saturating_add(T::DbWeight::get().writes(2_u64)) + } + /// Storage: `OcifStaking::Halted` (r:1 w:0) + /// Proof: `OcifStaking::Halted` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::RegisteredCore` (r:1 w:1) + /// Proof: `OcifStaking::RegisteredCore` (`max_values`: None, `max_size`: Some(477), added: 2952, mode: `MaxEncodedLen`) + /// The range of component `n` is `[0, 20]`. + /// The range of component `d` is `[0, 300]`. + /// The range of component `i` is `[0, 100]`. + fn change_core_metadata(n: u32, d: u32, i: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `86` + // Estimated: `3942` + // Minimum execution time: 9_000_000 picoseconds. + Weight::from_parts(9_593_278, 3942) + // Standard Error: 890 + .saturating_add(Weight::from_parts(4_471, 0).saturating_mul(n.into())) + // Standard Error: 61 + .saturating_add(Weight::from_parts(856, 0).saturating_mul(d.into())) + // Standard Error: 182 + .saturating_add(Weight::from_parts(1_028, 0).saturating_mul(i.into())) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + /// Storage: `OcifStaking::Halted` (r:1 w:0) + /// Proof: `OcifStaking::Halted` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::RegisteredCore` (r:1 w:1) + /// Proof: `OcifStaking::RegisteredCore` (`max_values`: None, `max_size`: Some(477), added: 2952, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::CurrentEra` (r:1 w:0) + /// Proof: `OcifStaking::CurrentEra` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::GeneralStakerInfo` (r:1 w:0) + /// Proof: `OcifStaking::GeneralStakerInfo` (`max_values`: None, `max_size`: Some(269), added: 2744, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::CoreEraStake` (r:1 w:1) + /// Proof: `OcifStaking::CoreEraStake` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::GeneralEraInfo` (r:1 w:1) + /// Proof: `OcifStaking::GeneralEraInfo` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(55), added: 2530, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(6), added: 501, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::UnregisteredCoreStakeInfo` (r:0 w:1) + /// Proof: `OcifStaking::UnregisteredCoreStakeInfo` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::UnregisteredCoreStakers` (r:0 w:1) + /// Proof: `OcifStaking::UnregisteredCoreStakers` (`max_values`: None, `max_size`: Some(320022), added: 322497, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(134194), added: 136669, mode: `MaxEncodedLen`) + fn unregister_core() -> Weight { + // Proof Size summary in bytes: + // Measured: `343` + // Estimated: `3942` + // Minimum execution time: 44_000_000 picoseconds. + Weight::from_parts(45_000_000, 3942) + .saturating_add(T::DbWeight::get().reads(10_u64)) + .saturating_add(T::DbWeight::get().writes(9_u64)) + } + /// Storage: `OcifStaking::Halted` (r:1 w:0) + /// Proof: `OcifStaking::Halted` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::RegisteredCore` (r:1 w:0) + /// Proof: `OcifStaking::RegisteredCore` (`max_values`: None, `max_size`: Some(477), added: 2952, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::Ledger` (r:1 w:1) + /// Proof: `OcifStaking::Ledger` (`max_values`: None, `max_size`: Some(265), added: 2740, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::CurrentEra` (r:1 w:0) + /// Proof: `OcifStaking::CurrentEra` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::CoreEraStake` (r:1 w:1) + /// Proof: `OcifStaking::CoreEraStake` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::GeneralStakerInfo` (r:1 w:1) + /// Proof: `OcifStaking::GeneralStakerInfo` (`max_values`: None, `max_size`: Some(269), added: 2744, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::GeneralEraInfo` (r:1 w:1) + /// Proof: `OcifStaking::GeneralEraInfo` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) + /// Storage: `Balances::Locks` (r:1 w:1) + /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) + /// Storage: `Balances::Freezes` (r:1 w:0) + /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + fn stake() -> Weight { + // Proof Size summary in bytes: + // Measured: `86` + // Estimated: `4764` + // Minimum execution time: 34_000_000 picoseconds. + Weight::from_parts(35_000_000, 4764) + .saturating_add(T::DbWeight::get().reads(9_u64)) + .saturating_add(T::DbWeight::get().writes(5_u64)) + } + /// Storage: `OcifStaking::Halted` (r:1 w:0) + /// Proof: `OcifStaking::Halted` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::RegisteredCore` (r:1 w:0) + /// Proof: `OcifStaking::RegisteredCore` (`max_values`: None, `max_size`: Some(477), added: 2952, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::CurrentEra` (r:1 w:0) + /// Proof: `OcifStaking::CurrentEra` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::GeneralStakerInfo` (r:1 w:1) + /// Proof: `OcifStaking::GeneralStakerInfo` (`max_values`: None, `max_size`: Some(269), added: 2744, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::CoreEraStake` (r:1 w:1) + /// Proof: `OcifStaking::CoreEraStake` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::Ledger` (r:1 w:1) + /// Proof: `OcifStaking::Ledger` (`max_values`: None, `max_size`: Some(265), added: 2740, mode: `MaxEncodedLen`) + /// Storage: `Balances::Locks` (r:1 w:1) + /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) + /// Storage: `Balances::Freezes` (r:1 w:0) + /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::GeneralEraInfo` (r:1 w:1) + /// Proof: `OcifStaking::GeneralEraInfo` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) + fn unstake() -> Weight { + // Proof Size summary in bytes: + // Measured: `397` + // Estimated: `4764` + // Minimum execution time: 36_000_000 picoseconds. + Weight::from_parts(37_000_000, 4764) + .saturating_add(T::DbWeight::get().reads(9_u64)) + .saturating_add(T::DbWeight::get().writes(5_u64)) + } + /// Storage: `OcifStaking::Halted` (r:1 w:0) + /// Proof: `OcifStaking::Halted` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::Ledger` (r:1 w:1) + /// Proof: `OcifStaking::Ledger` (`max_values`: None, `max_size`: Some(265), added: 2740, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::CurrentEra` (r:1 w:0) + /// Proof: `OcifStaking::CurrentEra` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `Balances::Locks` (r:1 w:1) + /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) + /// Storage: `Balances::Freezes` (r:1 w:0) + /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::GeneralEraInfo` (r:1 w:1) + /// Proof: `OcifStaking::GeneralEraInfo` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) + fn withdraw_unstaked() -> Weight { + // Proof Size summary in bytes: + // Measured: `449` + // Estimated: `4764` + // Minimum execution time: 31_000_000 picoseconds. + Weight::from_parts(32_000_000, 4764) + .saturating_add(T::DbWeight::get().reads(6_u64)) + .saturating_add(T::DbWeight::get().writes(3_u64)) + } + /// Storage: `OcifStaking::Halted` (r:1 w:0) + /// Proof: `OcifStaking::Halted` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::GeneralStakerInfo` (r:1 w:1) + /// Proof: `OcifStaking::GeneralStakerInfo` (`max_values`: None, `max_size`: Some(269), added: 2744, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::CurrentEra` (r:1 w:0) + /// Proof: `OcifStaking::CurrentEra` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::CoreEraStake` (r:1 w:0) + /// Proof: `OcifStaking::CoreEraStake` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::GeneralEraInfo` (r:1 w:0) + /// Proof: `OcifStaking::GeneralEraInfo` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) + fn staker_claim_rewards() -> Weight { + // Proof Size summary in bytes: + // Measured: `374` + // Estimated: `3734` + // Minimum execution time: 18_000_000 picoseconds. + Weight::from_parts(19_000_000, 3734) + .saturating_add(T::DbWeight::get().reads(5_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + /// Storage: `OcifStaking::Halted` (r:1 w:0) + /// Proof: `OcifStaking::Halted` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::CurrentEra` (r:1 w:0) + /// Proof: `OcifStaking::CurrentEra` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::CoreEraStake` (r:1 w:1) + /// Proof: `OcifStaking::CoreEraStake` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::GeneralEraInfo` (r:1 w:0) + /// Proof: `OcifStaking::GeneralEraInfo` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) + fn core_claim_rewards() -> Weight { + // Proof Size summary in bytes: + // Measured: `377` + // Estimated: `3557` + // Minimum execution time: 18_000_000 picoseconds. + Weight::from_parts(19_000_000, 3557) + .saturating_add(T::DbWeight::get().reads(5_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + /// Storage: `OcifStaking::Halted` (r:1 w:1) + /// Proof: `OcifStaking::Halted` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + fn halt_unhalt_pallet() -> Weight { + // Proof Size summary in bytes: + // Measured: `4` + // Estimated: `1486` + // Minimum execution time: 5_000_000 picoseconds. + Weight::from_parts(5_000_000, 1486) + .saturating_add(T::DbWeight::get().reads(1_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + /// Storage: `OcifStaking::Halted` (r:1 w:0) + /// Proof: `OcifStaking::Halted` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::RegisteredCore` (r:1 w:0) + /// Proof: `OcifStaking::RegisteredCore` (`max_values`: None, `max_size`: Some(477), added: 2952, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::CurrentEra` (r:1 w:0) + /// Proof: `OcifStaking::CurrentEra` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::GeneralStakerInfo` (r:2 w:2) + /// Proof: `OcifStaking::GeneralStakerInfo` (`max_values`: None, `max_size`: Some(269), added: 2744, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::CoreEraStake` (r:2 w:2) + /// Proof: `OcifStaking::CoreEraStake` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + fn move_stake() -> Weight { + // Proof Size summary in bytes: + // Measured: `302` + // Estimated: `6478` + // Minimum execution time: 24_000_000 picoseconds. + Weight::from_parts(25_000_000, 6478) + .saturating_add(T::DbWeight::get().reads(7_u64)) + .saturating_add(T::DbWeight::get().writes(4_u64)) + } +} + +// For backwards compatibility and tests. +impl WeightInfo for () { + /// Storage: `OcifStaking::Halted` (r:1 w:0) + /// Proof: `OcifStaking::Halted` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::RegisteredCore` (r:1 w:1) + /// Proof: `OcifStaking::RegisteredCore` (`max_values`: None, `max_size`: Some(477), added: 2952, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `n` is `[0, 20]`. + /// The range of component `d` is `[0, 300]`. + /// The range of component `i` is `[0, 100]`. + fn register_core(_n: u32, _d: u32, _i: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `213` + // Estimated: `3942` + // Minimum execution time: 22_000_000 picoseconds. + Weight::from_parts(24_293_021, 3942) + .saturating_add(RocksDbWeight::get().reads(4_u64)) + .saturating_add(RocksDbWeight::get().writes(2_u64)) + } + /// Storage: `OcifStaking::Halted` (r:1 w:0) + /// Proof: `OcifStaking::Halted` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::RegisteredCore` (r:1 w:1) + /// Proof: `OcifStaking::RegisteredCore` (`max_values`: None, `max_size`: Some(477), added: 2952, mode: `MaxEncodedLen`) + /// The range of component `n` is `[0, 20]`. + /// The range of component `d` is `[0, 300]`. + /// The range of component `i` is `[0, 100]`. + fn change_core_metadata(n: u32, d: u32, i: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `86` + // Estimated: `3942` + // Minimum execution time: 9_000_000 picoseconds. + Weight::from_parts(9_593_278, 3942) + // Standard Error: 890 + .saturating_add(Weight::from_parts(4_471, 0).saturating_mul(n.into())) + // Standard Error: 61 + .saturating_add(Weight::from_parts(856, 0).saturating_mul(d.into())) + // Standard Error: 182 + .saturating_add(Weight::from_parts(1_028, 0).saturating_mul(i.into())) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + /// Storage: `OcifStaking::Halted` (r:1 w:0) + /// Proof: `OcifStaking::Halted` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::RegisteredCore` (r:1 w:1) + /// Proof: `OcifStaking::RegisteredCore` (`max_values`: None, `max_size`: Some(477), added: 2952, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::CurrentEra` (r:1 w:0) + /// Proof: `OcifStaking::CurrentEra` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::GeneralStakerInfo` (r:1 w:0) + /// Proof: `OcifStaking::GeneralStakerInfo` (`max_values`: None, `max_size`: Some(269), added: 2744, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::CoreEraStake` (r:1 w:1) + /// Proof: `OcifStaking::CoreEraStake` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::GeneralEraInfo` (r:1 w:1) + /// Proof: `OcifStaking::GeneralEraInfo` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(55), added: 2530, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(6), added: 501, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::UnregisteredCoreStakeInfo` (r:0 w:1) + /// Proof: `OcifStaking::UnregisteredCoreStakeInfo` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::UnregisteredCoreStakers` (r:0 w:1) + /// Proof: `OcifStaking::UnregisteredCoreStakers` (`max_values`: None, `max_size`: Some(320022), added: 322497, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(134194), added: 136669, mode: `MaxEncodedLen`) + fn unregister_core() -> Weight { + // Proof Size summary in bytes: + // Measured: `343` + // Estimated: `3942` + // Minimum execution time: 44_000_000 picoseconds. + Weight::from_parts(45_000_000, 3942) + .saturating_add(RocksDbWeight::get().reads(10_u64)) + .saturating_add(RocksDbWeight::get().writes(9_u64)) + } + /// Storage: `OcifStaking::Halted` (r:1 w:0) + /// Proof: `OcifStaking::Halted` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::RegisteredCore` (r:1 w:0) + /// Proof: `OcifStaking::RegisteredCore` (`max_values`: None, `max_size`: Some(477), added: 2952, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::Ledger` (r:1 w:1) + /// Proof: `OcifStaking::Ledger` (`max_values`: None, `max_size`: Some(265), added: 2740, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::CurrentEra` (r:1 w:0) + /// Proof: `OcifStaking::CurrentEra` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::CoreEraStake` (r:1 w:1) + /// Proof: `OcifStaking::CoreEraStake` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::GeneralStakerInfo` (r:1 w:1) + /// Proof: `OcifStaking::GeneralStakerInfo` (`max_values`: None, `max_size`: Some(269), added: 2744, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::GeneralEraInfo` (r:1 w:1) + /// Proof: `OcifStaking::GeneralEraInfo` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) + /// Storage: `Balances::Locks` (r:1 w:1) + /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) + /// Storage: `Balances::Freezes` (r:1 w:0) + /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + fn stake() -> Weight { + // Proof Size summary in bytes: + // Measured: `86` + // Estimated: `4764` + // Minimum execution time: 34_000_000 picoseconds. + Weight::from_parts(35_000_000, 4764) + .saturating_add(RocksDbWeight::get().reads(9_u64)) + .saturating_add(RocksDbWeight::get().writes(5_u64)) + } + /// Storage: `OcifStaking::Halted` (r:1 w:0) + /// Proof: `OcifStaking::Halted` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::RegisteredCore` (r:1 w:0) + /// Proof: `OcifStaking::RegisteredCore` (`max_values`: None, `max_size`: Some(477), added: 2952, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::CurrentEra` (r:1 w:0) + /// Proof: `OcifStaking::CurrentEra` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::GeneralStakerInfo` (r:1 w:1) + /// Proof: `OcifStaking::GeneralStakerInfo` (`max_values`: None, `max_size`: Some(269), added: 2744, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::CoreEraStake` (r:1 w:1) + /// Proof: `OcifStaking::CoreEraStake` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::Ledger` (r:1 w:1) + /// Proof: `OcifStaking::Ledger` (`max_values`: None, `max_size`: Some(265), added: 2740, mode: `MaxEncodedLen`) + /// Storage: `Balances::Locks` (r:1 w:1) + /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) + /// Storage: `Balances::Freezes` (r:1 w:0) + /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::GeneralEraInfo` (r:1 w:1) + /// Proof: `OcifStaking::GeneralEraInfo` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) + fn unstake() -> Weight { + // Proof Size summary in bytes: + // Measured: `397` + // Estimated: `4764` + // Minimum execution time: 36_000_000 picoseconds. + Weight::from_parts(37_000_000, 4764) + .saturating_add(RocksDbWeight::get().reads(9_u64)) + .saturating_add(RocksDbWeight::get().writes(5_u64)) + } + /// Storage: `OcifStaking::Halted` (r:1 w:0) + /// Proof: `OcifStaking::Halted` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::Ledger` (r:1 w:1) + /// Proof: `OcifStaking::Ledger` (`max_values`: None, `max_size`: Some(265), added: 2740, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::CurrentEra` (r:1 w:0) + /// Proof: `OcifStaking::CurrentEra` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `Balances::Locks` (r:1 w:1) + /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) + /// Storage: `Balances::Freezes` (r:1 w:0) + /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::GeneralEraInfo` (r:1 w:1) + /// Proof: `OcifStaking::GeneralEraInfo` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) + fn withdraw_unstaked() -> Weight { + // Proof Size summary in bytes: + // Measured: `449` + // Estimated: `4764` + // Minimum execution time: 31_000_000 picoseconds. + Weight::from_parts(32_000_000, 4764) + .saturating_add(RocksDbWeight::get().reads(6_u64)) + .saturating_add(RocksDbWeight::get().writes(3_u64)) + } + /// Storage: `OcifStaking::Halted` (r:1 w:0) + /// Proof: `OcifStaking::Halted` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::GeneralStakerInfo` (r:1 w:1) + /// Proof: `OcifStaking::GeneralStakerInfo` (`max_values`: None, `max_size`: Some(269), added: 2744, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::CurrentEra` (r:1 w:0) + /// Proof: `OcifStaking::CurrentEra` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::CoreEraStake` (r:1 w:0) + /// Proof: `OcifStaking::CoreEraStake` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::GeneralEraInfo` (r:1 w:0) + /// Proof: `OcifStaking::GeneralEraInfo` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) + fn staker_claim_rewards() -> Weight { + // Proof Size summary in bytes: + // Measured: `374` + // Estimated: `3734` + // Minimum execution time: 18_000_000 picoseconds. + Weight::from_parts(19_000_000, 3734) + .saturating_add(RocksDbWeight::get().reads(5_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + /// Storage: `OcifStaking::Halted` (r:1 w:0) + /// Proof: `OcifStaking::Halted` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::CurrentEra` (r:1 w:0) + /// Proof: `OcifStaking::CurrentEra` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::CoreEraStake` (r:1 w:1) + /// Proof: `OcifStaking::CoreEraStake` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::GeneralEraInfo` (r:1 w:0) + /// Proof: `OcifStaking::GeneralEraInfo` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) + fn core_claim_rewards() -> Weight { + // Proof Size summary in bytes: + // Measured: `377` + // Estimated: `3557` + // Minimum execution time: 18_000_000 picoseconds. + Weight::from_parts(19_000_000, 3557) + .saturating_add(RocksDbWeight::get().reads(5_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + /// Storage: `OcifStaking::Halted` (r:1 w:1) + /// Proof: `OcifStaking::Halted` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + fn halt_unhalt_pallet() -> Weight { + // Proof Size summary in bytes: + // Measured: `4` + // Estimated: `1486` + // Minimum execution time: 5_000_000 picoseconds. + Weight::from_parts(5_000_000, 1486) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + /// Storage: `OcifStaking::Halted` (r:1 w:0) + /// Proof: `OcifStaking::Halted` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::RegisteredCore` (r:1 w:0) + /// Proof: `OcifStaking::RegisteredCore` (`max_values`: None, `max_size`: Some(477), added: 2952, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::CurrentEra` (r:1 w:0) + /// Proof: `OcifStaking::CurrentEra` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::GeneralStakerInfo` (r:2 w:2) + /// Proof: `OcifStaking::GeneralStakerInfo` (`max_values`: None, `max_size`: Some(269), added: 2744, mode: `MaxEncodedLen`) + /// Storage: `OcifStaking::CoreEraStake` (r:2 w:2) + /// Proof: `OcifStaking::CoreEraStake` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + fn move_stake() -> Weight { + // Proof Size summary in bytes: + // Measured: `302` + // Estimated: `6478` + // Minimum execution time: 24_000_000 picoseconds. + Weight::from_parts(25_000_000, 6478) + .saturating_add(RocksDbWeight::get().reads(7_u64)) + .saturating_add(RocksDbWeight::get().writes(4_u64)) + } +} diff --git a/pallets/README.md b/pallets/README.md new file mode 100644 index 00000000..1d21007a --- /dev/null +++ b/pallets/README.md @@ -0,0 +1,85 @@ +
+ +
+ +
+

InvArch FRAME Pallet Library

+ + +[![Twitter URL](https://img.shields.io/twitter/url?style=social&url=https%3A%2F%2Ftwitter.com%2FInvArch)](https://twitter.com/InvArchNetwork) +[![Discord](https://img.shields.io/badge/Discord-gray?logo=discord)](https://discord.gg/invarch) +[![Telegram](https://img.shields.io/badge/Telegram-gray?logo=telegram)](https://t.me/InvArch) +[![Knowledge Hub](https://img.shields.io/badge/🧠_Knwoledge_hub-gray)](https://abstracted.notion.site/Knowledge-Hub-eec0071f36364d6aa8138f0004ac8d85) +
+[![Polkadot SDK version](https://img.shields.io/badge/Polkadot_SDK-V1.6.0-E6007A?logo=polkadot)](https://github.com/paritytech/polkadot-sdk/releases/tag/polkadot-v1.6.0) +[![Medium](https://img.shields.io/badge/Medium-InvArch-E6007A?logo=medium)](https://invarch.medium.com/) +[![License](https://img.shields.io/github/license/InvArch/InvArch?color=E6007A)](https://github.com/InvArch/InvArch/blob/main/LICENSE) +[![Library Docs](https://img.shields.io/badge/Library-Docs%2Ers-E6007A?logo=docsdotrs)](https://invarch.github.io/InvArch-Frames/) + +
+ +--- + +## Intro + +This repository should contain the Polkadot SDK FRAME Pallets used in the InvArch blockchain, and reviews their relationships and functions. At the current stage, the goal of creating this document and repository is centered around getting feedback while we continue to write the code and develop InvArch. This is a WIP. + +Check out the [Knowledge Hub](https://abstracted.notion.site/Knowledge-Hub-eec0071f36364d6aa8138f0004ac8d85), it is the perfect place to dive into all things InvArch + +## Overview + +InvArch is a blockchain network & cross-consensus operating system for DAOs. InvArch revolves around on multi-party ownership & computation with a focus on non-custodial asset management, intellectual property rights facilitation, & DAO operations. + +Currently, InvArch features a multichain multisignature solution & DAO staking protocol. + +--- + +# Pallet Library + + ## [INV4](./INV4/pallet-inv4/) + - The INV4 pallet is designed to manage advanced virtual multisigs, internally referred to as cores. + - [`Docs.rs`](https://invarch.github.io/InvArch-Frames/pallet_inv4/index.html) + - Articles: + - [`The Saturn SDK.`](https://invarch.medium.com/the-saturn-sdk-c46b4e40f46e) + - [`The INV4 Protocol: The Core of the Creator Economy.`](https://invarch.medium.com/the-inv4-protocol-the-core-of-the-creator-economy-1af59fdbc943) + - [`🪐 Saturn: The Future of Multi-Party Ownership.`](https://invarch.medium.com/saturn-the-future-of-multi-party-ownership-ac7190f86a7b) + + ## [OCIF](./OCIF/staking/) + - The OCIF Staking Pallet is a pallet designed to facilitate staking towards INV-Cores within a blockchain network. + - [`Docs.rs`](https://invarch.github.io/InvArch-Frames/pallet_ocif_staking/index.html) + - Articles: + - [`The OCIF Protocol: Permissionless Funding for DAOs & Creators.`](https://invarch.medium.com/the-ocif-protocol-permissionless-funding-for-daos-creators-505aa18098f1) + - DAO Staking is live on [InvArch](https://portal.invarch.network/staking) and [Tinkernet](https://www.tinker.network/staking). + + ## [Rings](./pallet-rings) + - The Rings pallet provides a cross-consensus message (XCM) abstraction layer for INV4 Cores. + - [`Docs.rs`](https://invarch.github.io/InvArch-Frames/pallet_rings/index.html) + + ## [Checked Inflation](./pallet-checked-inflation) + - The Checked Inflation pallet is designed to facilitate the inflationary aspect of a blockchain's economy. + - [`Docs.rs`](https://invarch.github.io/InvArch-Frames/pallet_checked_inflation/index.html) + +--- + +## How to contribute + +We need volunteer developers to help this idea become a reality! + +If you haven't already, come find us on the [#InvArch Discord](https://discord.gg/invarch). We want you working on things you're excited about! + +### Submitting changes + +Please send a [GitHub Pull Request to InvArch](https://github.com/InvArch/InvArch/pull/new/master) with a clear list of what you've done (read more about [pull requests](http://help.github.com/pull-requests/)). Please make sure all of your commits are atomic (one feature per commit). + +Always write a clear log message for your commits. One-line messages are fine for small changes, but bigger changes should look like this: + + $ git commit -m "A brief summary of the commit + > + > A paragraph describing what changed and its impact." + +Please make sure to update tests as appropriate. + + +### License + +[GPLv3.0](https://github.com/InvArch/InvArch/blob/main/LICENSE) diff --git a/pallets/pallet-checked-inflation/Cargo.toml b/pallets/pallet-checked-inflation/Cargo.toml new file mode 100644 index 00000000..495ff357 --- /dev/null +++ b/pallets/pallet-checked-inflation/Cargo.toml @@ -0,0 +1,60 @@ +[package] +name = 'pallet-checked-inflation' +authors = ['InvArchitects '] +description = 'FRAME pallet to IP staking' +edition = '2018' +homepage = 'https://invarch.network' +license = 'GPLv3' +repository = 'https://github.com/InvArch/InvArch-Pallet-Library/' +version = '0.1.0-dev' + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[dependencies] +codec = {workspace = true, default-features = false} +scale-info = {workspace = true, default-features = false} +serde = {workspace = true, optional = true} + +frame-support = {workspace = true, default-features = false} +frame-system = {workspace = true, default-features = false} +num-traits = {workspace = true, default-features = false} +pallet-session = {workspace = true, default-features = false} +sp-arithmetic = {workspace = true, default-features = false} +sp-core = {workspace = true, default-features = false} +sp-io = {workspace = true, default-features = false} +sp-runtime = {workspace = true, default-features = false} +sp-staking = {workspace = true, default-features = false} +sp-std = {workspace = true, default-features = false} + +frame-benchmarking = {workspace = true, default-features = false, optional = true} + +[dev-dependencies] +pallet-balances = {workspace = true, default-features = false} + +[features] +default = ["std"] +std = [ + "serde", + "codec/std", + "scale-info/std", + "num-traits/std", + "sp-core/std", + "sp-runtime/std", + "sp-arithmetic/std", + "sp-io/std", + "sp-std/std", + "frame-support/std", + "frame-system/std", + "frame-benchmarking?/std", + "pallet-session/std", + "sp-staking/std", + "pallet-balances/std", + +] +runtime-benchmarks = [ + "frame-benchmarking/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", + "frame-system/runtime-benchmarks", +] +try-runtime = ["frame-support/try-runtime"] diff --git a/pallets/pallet-checked-inflation/README.md b/pallets/pallet-checked-inflation/README.md new file mode 100644 index 00000000..8eec92ed --- /dev/null +++ b/pallets/pallet-checked-inflation/README.md @@ -0,0 +1,65 @@ +# Checked Inflation Pallet + +## Overview + +The Checked Inflation Pallet is designed to facilitate the inflationary aspect of a blockchain's economy. +It automatically mints new tokens at the start of every era, with the amount determined by a configurable inflation method. +This functionality is crucial for maintaining a controlled expansion of the token supply, aligning with economic models or rewarding network participants. + +### Key Features + +- **Configurable Inflation**: The amount and method of inflation can be tailored to suit the blockchain's economic model. +- **Automatic Token Minting**: New tokens are minted automatically at the beginning of each era. +- **Yearly and Era-Based Inflation**: Supports fixed yearly, fixed per era, or rate-based inflation calculations. + +## Functionality + +The pallet's core functionality revolves around the `on_initialize` hook, which triggers at the beginning of each block. +If conditions align (start of a new era or year), the pallet calculates the amount to mint based on the configured inflation method and mints the tokens. + +## Inflation Methods + +Inflation can be configured in one of three ways, as defined in the `InflationMethod` enum: + +- **Rate**: A percentage of the current supply. +- **FixedYearly**: A fixed amount distributed evenly across all eras in a year. +- **FixedPerEra**: A fixed amount minted at the start of each era. + +The choice of method allows for flexibility in how the token supply expands over time, catering to different economic strategies. + +## Dispatchable Functions + +### `set_first_year_supply` + +Configures the initial token supply at the year's start, preparing the system for accurate inflation calculation. + +- **Access Control**: Root + +### `halt_unhalt_pallet` + +Toggles the inflation process, allowing it to be halted or resumed based on network needs. + +- **Parameters**: + - `halt`: A boolean indicating whether to halt (`true`) or resume (`false`) the inflation process. +- **Access Control**: Root + + +## Events + +- **NewYear**: Marks the beginning of a new year, resetting era counts and updating the starting issuance for inflation calculations. +- **NewEra**: Signifies the start of a new era, triggering token minting according to the configured inflation rate. +- **InflationMinted**: Indicates that tokens have been minted due to inflation, detailing the amounts involved. +- **OverInflationDetected**: Warns of excess token minting beyond expected amounts, prompting corrective measures. +- **HaltChanged**: Reports changes in the inflation process's halt status. + +## Errors + +- **NoHaltChange**: Triggered when attempting to change the halt status to its current value, indicating no action is needed. + +## Conclusion + +The Checked Inflation Pallet offers a flexible and automated way to manage token supply expansion through inflation. +By configuring the inflation method to match your blockchain's economic model, you can ensure a controlled and predictable increase in token supply, +this pallet is an essential tool for managing network growth and stability through controlled inflation in response to evolving economic conditions, +ensuring long-term sustainability. + diff --git a/pallets/pallet-checked-inflation/src/benchmarking.rs b/pallets/pallet-checked-inflation/src/benchmarking.rs new file mode 100644 index 00000000..e79853ce --- /dev/null +++ b/pallets/pallet-checked-inflation/src/benchmarking.rs @@ -0,0 +1,22 @@ +#![cfg(feature = "runtime-benchmarks")] + +use super::*; +use frame_benchmarking::benchmarks; +use frame_system::RawOrigin as SystemOrigin; + +fn assert_last_event(generic_event: ::RuntimeEvent) { + frame_system::Pallet::::assert_last_event(generic_event.into()); +} + +benchmarks! { + set_first_year_supply { + }: _(SystemOrigin::Root) + + halt_unhalt_pallet { + }: _(SystemOrigin::Root, true) + verify { + assert_last_event::(Event::::HaltChanged { + is_halted: true + }.into()); + } +} diff --git a/pallets/pallet-checked-inflation/src/inflation.rs b/pallets/pallet-checked-inflation/src/inflation.rs new file mode 100644 index 00000000..60441b7d --- /dev/null +++ b/pallets/pallet-checked-inflation/src/inflation.rs @@ -0,0 +1,43 @@ +//! Available inflation methods and resulting inflation amount generated per era. +//! +//! ## Overview +//! +//! This module contains the available inflation methods and the resulting inflation amount generated per era. + +use crate::{BalanceOf, Config}; +use codec::{Decode, Encode}; +use scale_info::TypeInfo; +use sp_arithmetic::per_things::Perbill; + +/// Inflation methods. +/// +/// The inflation methods are used to determine the amount of inflation generated per era. +#[derive(TypeInfo, Encode, Decode)] +pub enum InflationMethod { + /// The inflation is calculated as a percentage (`Perbill`) of the current supply. + Rate(Perbill), + /// The inflation is a fixed amount per year. + FixedYearly(Balance), + /// The inflation is a fixed amount per era. + FixedPerEra(Balance), +} + +/// Getter trait for the inflation amount to be minted in each era. +pub trait GetInflation { + /// Returns the inflation amount to be minted per era. + fn get_inflation_args(&self, eras_per_year: u32, current_supply: BalanceOf) -> BalanceOf; +} + +impl GetInflation for InflationMethod> +where + u32: Into>, +{ + /// Returns the inflation amount to be minted per era based on the inflation method. + fn get_inflation_args(&self, eras_per_year: u32, current_supply: BalanceOf) -> BalanceOf { + match self { + Self::Rate(rate) => (*rate * current_supply) / eras_per_year.into(), + Self::FixedYearly(amount) => *amount / eras_per_year.into(), + Self::FixedPerEra(amount) => *amount, + } + } +} diff --git a/pallets/pallet-checked-inflation/src/lib.rs b/pallets/pallet-checked-inflation/src/lib.rs new file mode 100644 index 00000000..7cbec736 --- /dev/null +++ b/pallets/pallet-checked-inflation/src/lib.rs @@ -0,0 +1,344 @@ +//! # Checked Inflation Pallet +//! +//! - [`Config`] +//! - [`Call`] +//! - [`Pallet`] +//! +//! ## Overview +//! This is a supporting pallet that provides the functionality for inflation. It is used to mint new tokens at the beginning of every era. +//! +//! The amount of tokens minted is determined by the inflation method and its amount, and is configurable in the runtime, +//! see the [`inflation`] module for the methods of inflation available and how their inflation amounts are calculated. +//! +//! Most of the logic is implemented in the `on_initialize` hook, which is called at the beginning of every block. +//! +//! ## Dispatchable Functions +//! +//! - `set_first_year_supply` - For configuring the pallet, sets the token's `YearStartIssuance` to its current total issuance. +//! - `halt_unhalt_pallet` - To start or stop the inflation process. + +#![cfg_attr(not(feature = "std"), no_std)] + +use frame_support::traits::Get; +use sp_arithmetic::traits::Zero; +use sp_std::convert::TryInto; + +mod inflation; + +#[cfg(feature = "runtime-benchmarks")] +mod benchmarking; +#[cfg(test)] +pub(crate) mod mock; + +#[cfg(test)] +mod test; + +pub use inflation::*; +pub use pallet::*; + +pub mod weights; + +pub use weights::WeightInfo; + +#[frame_support::pallet] +pub mod pallet { + use super::*; + use frame_support::{ + pallet_prelude::*, + traits::{Currency, LockableCurrency, OnUnbalanced, ReservableCurrency}, + }; + use frame_system::{ + ensure_root, + pallet_prelude::{BlockNumberFor, OriginFor}, + }; + use num_traits::CheckedSub; + + /// The balance type of this pallet. + pub(crate) type BalanceOf = + <::Currency as Currency<::AccountId>>::Balance; + + /// The opaque token type for an imbalance. This is returned by unbalanced operations and must be dealt with. + type NegativeImbalanceOf = <::Currency as Currency< + ::AccountId, + >>::NegativeImbalance; + + #[pallet::pallet] + pub struct Pallet(_); + + #[pallet::config] + pub trait Config: frame_system::Config { + /// The overarching event type. + type RuntimeEvent: From> + IsType<::RuntimeEvent>; + /// The currency (token) used in this pallet. + type Currency: LockableCurrency> + + ReservableCurrency + + Currency; + + /// Number of blocks per era. + #[pallet::constant] + type BlocksPerEra: Get>; + + /// Number of eras per year. + #[pallet::constant] + type ErasPerYear: Get; + + /// The inflation method and its amount. + #[pallet::constant] + type Inflation: Get>>; + + /// The `NegativeImbalanceOf` the currency, i.e. the amount of inflation to be applied. + type DealWithInflation: OnUnbalanced>; + + /// Weight information for extrinsics in this pallet. + type WeightInfo: WeightInfo; + } + + /// The current era. Starts from 1 and is reset every year. + #[pallet::storage] + #[pallet::getter(fn current_era)] + pub type CurrentEra = StorageValue<_, u32, ValueQuery>; + + /// Block that the next era starts at. + #[pallet::storage] + #[pallet::getter(fn next_era_starting_block)] + pub type NextEraStartingBlock = StorageValue<_, BlockNumberFor, ValueQuery>; + + /// Total token supply at the very beginning of the year before any inflation has been minted. + #[pallet::storage] + #[pallet::getter(fn year_start_issuance)] + pub type YearStartIssuance = StorageValue<_, BalanceOf, ValueQuery>; + + /// The number of tokens minted at the beginning of every era during a year. + #[pallet::storage] + #[pallet::getter(fn inflation_per_era)] + pub type YearlyInflationPerEra = StorageValue<_, BalanceOf, ValueQuery>; + + /// Whether the inflation process is halted. + #[pallet::storage] + #[pallet::getter(fn is_halted)] + pub type Halted = StorageValue<_, bool, ValueQuery>; + + #[pallet::error] + pub enum Error { + /// The pallet is already in the state that the user is trying to change it to. + NoHaltChange, + } + + #[pallet::event] + #[pallet::generate_deposit(fn deposit_event)] + pub enum Event { + /// Beginning of a new year. + NewYear { + starting_issuance: BalanceOf, + next_era_starting_block: BlockNumberFor, + }, + + /// Beginning of a new era. + NewEra { + era: u32, + next_era_starting_block: BlockNumberFor, + }, + + /// Tokens minted due to inflation. + InflationMinted { + year_start_issuance: BalanceOf, + current_issuance: BalanceOf, + expected_new_issuance: BalanceOf, + minted: BalanceOf, + }, + + /// Total supply of the token is higher than expected by Checked Inflation. + OverInflationDetected { + expected_issuance: BalanceOf, + current_issuance: BalanceOf, + }, + + /// Halt status changed. + HaltChanged { is_halted: bool }, + } + + #[pallet::hooks] + impl Hooks> for Pallet + where + BalanceOf: CheckedSub, + { + fn on_initialize(now: BlockNumberFor) -> Weight { + let previous_era = Self::current_era(); + let next_era_starting_block = Self::next_era_starting_block(); + + let blocks_per_era = T::BlocksPerEra::get(); + + let eras_per_year = T::ErasPerYear::get(); + + let is_halted = Self::is_halted(); + + if previous_era >= eras_per_year && now >= next_era_starting_block + || next_era_starting_block == Zero::zero() + { + // Reset block # back to 1 for the new year + CurrentEra::::put(1); + + NextEraStartingBlock::::put(now + blocks_per_era); + + let current_issuance = + <::Currency as Currency>::total_issuance(); + + YearStartIssuance::::put(current_issuance); + + let inflation_per_era = GetInflation::::get_inflation_args( + &T::Inflation::get(), + eras_per_year, + current_issuance, + ); + + YearlyInflationPerEra::::put(inflation_per_era); + + Self::deposit_event(Event::NewYear { + starting_issuance: current_issuance, + next_era_starting_block: (now + blocks_per_era), + }); + + if !is_halted { + Self::mint(inflation_per_era); + + Self::deposit_event(Event::InflationMinted { + year_start_issuance: current_issuance, + current_issuance, + expected_new_issuance: current_issuance + inflation_per_era, + minted: inflation_per_era, + }); + } + + T::DbWeight::get().reads_writes(3, 4) + } else { + let inflation_per_era = Self::inflation_per_era(); + + if now >= next_era_starting_block || previous_era.is_zero() { + CurrentEra::::put(previous_era + 1); + + NextEraStartingBlock::::put(now + blocks_per_era); + + Self::deposit_event(Event::NewEra { + era: (previous_era + 1), + next_era_starting_block: (now + blocks_per_era), + }); + + if !is_halted { + // Get issuance that the year started at + let start_issuance = Self::year_start_issuance(); + + // Get actual current total token issuance + let current_issuance = + <::Currency as Currency>::total_issuance(); + + // Calculate the expected current total token issuance + let expected_current_issuance = + start_issuance + (inflation_per_era * previous_era.into()); + + // Check that current_issuance and expected_current_issuance match in value. + // If the result is > 0, too many tokens were minted. + match current_issuance.checked_sub(&expected_current_issuance) { + // Either current issuance matches the expected issuance, or current issuance is higher than expected + // meaning too many tokens were minted + Some(over_inflation) if over_inflation > Zero::zero() => { + Self::deposit_event(Event::OverInflationDetected { + expected_issuance: expected_current_issuance, + current_issuance, + }); + + // Mint the difference + if let Some(to_mint) = + inflation_per_era.checked_sub(&over_inflation) + { + Self::mint(to_mint); + + Self::deposit_event(Event::InflationMinted { + year_start_issuance: start_issuance, + current_issuance, + expected_new_issuance: expected_current_issuance + + inflation_per_era, + minted: to_mint, + }); + } + } + + _ => { + Self::mint(inflation_per_era); + + Self::deposit_event(Event::InflationMinted { + year_start_issuance: start_issuance, + current_issuance, + expected_new_issuance: expected_current_issuance + + inflation_per_era, + minted: inflation_per_era, + }); + } + } + + T::DbWeight::get().reads_writes(5, 2) + } else { + T::DbWeight::get().reads_writes(4, 2) + } + } else { + T::DbWeight::get().reads(4) + } + } + } + } + + #[pallet::call] + impl Pallet { + /// This call is used for configuring the inflation mechanism and sets the token's `YearStartIssuance` to its current total issuance. + /// + /// The origin has to have `root` access. + #[pallet::call_index(0)] + #[pallet::weight( + ::WeightInfo::set_first_year_supply() + )] + pub fn set_first_year_supply(root: OriginFor) -> DispatchResult { + ensure_root(root)?; + + YearStartIssuance::::put( + <::Currency as Currency>::total_issuance(), + ); + + Ok(()) + } + + /// Halts or unhalts the inflation process. + /// + /// The origin has to have `root` access. + /// + /// - `halt`: `true` to halt the inflation process, `false` to unhalt it. + #[pallet::call_index(1)] + #[pallet::weight( + ::WeightInfo::halt_unhalt_pallet() + )] + pub fn halt_unhalt_pallet(root: OriginFor, halt: bool) -> DispatchResult { + ensure_root(root)?; + + let is_halted = Self::is_halted(); + + ensure!(is_halted ^ halt, Error::::NoHaltChange); + + Self::internal_halt_unhalt(halt); + + Self::deposit_event(Event::::HaltChanged { is_halted: halt }); + + Ok(()) + } + } + + impl Pallet { + /// Internal function for minting tokens to the currency due to inflation. + fn mint(amount: BalanceOf) { + let inflation = T::Currency::issue(amount); + ::DealWithInflation::on_unbalanced(inflation); + } + + /// Internal function to set the halt status to storage. + pub fn internal_halt_unhalt(halt: bool) { + Halted::::put(halt); + } + } +} diff --git a/pallets/pallet-checked-inflation/src/mock.rs b/pallets/pallet-checked-inflation/src/mock.rs new file mode 100644 index 00000000..f0322edc --- /dev/null +++ b/pallets/pallet-checked-inflation/src/mock.rs @@ -0,0 +1,150 @@ +use super::*; +use crate::inflation::InflationMethod; +use core::convert::TryFrom; +use frame_support::{ + derive_impl, parameter_types, + traits::{ConstU128, ConstU32, ConstU64, Currency, Hooks, OnUnbalanced}, +}; +use pallet_balances::AccountData; +use sp_core::H256; +use sp_runtime::{traits::IdentityLookup, BuildStorage, Perbill}; + +type Block = frame_system::mocking::MockBlock; +type Balance = u128; + +type AccountId = u32; +type NegativeImbalance = >::NegativeImbalance; + +pub const EXISTENTIAL_DEPOSIT: Balance = 1_000_000_000; + +pub const INFLATION_RECEIVER: AccountId = 0; +pub const ALICE: AccountId = 1; + +frame_support::construct_runtime!( + pub enum Test + { + System: frame_system, + Balances: pallet_balances, + CheckedInflation: pallet, + } +); + +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +impl frame_system::Config for Test { + type RuntimeOrigin = RuntimeOrigin; + type Nonce = u64; + type Block = Block; + type RuntimeCall = RuntimeCall; + type Hash = H256; + type Hashing = ::sp_runtime::traits::BlakeTwo256; + type AccountId = AccountId; + type Lookup = IdentityLookup; + type RuntimeEvent = RuntimeEvent; + type BlockHashCount = ConstU64<250>; + type PalletInfo = PalletInfo; + type AccountData = AccountData; + type MaxConsumers = ConstU32<16>; +} + +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig as pallet_balances::DefaultConfig)] +impl pallet_balances::Config for Test { + type MaxLocks = ConstU32<50>; + type Balance = Balance; + type RuntimeEvent = RuntimeEvent; + type ExistentialDeposit = ConstU128; + type AccountStore = System; + type MaxReserves = ConstU32<50>; + type ReserveIdentifier = [u8; 8]; +} + +parameter_types! { + pub const Inflation: InflationMethod> = InflationMethod::Rate(Perbill::from_percent(10)); +} + +pub struct DealWithInflation; +impl OnUnbalanced for DealWithInflation { + fn on_unbalanced(amount: NegativeImbalance) { + Balances::resolve_creating(&INFLATION_RECEIVER, amount) + } +} + +pub const BLOCKS_PER_ERA: u64 = 4; +pub const ERAS_PER_YEAR: u32 = 365; + +impl pallet::Config for Test { + type BlocksPerEra = ConstU64; + type Currency = Balances; + type RuntimeEvent = RuntimeEvent; + type ErasPerYear = ConstU32; + type Inflation = Inflation; + type DealWithInflation = DealWithInflation; + type WeightInfo = weights::SubstrateWeight; +} + +pub struct ExtBuilder; + +impl Default for ExtBuilder { + fn default() -> Self { + ExtBuilder + } +} + +pub const GENESIS_ISSUANCE: u128 = 11700000000000000000; + +impl ExtBuilder { + pub fn build(self) -> sp_io::TestExternalities { + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); + + pallet_balances::GenesisConfig:: { + balances: vec![(INFLATION_RECEIVER, GENESIS_ISSUANCE)], + } + .assimilate_storage(&mut t) + .unwrap(); + + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(0)); + + // ext.execute_with(|| YearStartIssuance::::put(Balances::total_issuance())); + + // ext.execute_with(|| run_to_block(1)); + + ext + } +} + +pub fn run_to_block(n: u64) { + while System::block_number() < n { + if System::block_number() > 1 { + System::on_finalize(System::block_number()); + } + System::set_block_number(System::block_number() + 1); + System::on_initialize(System::block_number()); + CheckedInflation::on_initialize(System::block_number()); + } +} + +pub fn run_to_next_era() { + run_to_block(CheckedInflation::next_era_starting_block()) +} + +pub fn run_to_next_year() { + // run_to_next_era(); + + let current_era = CheckedInflation::current_era(); + + run_to_block(System::block_number() + ((ERAS_PER_YEAR - current_era) as u64 * BLOCKS_PER_ERA)); + + run_to_next_era(); +} + +pub fn run_to_half_year() { + run_to_next_era(); + + let current_era = CheckedInflation::current_era(); + + run_to_block( + System::block_number() + (((ERAS_PER_YEAR / 2) - current_era) as u64 * BLOCKS_PER_ERA), + ); +} diff --git a/pallets/pallet-checked-inflation/src/test.rs b/pallets/pallet-checked-inflation/src/test.rs new file mode 100644 index 00000000..42fedff7 --- /dev/null +++ b/pallets/pallet-checked-inflation/src/test.rs @@ -0,0 +1,193 @@ +use crate::{mock::*, *}; +use frame_support::{ + assert_ok, + traits::{Currency, Imbalance}, +}; + +#[test] +fn inflate_one_era() { + ExtBuilder::default().build().execute_with(|| { + assert_eq!(CheckedInflation::current_era(), 0); + + run_to_block(1); + + assert_eq!(CheckedInflation::current_era(), 1); + + let per_era = GetInflation::::get_inflation_args( + &Inflation::get(), + ERAS_PER_YEAR, + GENESIS_ISSUANCE, + ); + + assert_eq!(Balances::total_issuance(), GENESIS_ISSUANCE + per_era); + + run_to_next_era(); + + assert_eq!(CheckedInflation::current_era(), 2); + + assert_eq!(Balances::total_issuance(), GENESIS_ISSUANCE + (per_era * 2)); + }); +} + +#[test] +fn inflate_one_year() { + ExtBuilder::default().build().execute_with(|| { + assert_eq!(CheckedInflation::current_era(), 0); + + run_to_block(1); + + assert_eq!(CheckedInflation::current_era(), 1); + + let per_era = GetInflation::::get_inflation_args( + &Inflation::get(), + ERAS_PER_YEAR, + GENESIS_ISSUANCE, + ); + + assert_eq!(Balances::total_issuance(), GENESIS_ISSUANCE + per_era); + + run_to_next_year(); + + assert_eq!(CheckedInflation::current_era(), 1); + assert_eq!( + CheckedInflation::year_start_issuance(), + GENESIS_ISSUANCE + (per_era * ERAS_PER_YEAR as u128) + ); + + let per_era_second_year = GetInflation::::get_inflation_args( + &Inflation::get(), + ERAS_PER_YEAR, + CheckedInflation::year_start_issuance(), + ); + + assert_eq!(CheckedInflation::inflation_per_era(), per_era_second_year); + + assert_eq!( + Balances::total_issuance(), + GENESIS_ISSUANCE + (per_era * ERAS_PER_YEAR as u128) + per_era_second_year + ); + }) +} + +#[test] +fn overinflate_then_run_to_next_year() { + ExtBuilder::default().build().execute_with(|| { + assert_eq!(CheckedInflation::current_era(), 0); + + run_to_block(1); + + assert_eq!(CheckedInflation::current_era(), 1); + + let per_era = GetInflation::::get_inflation_args( + &Inflation::get(), + ERAS_PER_YEAR, + GENESIS_ISSUANCE, + ); + + run_to_half_year(); + + let pre_mint = Balances::total_issuance(); + + Balances::deposit_creating(&ALICE, (per_era * ERAS_PER_YEAR as u128) / 4).peek(); + + assert_ne!(pre_mint, Balances::total_issuance()); + + run_to_next_year(); + + assert_eq!(CheckedInflation::current_era(), 1); + assert_eq!( + CheckedInflation::year_start_issuance(), + GENESIS_ISSUANCE + (per_era * ERAS_PER_YEAR as u128) + ); + + let per_era_second_year = GetInflation::::get_inflation_args( + &Inflation::get(), + ERAS_PER_YEAR, + CheckedInflation::year_start_issuance(), + ); + + assert_eq!(CheckedInflation::inflation_per_era(), per_era_second_year); + + assert_eq!( + Balances::total_issuance(), + GENESIS_ISSUANCE + (per_era * ERAS_PER_YEAR as u128) + per_era_second_year + ); + }) +} + +#[test] +fn halt() { + ExtBuilder::default().build().execute_with(|| { + assert_eq!(CheckedInflation::current_era(), 0); + + run_to_block(1); + + assert_eq!(CheckedInflation::current_era(), 1); + + let per_era = GetInflation::::get_inflation_args( + &Inflation::get(), + ERAS_PER_YEAR, + GENESIS_ISSUANCE, + ); + + assert_eq!(Balances::total_issuance(), GENESIS_ISSUANCE + per_era); + + run_to_next_era(); + + assert_eq!(CheckedInflation::current_era(), 2); + + assert_eq!(Balances::total_issuance(), GENESIS_ISSUANCE + (per_era * 2)); + + assert_ok!(CheckedInflation::halt_unhalt_pallet( + RuntimeOrigin::root(), + true + )); + + run_to_next_era(); + + assert_eq!(CheckedInflation::current_era(), 3); + + assert_eq!(Balances::total_issuance(), GENESIS_ISSUANCE + (per_era * 2)); + + run_to_next_year(); + + let per_era_second_year = GetInflation::::get_inflation_args( + &Inflation::get(), + ERAS_PER_YEAR, + CheckedInflation::year_start_issuance(), + ); + + assert_eq!(CheckedInflation::current_era(), 1); + + assert_eq!(Balances::total_issuance(), GENESIS_ISSUANCE + (per_era * 2)); + + run_to_next_era(); + + assert_eq!(CheckedInflation::current_era(), 2); + + assert_eq!(Balances::total_issuance(), GENESIS_ISSUANCE + (per_era * 2)); + + assert_ok!(CheckedInflation::halt_unhalt_pallet( + RuntimeOrigin::root(), + false + )); + + run_to_next_era(); + + assert_eq!(CheckedInflation::current_era(), 3); + + assert_eq!( + Balances::total_issuance(), + GENESIS_ISSUANCE + (per_era * 2) + per_era_second_year + ); + + run_to_next_era(); + + assert_eq!(CheckedInflation::current_era(), 4); + + assert_eq!( + Balances::total_issuance(), + GENESIS_ISSUANCE + (per_era * 2) + (per_era_second_year * 2) + ); + }); +} diff --git a/pallets/pallet-checked-inflation/src/weights.rs b/pallets/pallet-checked-inflation/src/weights.rs new file mode 100644 index 00000000..f8dcdb43 --- /dev/null +++ b/pallets/pallet-checked-inflation/src/weights.rs @@ -0,0 +1,88 @@ + +//! Autogenerated weights for `pallet_checked_inflation` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2024-05-24, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `anny.local`, CPU: `` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` + +// Executed Command: +// ./target/release/tinkernet-collator +// benchmark +// pallet +// --chain=dev +// --wasm-execution=compiled +// --pallet=pallet-checked-inflation +// --extrinsic=* +// --steps +// 50 +// --repeat +// 20 +// --output=../../InvArch-Frames/pallet-checked-inflation/src/weights.rs +// --template=../weights-template.hbs + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use core::marker::PhantomData; + +/// Weight functions needed for `pallet_checked_inflation`. +pub trait WeightInfo { + fn set_first_year_supply() -> Weight; + fn halt_unhalt_pallet() -> Weight; +} + +/// Weights for `pallet_checked_inflation` using the Substrate node and recommended hardware. +pub struct SubstrateWeight(PhantomData); +impl WeightInfo for SubstrateWeight { + /// Storage: `CheckedInflation::YearStartIssuance` (r:0 w:1) + /// Proof: `CheckedInflation::YearStartIssuance` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) + fn set_first_year_supply() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_000_000 picoseconds. + Weight::from_parts(3_000_000, 0) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + /// Storage: `CheckedInflation::Halted` (r:1 w:1) + /// Proof: `CheckedInflation::Halted` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + fn halt_unhalt_pallet() -> Weight { + // Proof Size summary in bytes: + // Measured: `42` + // Estimated: `1486` + // Minimum execution time: 5_000_000 picoseconds. + Weight::from_parts(6_000_000, 1486) + .saturating_add(T::DbWeight::get().reads(1_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } +} + +// For backwards compatibility and tests. +impl WeightInfo for () { + /// Storage: `CheckedInflation::YearStartIssuance` (r:0 w:1) + /// Proof: `CheckedInflation::YearStartIssuance` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) + fn set_first_year_supply() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_000_000 picoseconds. + Weight::from_parts(3_000_000, 0) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + /// Storage: `CheckedInflation::Halted` (r:1 w:1) + /// Proof: `CheckedInflation::Halted` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + fn halt_unhalt_pallet() -> Weight { + // Proof Size summary in bytes: + // Measured: `42` + // Estimated: `1486` + // Minimum execution time: 5_000_000 picoseconds. + Weight::from_parts(6_000_000, 1486) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } +} diff --git a/pallets/pallet-rings/Cargo.toml b/pallets/pallet-rings/Cargo.toml new file mode 100644 index 00000000..8c778f5e --- /dev/null +++ b/pallets/pallet-rings/Cargo.toml @@ -0,0 +1,87 @@ +[package] +name = 'pallet-rings' +authors = ['InvArchitects '] +description = '' +edition = '2021' +homepage = 'https://invarch.network' +license = 'GPLv3' +repository = 'https://github.com/InvArch/InvArch-Frames/' +version = '0.1.0-dev' + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[dependencies] +log = {workspace = true, default-features = false} +codec = {workspace = true, default-features = false} +scale-info = {workspace = true, default-features = false} +serde = {workspace = true, optional = true} + +frame-support = {workspace = true, default-features = false} +frame-system = {workspace = true, default-features = false} +num-traits = {workspace = true, default-features = false} +pallet-balances = {workspace = true, default-features = false} +pallet-session = {workspace = true, default-features = false} +pallet-timestamp = { workspace = true, default-features = false, optional = true } +sp-arithmetic = {workspace = true, default-features = false} +sp-core = {workspace = true, default-features = false} +sp-io = {workspace = true, default-features = false} +sp-runtime = {workspace = true} +sp-staking = {workspace = true} +sp-std = {workspace = true} + +pallet-inv4 = { path = "../INV4/pallet-inv4", default-features = false } + +pallet-xcm = {workspace = true, default-features = false} +xcm = {workspace = true, default-features = false} +xcm-executor = {workspace = true, default-features = false} + +frame-benchmarking = {workspace = true, default-features = false, optional = true} + +[dev-dependencies] +orml-traits = { workspace = true, default-features = false} +orml-traits2 = { workspace = true, default-features = false} +orml-tokens = { workspace = true, default-features = false} +orml-tokens2 = { workspace = true, default-features = false} +orml-asset-registry = { workspace = true, default-features = false} +xcm-builder = {workspace = true, default-features = false} + + +[features] +default = ["std"] +std = [ + "serde", + "codec/std", + "scale-info/std", + "num-traits/std", + "sp-core/std", + "sp-runtime/std", + "sp-arithmetic/std", + "sp-io/std", + "sp-std/std", + "frame-support/std", + "frame-system/std", + "pallet-balances/std", + "pallet-session/std", + "pallet-timestamp/std", + "sp-staking/std", + "pallet-inv4/std", + "pallet-xcm/std", + "xcm/std", + "orml-traits2/std", + "orml-traits/std", + "orml-tokens/std", + "orml-tokens2/std", + "orml-asset-registry/std", + "xcm-builder/std", + "frame-benchmarking?/std", +] +runtime-benchmarks = [ + "frame-benchmarking/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", + "frame-system/runtime-benchmarks", + "pallet-inv4/runtime-benchmarks", + "pallet-xcm/runtime-benchmarks", + "xcm-builder/runtime-benchmarks", +] +try-runtime = ["frame-support/try-runtime"] diff --git a/pallets/pallet-rings/README.md b/pallets/pallet-rings/README.md new file mode 100644 index 00000000..27a94b66 --- /dev/null +++ b/pallets/pallet-rings/README.md @@ -0,0 +1,76 @@ +# Rings Pallet + +## Overview + +The Rings pallet provides a cross-consensus message (XCM) abstraction layer for INV4 Cores, enabling them to manage assets effortlessly across multiple chains. It abstracts XCM complexities, facilitating easier handling of cross-chain transactions. + +## Key Features + +- **Maintenance Mode**: Chains can be put under maintenance, restricting certain operations to ensure system integrity during upgrades or when issues are detected. +- **Cross-chain Calls**: Enables sending XCM calls to other chains, allowing for a wide range of interactions. +- **Asset Transfers**: Supports transferring fungible assets between accounts across different chains. +- **Asset Bridging**: Facilitates the bridging of assets between chains, enhancing liquidity and asset interoperability. + +## Traits Overview + +The pallet utilizes traits to abstract chain and asset locations: + +- [`ChainList`]: Provides an interface for referencing chains and retrieving their [`MultiLocation`] or main asset. +- [`ChainAssetsList`]: Offers an interface for referencing chain assets and obtaining their [`MultiLocation`] or parent chain. + +## Dispatchable Functions + +### `set_maintenance_status` + +Sets the maintenance status of a chain. Requires `MaintenanceOrigin` authorization. + +- `chain`: The chain to modify. +- `under_maintenance`: The desired maintenance status. + +### `send_call` + +Allows sending a XCM call to another chain. Can be initiated by a core. + +- `destination`: The target chain. +- `weight`: The call's weight. +- `fee_asset`: The asset used for fee payment. +- `fee`: The fee amount. +- `call`: The call data. + +### `transfer_assets` + +Allows transfers of fungible assets to another account in the destination chain. +**Requires asset and fee_asset to be located in the same chain**. + +- `asset`: The asset to transfer. +- `amount`: The amount to transfer. +- `to`: The recipient account. +- `fee_asset`: The asset used for fee payment. +- `fee`: The fee amount. + +### `bridge_assets` + +Allows bridging of assets to another chain, with either the core account or a third-party account as the beneficiary. + +- `asset`: The asset to bridge and it's origin chain. +- `destination`: The destination chain. +- `fee`: The bridging fee. +- `amount`: The amount to bridge. +- `to`: Optional beneficiary account on the destination chain. (Defaults to the core account) + +## Events + +- `CallSent`: Emitted when a XCM call is sent to another chain. +- `AssetsTransferred`: Emitted when assets are transferred to another account on a different chain. +- `AssetsBridged`: Emitted when assets are bridged to another chain. +- `ChainMaintenanceStatusChanged`: Indicates a change in a chain's maintenance status. + +## Errors + +- `SendingFailed`: Emitted when sending a XCM message fails. +- `WeightTooHigh`: Emitted when the call's weight exceeds the maximum allowed. +- `FailedToCalculateXcmFee`: Emitted when calculating the XCM fee fails. +- `FailedToReanchorAsset`, `FailedToInvertLocation`: Errors related to asset reanchoring or location inversion. +- `DifferentChains`, `ChainUnderMaintenance`: Indicate issues with the target chain or maintenance status. + +This pallet serves as a foundational component for building cross-chain solutions within the InvArch ecosystem, streamlining asset management and interoperability across diverse blockchain environments. \ No newline at end of file diff --git a/pallets/pallet-rings/src/benchmarking.rs b/pallets/pallet-rings/src/benchmarking.rs new file mode 100644 index 00000000..8a5cae99 --- /dev/null +++ b/pallets/pallet-rings/src/benchmarking.rs @@ -0,0 +1,90 @@ +#![cfg(feature = "runtime-benchmarks")] + +use super::*; +use frame_benchmarking::{benchmarks, whitelisted_caller}; +use frame_support::{pallet_prelude::Weight, traits::Get, BoundedVec}; +use frame_system::RawOrigin as SystemOrigin; +use pallet_inv4::origin::{INV4Origin, MultisigInternalOrigin}; +use sp_std::{ops::Div, prelude::*, vec}; + +fn assert_last_event(generic_event: ::RuntimeEvent) { + frame_system::Pallet::::assert_last_event(generic_event.into()); +} + +benchmarks! { + where_clause { + where + Result< + INV4Origin, + ::RuntimeOrigin, + >: From<::RuntimeOrigin>, + ::RuntimeOrigin: From>, + + ::CoreId: Into, + + [u8; 32]: From<::AccountId>, + + T::AccountId: From<[u8; 32]>, +} + + set_maintenance_status { + let chain = T::Chains::benchmark_mock(); + + }: _(SystemOrigin::Root, chain.clone(), true) + verify { + assert_last_event::(Event::ChainMaintenanceStatusChanged { + chain, + under_maintenance: true + }.into()); + } + + send_call { + let c in 0 .. T::MaxXCMCallLength::get(); + + let call: BoundedVec = vec![u8::MAX; c as usize].try_into().unwrap(); + let destination = T::Chains::benchmark_mock(); + let weight = Weight::from_parts(100_000_000u64, 10_000u64); + let fee_asset: <::Chains as ChainList>::ChainAssets = T::Chains::benchmark_mock().get_main_asset(); + let fee: u128 = u128::MAX.div(4u128); + + }: _(INV4Origin::Multisig(MultisigInternalOrigin::new(0u32.into())), destination.clone(), weight, fee_asset, fee, call.clone()) + verify { + assert_last_event::(Event::CallSent { + sender: 0u32.into(), + destination, + call: call.to_vec(), + }.into()); + } + + transfer_assets { + let asset: <::Chains as ChainList>::ChainAssets = T::Chains::benchmark_mock().get_main_asset(); + let amount: u128 = u128::MAX.div(4u128); + let to: T::AccountId = whitelisted_caller(); + + }: _(INV4Origin::Multisig(MultisigInternalOrigin::new(0u32.into())), asset.clone(), amount, to.clone(), asset.clone(), amount) + verify { + assert_last_event::(Event::AssetsTransferred { + chain: asset.clone().get_chain(), + asset, + amount, + from: 0u32.into(), + to, + }.into()); + } + + bridge_assets { + let asset: <::Chains as ChainList>::ChainAssets = T::Chains::benchmark_mock().get_main_asset(); + let amount: u128 = u128::MAX.div(4u128); + let fee: u128 = amount.div(5u128); + let to: Option = Some(whitelisted_caller()); + + }: _(INV4Origin::Multisig(MultisigInternalOrigin::new(0u32.into())), asset.clone(), asset.clone().get_chain(), fee, amount, to) + verify { + assert_last_event::(Event::AssetsBridged { + origin_chain_asset: asset, + amount, + from: 0u32.into(), + to: whitelisted_caller(), + }.into()); + } +} diff --git a/pallets/pallet-rings/src/lib.rs b/pallets/pallet-rings/src/lib.rs new file mode 100644 index 00000000..44dec8ad --- /dev/null +++ b/pallets/pallet-rings/src/lib.rs @@ -0,0 +1,542 @@ +//! # Rings Pallet +//! +//! - [`Config`] +//! - [`Call`] +//! - [`Pallet`] +//! +//! ## Overview +//! This pallet provides a XCM abstraction layer for INV4 Cores, allowing them to manage assets easily across multiple chains. +//! +//! The module [`traits`] contains traits that provide an abstraction on top of XCM [`MultiLocation`] and has to be correctly implemented in the runtime. +//! +//! ## Dispatchable Functions +//! +//! - `set_maintenance_status` - Sets the maintenance status of a chain, requires the origin to be authorized as a `MaintenanceOrigin`. +//! - `send_call` - Allows a core to send a XCM call to a destination chain. +//! - `transfer_assets` - Allows a core to transfer fungible assets to another account in the destination chain. +//! - `bridge_assets` - Allows a core to bridge fungible assets to another chain having either a third party account or +//! the core account as beneficiary in the destination chain. + +#![cfg_attr(not(feature = "std"), no_std)] + +use frame_support::traits::Get; +use sp_std::convert::TryInto; + +#[cfg(feature = "runtime-benchmarks")] +mod benchmarking; + +#[cfg(test)] +mod tests; + +mod traits; +pub mod weights; + +pub use pallet::*; +pub use traits::{ChainAssetsList, ChainList}; +pub use weights::WeightInfo; + +#[frame_support::pallet] +pub mod pallet { + use super::*; + use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::OriginFor; + use pallet_inv4::origin::{ensure_multisig, INV4Origin}; + use sp_std::{vec, vec::Vec}; + use xcm::{ + v3::{prelude::*, MultiAsset, Weight, WildMultiAsset}, + DoubleEncoded, + }; + + #[pallet::pallet] + pub struct Pallet(_); + + #[pallet::config] + pub trait Config: frame_system::Config + pallet_inv4::Config + pallet_xcm::Config { + /// The overarching event type. + type RuntimeEvent: From> + IsType<::RuntimeEvent>; + + /// Higher level type providing an abstraction over a chain's asset and location. + type Chains: ChainList; + + /// Max length of an XCM call. + #[pallet::constant] + type MaxXCMCallLength: Get; + + /// Origin that can set maintenance status. + type MaintenanceOrigin: EnsureOrigin<::RuntimeOrigin>; + + /// Weight information for extrinsics in this pallet. + type WeightInfo: WeightInfo; + } + + /// Maps chain's and their maintenance status. + #[pallet::storage] + #[pallet::getter(fn is_under_maintenance)] + pub type ChainsUnderMaintenance = + StorageMap<_, Blake2_128Concat, MultiLocation, bool>; + + #[pallet::error] + pub enum Error { + /// Failed to send XCM. + SendingFailed, + /// Weight exceeds `MaxXCMCallLength`. + WeightTooHigh, + /// Failed to calculate XCM fee. + FailedToCalculateXcmFee, + /// Failed to reanchor asset. + FailedToReanchorAsset, + /// Failed to invert location. + FailedToInvertLocation, + /// Asset is not supported in the destination chain. + DifferentChains, + /// Chain is under maintenance. + ChainUnderMaintenance, + } + + #[pallet::event] + #[pallet::generate_deposit(fn deposit_event)] + pub enum Event { + /// A XCM call was sent. + CallSent { + sender: ::CoreId, + destination: ::Chains, + call: Vec, + }, + + /// Assets were transferred. + AssetsTransferred { + chain: <<::Chains as ChainList>::ChainAssets as ChainAssetsList>::Chains, + asset: <::Chains as ChainList>::ChainAssets, + amount: u128, + from: ::CoreId, + to: ::AccountId, + }, + + /// Assets were bridged. + AssetsBridged { + origin_chain_asset: <::Chains as ChainList>::ChainAssets, + amount: u128, + from: ::CoreId, + to: Option<::AccountId>, + }, + + /// A Chain's maintenance status changed. + ChainMaintenanceStatusChanged { + chain: ::Chains, + under_maintenance: bool, + } + } + + #[pallet::call] + impl Pallet + where + Result, ::RuntimeOrigin>: + From<::RuntimeOrigin>, + + ::CoreId: Into, + + [u8; 32]: From<::AccountId>, + ::AccountId: From<[u8; 32]>, + { + /// Set the maintenance status of a chain. + /// + /// The origin has to be `MaintenanceOrigin`. + /// + /// - `chain`: referred chain. + /// - `under_maintenance`: maintenance status. + #[pallet::call_index(0)] + #[pallet::weight((::WeightInfo::set_maintenance_status(), Pays::No))] + pub fn set_maintenance_status( + origin: OriginFor, + chain: ::Chains, + under_maintenance: bool, + ) -> DispatchResult { + T::MaintenanceOrigin::ensure_origin(origin)?; + + ChainsUnderMaintenance::::insert(chain.get_location(), under_maintenance); + + Self::deposit_event(Event::::ChainMaintenanceStatusChanged { + chain, + under_maintenance, + }); + + Ok(()) + } + + /// Send a XCM call to a destination chain. + /// + /// The origin has to be a core. + /// + /// - `destination`: destination chain. + /// - `weight`: weight of the call. + /// - `fee_asset`: asset used to pay the fee. + /// - `fee`: fee amount. + /// - `call`: XCM call. + #[pallet::call_index(1)] + #[pallet::weight( + ::WeightInfo::send_call(call.len() as u32) + )] + pub fn send_call( + origin: OriginFor, + destination: ::Chains, + weight: Weight, + fee_asset: <::Chains as ChainList>::ChainAssets, + fee: u128, + call: BoundedVec, + ) -> DispatchResult { + let core = ensure_multisig::>(origin)?; + let core_id = core.id.into(); + + let dest = destination.get_location(); + + ensure!( + !Self::is_under_maintenance(dest).unwrap_or(false), + Error::::ChainUnderMaintenance + ); + + let descend_interior = Junction::Plurality { + id: BodyId::Index(core_id), + part: BodyPart::Voice, + }; + + let fee_asset_location = fee_asset.get_asset_location(); + + let mut core_multilocation: MultiLocation = MultiLocation { + parents: 1, + interior: Junctions::X2( + Junction::Parachain(::ParaId::get()), + descend_interior, + ), + }; + + mutate_if_relay(&mut core_multilocation, &dest); + + let fee_multiasset = MultiAsset { + id: AssetId::Concrete(fee_asset_location), + fun: Fungibility::Fungible(fee), + }; + + let message = Xcm(vec![ + Instruction::WithdrawAsset(fee_multiasset.clone().into()), + Instruction::BuyExecution { + fees: fee_multiasset, + weight_limit: WeightLimit::Unlimited, + }, + Instruction::Transact { + origin_kind: OriginKind::SovereignAccount, + require_weight_at_most: weight, + call: as From>>::from(call.clone().to_vec()), + }, + Instruction::RefundSurplus, + Instruction::DepositAsset { + assets: MultiAssetFilter::Wild(WildMultiAsset::AllCounted(1)), + beneficiary: core_multilocation, + }, + ]); + + pallet_xcm::Pallet::::send_xcm(descend_interior, dest, message) + .map_err(|_| Error::::SendingFailed)?; + + Self::deposit_event(Event::CallSent { + sender: core.id, + destination, + call: call.to_vec(), + }); + + Ok(()) + } + + /// Transfer fungible assets to another account in the destination chain. + /// + /// Both asset and fee_asset have to be in the same chain. + /// + /// The origin has to be a core. + /// + /// - `asset`: asset to transfer. + /// - `amount`: amount to transfer. + /// - `to`: account receiving the asset. + /// - `fee_asset`: asset used to pay the fee. + /// - `fee`: fee amount. + #[pallet::call_index(2)] + #[pallet::weight(::WeightInfo::transfer_assets())] + pub fn transfer_assets( + origin: OriginFor, + asset: <::Chains as ChainList>::ChainAssets, + amount: u128, + to: ::AccountId, + fee_asset: <::Chains as ChainList>::ChainAssets, + fee: u128, + ) -> DispatchResult { + let core = ensure_multisig::>(origin)?; + let core_id = core.id.into(); + + let chain = asset.get_chain(); + let dest = chain.get_location(); + + ensure!( + !Self::is_under_maintenance(dest).unwrap_or(false), + Error::::ChainUnderMaintenance + ); + + ensure!(chain == fee_asset.get_chain(), Error::::DifferentChains); + + let descend_interior = Junction::Plurality { + id: BodyId::Index(core_id), + part: BodyPart::Voice, + }; + + let asset_location = asset.get_asset_location(); + + let multi_asset = MultiAsset { + id: AssetId::Concrete(asset_location), + fun: Fungibility::Fungible(amount), + }; + + let beneficiary: MultiLocation = MultiLocation { + parents: 0, + interior: Junctions::X1(Junction::AccountId32 { + network: None, + id: to.clone().into(), + }), + }; + + let mut core_multilocation: MultiLocation = MultiLocation { + parents: 1, + interior: Junctions::X2( + Junction::Parachain(::ParaId::get()), + descend_interior, + ), + }; + + mutate_if_relay(&mut core_multilocation, &dest); + + let fee_multiasset = MultiAsset { + id: AssetId::Concrete(fee_asset.get_asset_location()), + fun: Fungibility::Fungible(fee), + }; + + let message = Xcm(vec![ + // Pay execution fees + Instruction::WithdrawAsset(fee_multiasset.clone().into()), + Instruction::BuyExecution { + fees: fee_multiasset, + weight_limit: WeightLimit::Unlimited, + }, + // Actual transfer instruction + Instruction::TransferAsset { + assets: multi_asset.into(), + beneficiary, + }, + // Refund unused fees + Instruction::RefundSurplus, + Instruction::DepositAsset { + assets: MultiAssetFilter::Wild(WildMultiAsset::AllCounted(1)), + beneficiary: core_multilocation, + }, + ]); + + pallet_xcm::Pallet::::send_xcm(descend_interior, dest, message) + .map_err(|_| Error::::SendingFailed)?; + + Self::deposit_event(Event::AssetsTransferred { + chain, + asset, + amount, + from: core.id, + to, + }); + + Ok(()) + } + + /// Bridge fungible assets to another chain. + /// + /// The origin has to be a core. + /// + /// - `asset`: asset to bridge and the chain to bridge from. + /// - `destination`: destination chain. + /// - `fee`: fee amount. + /// - `amount`: amount to bridge. + /// - `to`: account receiving the asset, None defaults to core account. + #[pallet::call_index(3)] + #[pallet::weight(::WeightInfo::bridge_assets())] + pub fn bridge_assets( + origin: OriginFor, + asset: <::Chains as ChainList>::ChainAssets, + destination: <<::Chains as ChainList>::ChainAssets as ChainAssetsList>::Chains, + fee: u128, + amount: u128, + to: Option<::AccountId>, + ) -> DispatchResult { + let core = ensure_multisig::>(origin)?; + + let core_id = core.id.into(); + + let from_chain = asset.get_chain(); + let from_chain_location = from_chain.get_location(); + + let dest = destination.get_location(); + + ensure!( + !(Self::is_under_maintenance(from_chain_location).unwrap_or(false) + || Self::is_under_maintenance(dest).unwrap_or(false)), + Error::::ChainUnderMaintenance + ); + + let descend_interior = Junction::Plurality { + id: BodyId::Index(core_id), + part: BodyPart::Voice, + }; + + let asset_location = asset.get_asset_location(); + + let inverted_destination = dest + .reanchored(&from_chain_location, *from_chain_location.interior()) + .map(|inverted| { + if let (ml, Some(Junction::OnlyChild) | None) = inverted.split_last_interior() { + ml + } else { + inverted + } + }) + .map_err(|_| Error::::FailedToInvertLocation)?; + + let multiasset = MultiAsset { + id: AssetId::Concrete(asset_location), + fun: Fungibility::Fungible(amount), + }; + + let fee_multiasset = MultiAsset { + id: AssetId::Concrete(asset_location), + fun: Fungibility::Fungible(fee), + }; + + let reanchored_multiasset = multiasset + .clone() + .reanchored(&dest, *from_chain_location.interior()) + .map(|mut reanchored| { + if let AssetId::Concrete(ref mut m) = reanchored.id { + if let (ml, Some(Junction::OnlyChild) | None) = (*m).split_last_interior() { + *m = ml; + } + } + reanchored + }) + .map_err(|_| Error::::FailedToReanchorAsset)?; + + let mut core_multilocation: MultiLocation = MultiLocation { + parents: 1, + interior: Junctions::X2( + Junction::Parachain(::ParaId::get()), + descend_interior, + ), + }; + + let beneficiary: MultiLocation = match to.clone() { + Some(to_inner) => MultiLocation { + parents: 0, + interior: Junctions::X1(Junction::AccountId32 { + network: None, + id: to_inner.into(), + }), + }, + None => { + let mut dest_core_multilocation = core_multilocation; + + mutate_if_relay(&mut dest_core_multilocation, &dest); + + dest_core_multilocation + } + }; + + mutate_if_relay(&mut core_multilocation, &dest); + + // If the asset originates from the destination chain, we need to reverse the reserve-transfer. + let message = if asset_location.starts_with(&dest) { + Xcm(vec![ + WithdrawAsset(vec![fee_multiasset.clone(), multiasset.clone()].into()), + // Core pays for the execution fee incurred on sending the XCM. + Instruction::BuyExecution { + fees: fee_multiasset, + weight_limit: WeightLimit::Unlimited, + }, + InitiateReserveWithdraw { + assets: multiasset.into(), + reserve: inverted_destination, + xcm: Xcm(vec![ + // the beneficiary buys execution fee in the destination chain for the deposit. + Instruction::BuyExecution { + fees: reanchored_multiasset, + weight_limit: WeightLimit::Unlimited, + }, + Instruction::DepositAsset { + assets: AllCounted(1).into(), + beneficiary, + }, + Instruction::RefundSurplus, + // Refunds the beneficiary the surplus of the execution fees in the destination chain. + Instruction::DepositAsset { + assets: AllCounted(1).into(), + beneficiary, + }, + ]), + }, + Instruction::RefundSurplus, + // Refunds the core the surplus of the execution fees incurred on sending the XCM. + Instruction::DepositAsset { + assets: AllCounted(1).into(), + beneficiary: core_multilocation, + }, + ]) + } else { + Xcm(vec![ + // Pay execution fees + Instruction::WithdrawAsset(fee_multiasset.clone().into()), + Instruction::BuyExecution { + fees: fee_multiasset, + weight_limit: WeightLimit::Unlimited, + }, + // Actual reserve transfer instruction + Instruction::TransferReserveAsset { + assets: multiasset.into(), + dest: inverted_destination, + xcm: Xcm(vec![ + Instruction::BuyExecution { + fees: reanchored_multiasset, + weight_limit: WeightLimit::Unlimited, + }, + Instruction::DepositAsset { + assets: MultiAssetFilter::Wild(WildMultiAsset::AllCounted(1)), + beneficiary, + }, + ]), + }, + // Refund unused fees + Instruction::RefundSurplus, + Instruction::DepositAsset { + assets: MultiAssetFilter::Wild(WildMultiAsset::AllCounted(1)), + beneficiary: core_multilocation, + }, + ]) + }; + + pallet_xcm::Pallet::::send_xcm(descend_interior, from_chain_location, message) + .map_err(|_| Error::::SendingFailed)?; + + Self::deposit_event(Event::AssetsBridged { + origin_chain_asset: asset, + from: core.id, + amount, + to, + }); + + Ok(()) + } + } + + pub fn mutate_if_relay(origin: &mut MultiLocation, dest: &MultiLocation) { + if dest.contains_parents_only(1) { + origin.dec_parent(); + } + } +} diff --git a/pallets/pallet-rings/src/tests/mock.rs b/pallets/pallet-rings/src/tests/mock.rs new file mode 100644 index 00000000..b6ff8f31 --- /dev/null +++ b/pallets/pallet-rings/src/tests/mock.rs @@ -0,0 +1,634 @@ +use crate::{ + traits::{ChainAssetsList, ChainList}, + *, +}; +use codec::{Decode, Encode, MaxEncodedLen}; +use core::convert::TryFrom; +use frame_support::{ + derive_impl, parameter_types, + traits::{ + fungibles::Credit, ConstU128, ConstU32, ConstU64, Contains, Currency, EnsureOrigin, + EnsureOriginWithArg, Everything, Nothing, + }, + weights::ConstantMultiplier, +}; +use frame_system::EnsureRoot; +use orml_asset_registry::AssetMetadata; +use pallet_balances::AccountData; +use pallet_inv4::fee_handling::*; +use scale_info::TypeInfo; +use sp_core::H256; +use sp_runtime::{traits::IdentityLookup, AccountId32, BuildStorage}; +pub use sp_std::{cell::RefCell, fmt::Debug}; +use sp_std::{convert::TryInto, vec}; +use xcm::latest::prelude::*; +use xcm_builder::{ + AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, + AllowTopLevelPaidExecutionFrom, FixedRateOfFungible, FixedWeightBounds, + FungibleAdapter as XcmCurrencyAdapter, IsConcrete, SignedAccountId32AsNative, + SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, +}; +use xcm_executor::XcmExecutor; + +type Block = frame_system::mocking::MockBlock; +type Balance = u128; + +type AccountId = AccountId32; + +const MICROUNIT: Balance = 1_000_000; + +pub const EXISTENTIAL_DEPOSIT: Balance = 1_000_000_000; + +pub const ALICE: AccountId = AccountId32::new([ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +]); +pub const BOB: AccountId = AccountId32::new([ + 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +]); +pub const CHARLIE: AccountId = AccountId32::new([ + 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +]); + +frame_support::construct_runtime!( + pub enum Test + { + System: frame_system, + Balances: pallet_balances, + Tokens: orml_tokens, + CoreAssets: orml_tokens2, + AssetRegistry: orml_asset_registry, + INV4: pallet_inv4, + Rings: pallet, + XcmPallet: pallet_xcm, + } +); + +pub struct TestBaseCallFilter; +impl Contains for TestBaseCallFilter { + fn contains(_c: &RuntimeCall) -> bool { + true + } +} + +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +impl frame_system::Config for Test { + type RuntimeOrigin = RuntimeOrigin; + type RuntimeTask = RuntimeTask; + type Nonce = u64; + type Block = Block; + type RuntimeCall = RuntimeCall; + type Hash = H256; + type Hashing = ::sp_runtime::traits::BlakeTwo256; + type AccountId = AccountId; + type Lookup = IdentityLookup; + type RuntimeEvent = RuntimeEvent; + type BlockHashCount = ConstU64<250>; + type BlockWeights = (); + type BlockLength = (); + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type DbWeight = (); + type BaseCallFilter = TestBaseCallFilter; + type SystemWeightInfo = (); + type SS58Prefix = (); + type OnSetCode = (); + type MaxConsumers = ConstU32<16>; +} + +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig as pallet_balances::DefaultConfig)] +impl pallet_balances::Config for Test { + type MaxLocks = ConstU32<50>; + /// The type for recording an account's balance. + type Balance = Balance; + type RuntimeEvent = RuntimeEvent; + type DustRemoval = (); + type ExistentialDeposit = ConstU128; + type AccountStore = System; + type WeightInfo = (); + type MaxReserves = ConstU32<50>; + type ReserveIdentifier = [u8; 8]; + type MaxHolds = ConstU32<1>; + type MaxFreezes = (); +} + +thread_local! { + pub static SENT_XCM: RefCell)>> = RefCell::new(Vec::new()); +} + +/// Sender that never returns error, always sends +pub struct TestSendXcm; +impl SendXcm for TestSendXcm { + type Ticket = (MultiLocation, Xcm<()>); + fn validate( + dest: &mut Option, + msg: &mut Option>, + ) -> SendResult<(MultiLocation, Xcm<()>)> { + let pair = (dest.take().unwrap(), msg.take().unwrap()); + Ok((pair, MultiAssets::new())) + } + fn deliver(pair: (MultiLocation, Xcm<()>)) -> Result { + let hash = pair.1.using_encoded(sp_io::hashing::blake2_256); + SENT_XCM.with(|q| q.borrow_mut().push(pair)); + Ok(hash) + } +} + +parameter_types! { + pub const RelayLocation: MultiLocation = MultiLocation::parent(); + pub const AnyNetwork: Option = None; + pub Ancestry: MultiLocation = Here.into(); + pub UnitWeightCost: u64 = 1_000; +} + +pub type SovereignAccountOf = (AccountId32Aliases,); + +pub type LocalAssetTransactor = + XcmCurrencyAdapter, SovereignAccountOf, AccountId, ()>; + +type LocalOriginConverter = ( + SovereignSignedViaLocation, + SignedAccountId32AsNative, +); + +parameter_types! { + pub const BaseXcmWeight: u64 = 1_000; + pub CurrencyPerSecond: (xcm::latest::AssetId, u128, u128) = (Concrete(RelayLocation::get()), 1, 1); + pub TrustedAssets: (MultiAssetFilter, MultiLocation) = (All.into(), Here.into()); + pub const MaxInstructions: u32 = 100; + pub UniversalLocation: InteriorMultiLocation = Here; + pub const MaxAssetsIntoHolding: u32 = 64; +} + +pub type Barrier = ( + TakeWeightCredit, + AllowTopLevelPaidExecutionFrom, + AllowKnownQueryResponses, + AllowSubscriptionsFrom, +); + +pub struct XcmConfig; +impl xcm_executor::Config for XcmConfig { + type RuntimeCall = RuntimeCall; + type XcmSender = TestSendXcm; + type AssetTransactor = LocalAssetTransactor; + type OriginConverter = LocalOriginConverter; + type IsReserve = (); + type IsTeleporter = (); + type Barrier = Barrier; + type Weigher = FixedWeightBounds; + type Trader = FixedRateOfFungible; + type ResponseHandler = XcmPallet; + type AssetTrap = XcmPallet; + type AssetClaims = XcmPallet; + type SubscriptionService = XcmPallet; + type AssetLocker = (); + type AssetExchanger = (); + type FeeManager = (); + type MessageExporter = (); + type UniversalAliases = Nothing; + type UniversalLocation = UniversalLocation; + type CallDispatcher = RuntimeCall; + type SafeCallFilter = Everything; + type PalletInstancesInfo = AllPalletsWithSystem; + type MaxAssetsIntoHolding = MaxAssetsIntoHolding; + type Aliasers = (); +} + +pub type LocalOriginToLocation = SignedToAccountId32; + +impl pallet_xcm::Config for Test { + type RuntimeEvent = RuntimeEvent; + type SendXcmOrigin = xcm_builder::EnsureXcmOrigin; + type XcmRouter = TestSendXcm; + type ExecuteXcmOrigin = xcm_builder::EnsureXcmOrigin; + type XcmExecuteFilter = Everything; + type XcmExecutor = XcmExecutor; + type XcmTeleportFilter = Everything; + type XcmReserveTransferFilter = Everything; + type Weigher = FixedWeightBounds; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; + type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; + type UniversalLocation = UniversalLocation; + type MaxLockers = frame_support::traits::ConstU32<8>; + type MaxRemoteLockConsumers = frame_support::traits::ConstU32<0>; + type Currency = Balances; + type CurrencyMatcher = IsConcrete; + type AdminOrigin = EnsureRoot; + type TrustedLockers = (); + type SovereignAccountOf = AccountId32Aliases<(), AccountId32>; + type RemoteLockConsumerIdentifier = (); + type WeightInfo = pallet_xcm::TestWeightInfo; +} + +const UNIT: u128 = 1000000000000; + +orml_traits2::parameter_type_with_key! { + pub CoreExistentialDeposits: |_currency_id: ::CoreId| -> Balance { + 1u128 + }; +} + +pub struct CoreDustRemovalWhitelist; +impl Contains for CoreDustRemovalWhitelist { + fn contains(_: &AccountId) -> bool { + true + } +} + +pub struct DisallowIfFrozen; +impl orml_traits2::currency::OnTransfer::CoreId, Balance> + for DisallowIfFrozen +{ + fn on_transfer( + currency_id: ::CoreId, + _from: &AccountId, + _to: &AccountId, + _amount: Balance, + ) -> sp_runtime::DispatchResult { + if let Some(true) = INV4::is_asset_frozen(currency_id) { + Err(sp_runtime::DispatchError::Token( + sp_runtime::TokenError::Frozen, + )) + } else { + Ok(()) + } + } +} + +pub struct HandleNewMembers; +impl orml_traits2::Happened<(AccountId, ::CoreId)> + for HandleNewMembers +{ + fn happened((member, core_id): &(AccountId, ::CoreId)) { + INV4::add_member(core_id, member) + } +} + +pub struct HandleRemovedMembers; +impl orml_traits2::Happened<(AccountId, ::CoreId)> + for HandleRemovedMembers +{ + fn happened((member, core_id): &(AccountId, ::CoreId)) { + INV4::remove_member(core_id, member) + } +} + +pub struct INV4TokenHooks; +impl + orml_traits2::currency::MutationHooks::CoreId, Balance> + for INV4TokenHooks +{ + type PreTransfer = DisallowIfFrozen; + type OnDust = (); + type OnSlash = (); + type PreDeposit = (); + type PostDeposit = (); + type PostTransfer = (); + type OnNewTokenAccount = HandleNewMembers; + type OnKilledTokenAccount = HandleRemovedMembers; +} + +impl orml_tokens2::Config for Test { + type RuntimeEvent = RuntimeEvent; + type Balance = Balance; + type Amount = i128; + type CurrencyId = ::CoreId; + type WeightInfo = (); + type ExistentialDeposits = CoreExistentialDeposits; + type MaxLocks = ConstU32<0u32>; + type MaxReserves = ConstU32<0u32>; + type DustRemovalWhitelist = CoreDustRemovalWhitelist; + type ReserveIdentifier = [u8; 8]; + type CurrencyHooks = INV4TokenHooks; +} + +parameter_types! { + pub const MaxMetadata: u32 = 10000; + pub const MaxCallers: u32 = 10000; + pub const CoreSeedBalance: Balance = 1000000u128; + pub const CoreCreationFee: Balance = UNIT; + pub const StringLimit: u32 = 2125; + pub const RelayCoreCreationFee: Balance = UNIT; +} + +pub type AssetId = u32; + +pub const NATIVE_ASSET_ID: AssetId = 0; +pub const RELAY_ASSET_ID: AssetId = 1; + +parameter_types! { + pub const NativeAssetId: AssetId = NATIVE_ASSET_ID; + pub const RelayAssetId: AssetId = RELAY_ASSET_ID; + pub const ExistentialDeposit: u128 = 100000000000; + pub const MaxLocks: u32 = 1; + pub const MaxReserves: u32 = 1; + pub const TransactionByteFee: Balance = 10 * MICROUNIT; +} + +pub struct AssetAuthority; +impl EnsureOriginWithArg> for AssetAuthority { + type Success = (); + + fn try_origin( + origin: RuntimeOrigin, + _asset_id: &Option, + ) -> Result { + as EnsureOrigin>::try_origin(origin) + } +} + +impl orml_asset_registry::Config for Test { + type RuntimeEvent = RuntimeEvent; + type AuthorityOrigin = AssetAuthority; + type AssetId = AssetId; + type Balance = Balance; + type AssetProcessor = orml_asset_registry::SequentialId; + type CustomMetadata = (); + type WeightInfo = (); + type StringLimit = StringLimit; +} + +pub struct DustRemovalWhitelist; +impl Contains for DustRemovalWhitelist { + fn contains(_: &AccountId) -> bool { + true + } +} + +pub type Amount = i128; + +orml_traits::parameter_type_with_key! { + pub ExistentialDeposits: |currency_id: AssetId| -> Balance { + if currency_id == &NATIVE_ASSET_ID { + ExistentialDeposit::get() + } else { + orml_asset_registry::ExistentialDeposits::::get(currency_id) + } + }; +} + +impl orml_tokens::Config for Test { + type RuntimeEvent = RuntimeEvent; + type Balance = Balance; + type Amount = Amount; + type CurrencyId = AssetId; + type WeightInfo = (); + type ExistentialDeposits = ExistentialDeposits; + type MaxLocks = MaxLocks; + type DustRemovalWhitelist = DustRemovalWhitelist; + type MaxReserves = MaxReserves; + type ReserveIdentifier = [u8; 8]; + type CurrencyHooks = (); +} + +#[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo, Debug)] +pub struct FeeCharger; + +impl MultisigFeeHandler for FeeCharger { + type Pre = ( + // tip + Balance, + // who paid the fee + AccountId, + // imbalance resulting from withdrawing the fee + (), + // asset_id for the transaction payment + Option, + ); + + fn pre_dispatch( + fee_asset: &FeeAsset, + who: &AccountId, + _call: &RuntimeCall, + _info: &sp_runtime::traits::DispatchInfoOf, + _len: usize, + ) -> Result { + Ok(( + 0u128, + who.clone(), + (), + match fee_asset { + FeeAsset::Native => None, + FeeAsset::Relay => Some(1u32), + }, + )) + } + + fn post_dispatch( + _fee_asset: &FeeAsset, + _pre: Option, + _info: &sp_runtime::traits::DispatchInfoOf, + _post_info: &sp_runtime::traits::PostDispatchInfoOf, + _len: usize, + _result: &sp_runtime::DispatchResult, + ) -> Result<(), frame_support::unsigned::TransactionValidityError> { + Ok(()) + } + + fn handle_creation_fee( + _imbalance: FeeAssetNegativeImbalance< + >::NegativeImbalance, + Credit, + >, + ) { + } +} + +impl pallet_inv4::Config for Test { + type MaxMetadata = MaxMetadata; + type CoreId = u32; + type RuntimeEvent = RuntimeEvent; + type Currency = Balances; + type RuntimeCall = RuntimeCall; + type MaxCallers = MaxCallers; + type CoreSeedBalance = CoreSeedBalance; + type AssetsProvider = CoreAssets; + type RuntimeOrigin = RuntimeOrigin; + type CoreCreationFee = CoreCreationFee; + type FeeCharger = FeeCharger; + type WeightInfo = pallet_inv4::weights::SubstrateWeight; + + type Tokens = Tokens; + type RelayAssetId = RelayAssetId; + type RelayCoreCreationFee = RelayCoreCreationFee; + type MaxCallSize = ConstU32<51200>; + + type ParaId = ConstU32<2125>; + type LengthToFee = ConstantMultiplier; +} + +parameter_types! { + pub ParaId: u32 = 2125u32; + pub MaxWeightedLength: u32 = 100_000; + pub INV4PalletIndex: u8 = 2u8; +} + +impl pallet::Config for Test { + type RuntimeEvent = RuntimeEvent; + type Chains = Chains; + type WeightInfo = weights::SubstrateWeight; + type MaxXCMCallLength = ConstU32<100_000>; + type MaintenanceOrigin = EnsureRoot; +} + +#[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] +pub enum Chains { + Relay, + ChainA, + ChainB, +} + +#[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] +pub enum Assets { + AssetA, + AssetB, +} + +#[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] +pub enum ChainAssets { + Relay(Assets), + ChainA(Assets), + ChainB(Assets), +} + +impl ChainAssetsList for ChainAssets { + type Chains = Chains; + + fn get_chain(&self) -> Self::Chains { + match self { + Self::ChainA(_) => Chains::ChainA, + Self::ChainB(_) => Chains::ChainB, + Self::Relay(_) => Chains::Relay, + } + } + + fn get_asset_location(&self) -> MultiLocation { + match { + match self { + Self::ChainA(asset) => asset, + Self::ChainB(asset) => asset, + Self::Relay(asset) => asset, + } + } { + Assets::AssetA => MultiLocation { + parents: 1, + interior: Junctions::X1(Junction::Parachain(1234)), + }, + + Assets::AssetB => MultiLocation { + parents: 1, + interior: Junctions::X1(Junction::Parachain(2345)), + }, + } + } +} + +impl ChainList for Chains { + type Balance = Balance; + type ChainAssets = ChainAssets; + + fn get_location(&self) -> MultiLocation { + match self { + Self::ChainA => MultiLocation { + parents: 1, + interior: Junctions::X1(Junction::Parachain(1234)), + }, + Self::ChainB => MultiLocation { + parents: 1, + interior: Junctions::X1(Junction::Parachain(2345)), + }, + Self::Relay => MultiLocation { + parents: 1, + interior: Junctions::Here, + }, + } + } + + fn get_main_asset(&self) -> Self::ChainAssets { + match self { + Self::ChainA => ChainAssets::ChainA(Assets::AssetA), + Self::ChainB => ChainAssets::ChainB(Assets::AssetB), + Self::Relay => ChainAssets::Relay(Assets::AssetA), + } + } +} + +pub struct ExtBuilder; + +impl Default for ExtBuilder { + fn default() -> Self { + ExtBuilder + } +} + +pub const INITIAL_BALANCE: Balance = 100000000000000000; + +impl ExtBuilder { + pub fn build(self) -> sp_io::TestExternalities { + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); + + pallet_balances::GenesisConfig:: { + balances: vec![ + (ALICE, INITIAL_BALANCE), + (BOB, INITIAL_BALANCE), + (CHARLIE, INITIAL_BALANCE), + ], + } + .assimilate_storage(&mut t) + .unwrap(); + + orml_asset_registry::GenesisConfig:: { + assets: vec![ + ( + 0u32, + AssetMetadata { + decimals: 12, + name: sp_core::bounded_vec::BoundedVec::::new(), + symbol: sp_core::bounded_vec::BoundedVec::::new(), + existential_deposit: ExistentialDeposit::get(), + location: None, + additional: (), + } + .encode(), + ), + ( + 1u32, + AssetMetadata { + decimals: 12, + name: sp_core::bounded_vec::BoundedVec::::new(), + symbol: sp_core::bounded_vec::BoundedVec::::new(), + existential_deposit: ExistentialDeposit::get(), + location: None, + additional: (), + } + .encode(), + ), + ], + last_asset_id: 1u32, + } + .assimilate_storage(&mut t) + .unwrap(); + + orml_tokens::GenesisConfig:: { + balances: vec![ + (ALICE, RELAY_ASSET_ID, INITIAL_BALANCE), + (BOB, RELAY_ASSET_ID, INITIAL_BALANCE), + (CHARLIE, RELAY_ASSET_ID, INITIAL_BALANCE), + ], + } + .assimilate_storage(&mut t) + .unwrap(); + + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(0)); + + ext + } +} diff --git a/pallets/pallet-rings/src/tests/mod.rs b/pallets/pallet-rings/src/tests/mod.rs new file mode 100644 index 00000000..3ebcfdd0 --- /dev/null +++ b/pallets/pallet-rings/src/tests/mod.rs @@ -0,0 +1,290 @@ +mod mock; + +use crate::{traits::*, Error}; +use frame_support::{assert_err, assert_ok, error::BadOrigin}; +use frame_system::RawOrigin; +use mock::*; +use pallet_inv4::{origin::MultisigInternalOrigin, Origin}; +use sp_std::vec; +use xcm::latest::{BodyId, BodyPart, Junction, Junctions, MultiLocation, Weight}; + +#[test] +fn set_maintenance_status() { + ExtBuilder::default().build().execute_with(|| { + let chain_a = Chains::ChainA; + + assert_eq!( + Rings::is_under_maintenance(chain_a.clone().get_location()), + None + ); + + assert_ok!(Rings::set_maintenance_status( + RawOrigin::Root.into(), + chain_a.clone(), + true + )); + + assert_eq!( + Rings::is_under_maintenance(chain_a.clone().get_location()), + Some(true) + ); + + assert_ok!(Rings::set_maintenance_status( + RawOrigin::Root.into(), + chain_a.clone(), + false + )); + + assert_eq!( + Rings::is_under_maintenance(chain_a.clone().get_location()), + Some(false) + ); + + assert_err!( + Rings::set_maintenance_status(RawOrigin::Signed(ALICE).into(), chain_a, true), + BadOrigin + ); + }) +} + +#[test] +fn send_call_works() { + ExtBuilder::default().build().execute_with(|| { + let chain_a = Chains::ChainA; + let fee_asset = Chains::ChainA.get_main_asset(); + + assert_ok!(Rings::send_call( + Origin::Multisig(MultisigInternalOrigin::new(0u32)).into(), + chain_a.clone(), + Weight::from_parts(5000000000, 0), + fee_asset, + 10000000000000u128, + vec![1, 2, 3].try_into().unwrap() + )); + }) +} + +#[test] +fn send_call_fails() { + ExtBuilder::default().build().execute_with(|| { + let chain_a = Chains::ChainA; + let fee_asset = Chains::ChainA.get_main_asset(); + + // Wrong origin. + assert_err!( + Rings::send_call( + RawOrigin::Signed(ALICE).into(), + chain_a.clone(), + Weight::from_parts(5000000000, 0), + fee_asset.clone(), + 10000000000000u128, + vec![1, 2, 3].try_into().unwrap() + ), + BadOrigin + ); + + // Chain under maintenance. + Rings::set_maintenance_status(RawOrigin::Root.into(), chain_a.clone(), true).unwrap(); + assert_err!( + Rings::send_call( + Origin::Multisig(MultisigInternalOrigin::new(0u32)).into(), + chain_a, + Weight::from_parts(5000000000, 0), + fee_asset, + 10000000000000u128, + vec![1, 2, 3].try_into().unwrap() + ), + Error::::ChainUnderMaintenance + ); + }) +} + +#[test] +fn transfer_assets_works() { + ExtBuilder::default().build().execute_with(|| { + let asset = Chains::ChainA.get_main_asset(); + + assert_ok!(Rings::transfer_assets( + Origin::Multisig(MultisigInternalOrigin::new(0u32)).into(), + asset.clone(), + 100000000000000u128, + ALICE, + asset.clone(), + 10000000000000u128, + )); + }) +} + +#[test] +fn transfer_assets_fails() { + ExtBuilder::default().build().execute_with(|| { + let asset = Chains::ChainA.get_main_asset(); + let other_asset = Chains::ChainB.get_main_asset(); + + // Wrong origin. + assert_err!( + Rings::transfer_assets( + RawOrigin::Signed(ALICE).into(), + asset.clone(), + 100000000000000u128, + ALICE, + asset.clone(), + 10000000000000u128, + ), + BadOrigin + ); + + // Fee asset is from a different chain. + assert_err!( + Rings::transfer_assets( + Origin::Multisig(MultisigInternalOrigin::new(0u32)).into(), + asset.clone(), + 100000000000000u128, + ALICE, + other_asset.clone(), + 10000000000000u128, + ), + Error::::DifferentChains + ); + + // Chain under maintenance. + Rings::set_maintenance_status(RawOrigin::Root.into(), asset.get_chain().clone(), true) + .unwrap(); + assert_err!( + Rings::transfer_assets( + Origin::Multisig(MultisigInternalOrigin::new(0u32)).into(), + asset.clone(), + 100000000000000u128, + ALICE, + asset.clone(), + 10000000000000u128, + ), + Error::::ChainUnderMaintenance + ); + }) +} + +#[test] +fn bridge_assets_works() { + ExtBuilder::default().build().execute_with(|| { + let asset = Chains::ChainA.get_main_asset(); + let destination = Chains::ChainB; + + assert_ok!(Rings::bridge_assets( + Origin::Multisig(MultisigInternalOrigin::new(0u32)).into(), + asset.clone(), + destination.clone(), + 10000000000000u128, + 100000000000000u128, + Some(ALICE), + )); + + assert_ok!(Rings::bridge_assets( + Origin::Multisig(MultisigInternalOrigin::new(0u32)).into(), + asset.clone(), + destination.clone(), + 10000000000000u128, + 100000000000000u128, + None, + )); + }) +} + +#[test] +fn bridge_assets_fails() { + ExtBuilder::default().build().execute_with(|| { + let asset = Chains::ChainA.get_main_asset(); + let destination = Chains::ChainB; + + // Wrong origin. + assert_err!( + Rings::bridge_assets( + RawOrigin::Signed(ALICE).into(), + asset.clone(), + destination.clone(), + 10000000000000u128, + 100000000000000u128, + None, + ), + BadOrigin + ); + + // Chain under maintenance. + Rings::set_maintenance_status(RawOrigin::Root.into(), asset.get_chain().clone(), true) + .unwrap(); + assert_err!( + Rings::bridge_assets( + Origin::Multisig(MultisigInternalOrigin::new(0u32)).into(), + asset.clone(), + destination.clone(), + 10000000000000u128, + 100000000000000u128, + None, + ), + Error::::ChainUnderMaintenance + ); + Rings::set_maintenance_status(RawOrigin::Root.into(), asset.get_chain().clone(), false) + .unwrap(); + Rings::set_maintenance_status(RawOrigin::Root.into(), destination.clone(), true).unwrap(); + assert_err!( + Rings::bridge_assets( + Origin::Multisig(MultisigInternalOrigin::new(0u32)).into(), + asset.clone(), + destination.clone(), + 10000000000000u128, + 100000000000000u128, + None, + ), + Error::::ChainUnderMaintenance + ); + }) +} + +#[test] +fn mutate_location_if_dest_is_relay() { + let relay_dest = Chains::Relay.get_location(); + let para_dest = Chains::ChainA.get_location(); + + let mut core_multilocation = MultiLocation { + parents: 1, + interior: Junctions::X2( + Junction::Parachain(2125), + Junction::Plurality { + id: BodyId::Index(0), + part: BodyPart::Voice, + }, + ), + }; + + crate::pallet::mutate_if_relay(&mut core_multilocation, ¶_dest); + + assert_eq!( + core_multilocation, + MultiLocation { + parents: 1, + interior: Junctions::X2( + Junction::Parachain(2125), + Junction::Plurality { + id: BodyId::Index(0), + part: BodyPart::Voice, + } + ) + } + ); + + crate::pallet::mutate_if_relay(&mut core_multilocation, &relay_dest); + + assert_eq!( + core_multilocation, + MultiLocation { + parents: 0, + interior: Junctions::X2( + Junction::Parachain(2125), + Junction::Plurality { + id: BodyId::Index(0), + part: BodyPart::Voice, + } + ) + } + ); +} diff --git a/pallets/pallet-rings/src/traits.rs b/pallets/pallet-rings/src/traits.rs new file mode 100644 index 00000000..1868a9ce --- /dev/null +++ b/pallets/pallet-rings/src/traits.rs @@ -0,0 +1,51 @@ +//! Provides supporting traits for the rings pallet. +//! +//! ## Overview +//! +//! This module contains the traits responsible for creating an abstraction layer on top of XCM [`MultiLocation`] and allows +//! easier handling of cross-chain transactions through XCM. +//! +//! The traits contained in this pallet require an appropriate runtime implementation. +//! +//! ## Traits overview: +//! +//! - [`ChainList`] - Trait used to opaquely refer to a chain, provides an interface to get the chain `MultiLocation` or the chain's main asset as `ChainAssetsList`. +//! - [`ChainAssetsList`] - Trait used to opaquely refer to a chain's asset, provides an interface to get the chain asset `MultiLocation` or the chain as `ChainList`. + +use codec::MaxEncodedLen; +use frame_support::Parameter; +use xcm::opaque::v3::MultiLocation; + +/// A chain [`MultiLocation`] abstraction trait. +/// +/// It provides an interface for easily getting a chain's [`MultiLocation`] and to go back and forth between the chain and its assets. +/// +/// This should be implemented properly in the runtime. +pub trait ChainList: Parameter + MaxEncodedLen { + type Balance: Into; + type ChainAssets: ChainAssetsList; + + /// Returns the chain's [`MultiLocation`]. + fn get_location(&self) -> MultiLocation; + + /// Returns the chain's main asset as `ChainAssetsList`. + fn get_main_asset(&self) -> Self::ChainAssets; + + #[cfg(feature = "runtime-benchmarks")] + fn benchmark_mock() -> Self; +} + +/// A chain asset [`MultiLocation`] abstraction trait. +/// +/// It provides an interface for easily getting a chain's asset [`MultiLocation`] and to go back and forth between the asset and its parent chain. +/// +/// This should be implemented properly in the runtime. +pub trait ChainAssetsList: Parameter + MaxEncodedLen { + type Chains: ChainList; + + /// Returns the asset's parent chain. + fn get_chain(&self) -> Self::Chains; + + /// Returns the asset's [`MultiLocation`]. + fn get_asset_location(&self) -> MultiLocation; +} diff --git a/pallets/pallet-rings/src/weights.rs b/pallets/pallet-rings/src/weights.rs new file mode 100644 index 00000000..747e8534 --- /dev/null +++ b/pallets/pallet-rings/src/weights.rs @@ -0,0 +1,213 @@ + +//! Autogenerated weights for `pallet_rings` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-08-04, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `Gabriels-MacBook-Pro-3.local`, CPU: `` +//! EXECUTION: `Some(Wasm)`, WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` + +// Executed Command: + // ./target/release/invarch-collator + // benchmark + // pallet + // --chain=dev + // --execution=wasm + // --wasm-execution=compiled + // --pallet=pallet_rings + // --extrinsic=* + // --steps + // 50 + // --repeat + // 20 + // --output=../InvArch-Frames/pallet-rings/src/weights.rs + // --template=weights-template.hbs + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use core::marker::PhantomData; + +/// Weight functions needed for `pallet_rings`. +pub trait WeightInfo { + fn set_maintenance_status() -> Weight; + fn send_call(c: u32, ) -> Weight; + fn transfer_assets() -> Weight; + fn bridge_assets() -> Weight; + } + + /// Weights for `pallet_rings` using the Substrate node and recommended hardware. + pub struct SubstrateWeight(PhantomData); + impl WeightInfo for SubstrateWeight { + /// Storage: Rings ChainsUnderMaintenance (r:0 w:1) + /// Proof: Rings ChainsUnderMaintenance (max_values: None, max_size: Some(619), added: 3094, mode: MaxEncodedLen) + fn set_maintenance_status() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 8_000_000 picoseconds. + Weight::from_parts(8_000_000, 0) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + /// Storage: Rings ChainsUnderMaintenance (r:1 w:0) + /// Proof: Rings ChainsUnderMaintenance (max_values: None, max_size: Some(619), added: 3094, mode: MaxEncodedLen) + /// Storage: ParachainInfo ParachainId (r:1 w:0) + /// Proof: ParachainInfo ParachainId (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) + /// Storage: PolkadotXcm SupportedVersion (r:1 w:0) + /// Proof Skipped: PolkadotXcm SupportedVersion (max_values: None, max_size: None, mode: Measured) + /// Storage: PolkadotXcm VersionDiscoveryQueue (r:1 w:1) + /// Proof Skipped: PolkadotXcm VersionDiscoveryQueue (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: PolkadotXcm SafeXcmVersion (r:1 w:0) + /// Proof Skipped: PolkadotXcm SafeXcmVersion (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: ParachainSystem HostConfiguration (r:1 w:0) + /// Proof Skipped: ParachainSystem HostConfiguration (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: ParachainSystem PendingUpwardMessages (r:1 w:1) + /// Proof Skipped: ParachainSystem PendingUpwardMessages (max_values: Some(1), max_size: None, mode: Measured) + /// The range of component `c` is `[0, 100000]`. + fn send_call(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `253` + // Estimated: `4084` + // Minimum execution time: 36_000_000 picoseconds. + Weight::from_parts(37_257_805, 4084) + // Standard Error: 1 + .saturating_add(Weight::from_parts(2_102, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(7_u64)) + .saturating_add(T::DbWeight::get().writes(2_u64)) + } + /// Storage: Rings ChainsUnderMaintenance (r:1 w:0) + /// Proof: Rings ChainsUnderMaintenance (max_values: None, max_size: Some(619), added: 3094, mode: MaxEncodedLen) + /// Storage: ParachainInfo ParachainId (r:1 w:0) + /// Proof: ParachainInfo ParachainId (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) + /// Storage: PolkadotXcm SupportedVersion (r:1 w:0) + /// Proof Skipped: PolkadotXcm SupportedVersion (max_values: None, max_size: None, mode: Measured) + /// Storage: PolkadotXcm VersionDiscoveryQueue (r:1 w:1) + /// Proof Skipped: PolkadotXcm VersionDiscoveryQueue (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: PolkadotXcm SafeXcmVersion (r:1 w:0) + /// Proof Skipped: PolkadotXcm SafeXcmVersion (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: ParachainSystem HostConfiguration (r:1 w:0) + /// Proof Skipped: ParachainSystem HostConfiguration (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: ParachainSystem PendingUpwardMessages (r:1 w:1) + /// Proof Skipped: ParachainSystem PendingUpwardMessages (max_values: Some(1), max_size: None, mode: Measured) + fn transfer_assets() -> Weight { + // Proof Size summary in bytes: + // Measured: `253` + // Estimated: `4084` + // Minimum execution time: 36_000_000 picoseconds. + Weight::from_parts(37_000_000, 4084) + .saturating_add(T::DbWeight::get().reads(7_u64)) + .saturating_add(T::DbWeight::get().writes(2_u64)) + } + /// Storage: Rings ChainsUnderMaintenance (r:1 w:0) + /// Proof: Rings ChainsUnderMaintenance (max_values: None, max_size: Some(619), added: 3094, mode: MaxEncodedLen) + /// Storage: ParachainInfo ParachainId (r:1 w:0) + /// Proof: ParachainInfo ParachainId (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) + /// Storage: PolkadotXcm SupportedVersion (r:1 w:0) + /// Proof Skipped: PolkadotXcm SupportedVersion (max_values: None, max_size: None, mode: Measured) + /// Storage: PolkadotXcm VersionDiscoveryQueue (r:1 w:1) + /// Proof Skipped: PolkadotXcm VersionDiscoveryQueue (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: PolkadotXcm SafeXcmVersion (r:1 w:0) + /// Proof Skipped: PolkadotXcm SafeXcmVersion (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: ParachainSystem HostConfiguration (r:1 w:0) + /// Proof Skipped: ParachainSystem HostConfiguration (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: ParachainSystem PendingUpwardMessages (r:1 w:1) + /// Proof Skipped: ParachainSystem PendingUpwardMessages (max_values: Some(1), max_size: None, mode: Measured) + fn bridge_assets() -> Weight { + // Proof Size summary in bytes: + // Measured: `253` + // Estimated: `4084` + // Minimum execution time: 43_000_000 picoseconds. + Weight::from_parts(44_000_000, 4084) + .saturating_add(T::DbWeight::get().reads(7_u64)) + .saturating_add(T::DbWeight::get().writes(2_u64)) + } + } + + // For backwards compatibility and tests. + impl WeightInfo for () { + /// Storage: Rings ChainsUnderMaintenance (r:0 w:1) + /// Proof: Rings ChainsUnderMaintenance (max_values: None, max_size: Some(619), added: 3094, mode: MaxEncodedLen) + fn set_maintenance_status() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 8_000_000 picoseconds. + Weight::from_parts(8_000_000, 0) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + /// Storage: Rings ChainsUnderMaintenance (r:1 w:0) + /// Proof: Rings ChainsUnderMaintenance (max_values: None, max_size: Some(619), added: 3094, mode: MaxEncodedLen) + /// Storage: ParachainInfo ParachainId (r:1 w:0) + /// Proof: ParachainInfo ParachainId (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) + /// Storage: PolkadotXcm SupportedVersion (r:1 w:0) + /// Proof Skipped: PolkadotXcm SupportedVersion (max_values: None, max_size: None, mode: Measured) + /// Storage: PolkadotXcm VersionDiscoveryQueue (r:1 w:1) + /// Proof Skipped: PolkadotXcm VersionDiscoveryQueue (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: PolkadotXcm SafeXcmVersion (r:1 w:0) + /// Proof Skipped: PolkadotXcm SafeXcmVersion (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: ParachainSystem HostConfiguration (r:1 w:0) + /// Proof Skipped: ParachainSystem HostConfiguration (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: ParachainSystem PendingUpwardMessages (r:1 w:1) + /// Proof Skipped: ParachainSystem PendingUpwardMessages (max_values: Some(1), max_size: None, mode: Measured) + /// The range of component `c` is `[0, 100000]`. + fn send_call(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `253` + // Estimated: `4084` + // Minimum execution time: 36_000_000 picoseconds. + Weight::from_parts(37_257_805, 4084) + // Standard Error: 1 + .saturating_add(Weight::from_parts(2_102, 0).saturating_mul(c.into())) + .saturating_add(RocksDbWeight::get().reads(7_u64)) + .saturating_add(RocksDbWeight::get().writes(2_u64)) + } + /// Storage: Rings ChainsUnderMaintenance (r:1 w:0) + /// Proof: Rings ChainsUnderMaintenance (max_values: None, max_size: Some(619), added: 3094, mode: MaxEncodedLen) + /// Storage: ParachainInfo ParachainId (r:1 w:0) + /// Proof: ParachainInfo ParachainId (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) + /// Storage: PolkadotXcm SupportedVersion (r:1 w:0) + /// Proof Skipped: PolkadotXcm SupportedVersion (max_values: None, max_size: None, mode: Measured) + /// Storage: PolkadotXcm VersionDiscoveryQueue (r:1 w:1) + /// Proof Skipped: PolkadotXcm VersionDiscoveryQueue (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: PolkadotXcm SafeXcmVersion (r:1 w:0) + /// Proof Skipped: PolkadotXcm SafeXcmVersion (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: ParachainSystem HostConfiguration (r:1 w:0) + /// Proof Skipped: ParachainSystem HostConfiguration (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: ParachainSystem PendingUpwardMessages (r:1 w:1) + /// Proof Skipped: ParachainSystem PendingUpwardMessages (max_values: Some(1), max_size: None, mode: Measured) + fn transfer_assets() -> Weight { + // Proof Size summary in bytes: + // Measured: `253` + // Estimated: `4084` + // Minimum execution time: 36_000_000 picoseconds. + Weight::from_parts(37_000_000, 4084) + .saturating_add(RocksDbWeight::get().reads(7_u64)) + .saturating_add(RocksDbWeight::get().writes(2_u64)) + } + /// Storage: Rings ChainsUnderMaintenance (r:1 w:0) + /// Proof: Rings ChainsUnderMaintenance (max_values: None, max_size: Some(619), added: 3094, mode: MaxEncodedLen) + /// Storage: ParachainInfo ParachainId (r:1 w:0) + /// Proof: ParachainInfo ParachainId (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) + /// Storage: PolkadotXcm SupportedVersion (r:1 w:0) + /// Proof Skipped: PolkadotXcm SupportedVersion (max_values: None, max_size: None, mode: Measured) + /// Storage: PolkadotXcm VersionDiscoveryQueue (r:1 w:1) + /// Proof Skipped: PolkadotXcm VersionDiscoveryQueue (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: PolkadotXcm SafeXcmVersion (r:1 w:0) + /// Proof Skipped: PolkadotXcm SafeXcmVersion (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: ParachainSystem HostConfiguration (r:1 w:0) + /// Proof Skipped: ParachainSystem HostConfiguration (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: ParachainSystem PendingUpwardMessages (r:1 w:1) + /// Proof Skipped: ParachainSystem PendingUpwardMessages (max_values: Some(1), max_size: None, mode: Measured) + fn bridge_assets() -> Weight { + // Proof Size summary in bytes: + // Measured: `253` + // Estimated: `4084` + // Minimum execution time: 43_000_000 picoseconds. + Weight::from_parts(44_000_000, 4084) + .saturating_add(RocksDbWeight::get().reads(7_u64)) + .saturating_add(RocksDbWeight::get().writes(2_u64)) + } + } diff --git a/pallets/primitives/Cargo.toml b/pallets/primitives/Cargo.toml new file mode 100644 index 00000000..6c190c42 --- /dev/null +++ b/pallets/primitives/Cargo.toml @@ -0,0 +1,35 @@ +[package] +name = 'invarch-primitives' +version = '0.1.0-dev' +authors = ['InvArchitects '] +description = 'InvArch primitives for InvArchh Pallet Library' +homepage = 'https://invarch.network' +edition = '2021' +license = 'GPLv3' +repository = 'https://github.com/InvArch/InvArch-Pallet-Library/ipt' + + +[dependencies] +serde = { workspace = true, optional = true } +codec = { workspace = true, default-features = false } +scale-info = { workspace = true, default-features = false } + +frame-system = { workspace = true, default-features = false } +sp-core = { workspace = true, default-features = false } +sp-runtime = { workspace = true, default-features = false } +sp-std = { workspace = true, default-features = false } +sp-io = { workspace = true, default-features = false } + + +[features] +default = ["std"] +std = [ + "serde", + "codec/std", + "sp-core/std", + "frame-system/std", + "sp-std/std", + "scale-info/std", + "sp-io/std", + "sp-runtime/std", +] diff --git a/pallets/primitives/src/lib.rs b/pallets/primitives/src/lib.rs new file mode 100644 index 00000000..220fc087 --- /dev/null +++ b/pallets/primitives/src/lib.rs @@ -0,0 +1,81 @@ +#![cfg_attr(not(feature = "std"), no_std)] + +use codec::{Decode, Encode, MaxEncodedLen}; +use scale_info::TypeInfo; +use sp_runtime::{Perbill, Percent}; + +/// Voting weight of an IPT +#[derive(Encode, Decode, Clone, Copy, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] +pub enum OneOrPercent { + /// Represents 100% + One, + /// Represents 0% - 99% inclusive + ZeroPoint(Percent), +} + +/// Entity is parent or child? +#[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] +pub enum Parentage { + /// Parent IP (Account Id of itself) + Parent(AccountId), + /// Child IP (Id of the immediate parent, Account Id of the topmost parent) + Child(IpsId, AccountId), +} + +/// Normal or replica IPS +#[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] +pub enum IpsType { + /// Normal IPS (original) + Normal, + /// IP Replica (Id of the original IP) + Replica(IpsId), +} + +#[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] +pub enum BoolOrWasm { + Bool(bool), + Wasm(Wasm), +} + +/// Core IP Set struct +#[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] +pub struct CoreInfo { + /// IPS parentage + pub account: AccountId, + /// IPS metadata + pub metadata: CoreMetadataOf, + + /// Aye vote percentage required to execute a multisig call. + /// + /// Invariant: If set to `One`, 100% of tokens that have non-zero voting weight must approve + pub minimum_support: Perbill, + pub required_approval: Perbill, + + pub frozen_tokens: bool, +} + +/// IPF Info +#[derive(Encode, Decode, Clone, Eq, PartialEq, MaxEncodedLen, Debug, TypeInfo)] +pub struct IpfInfo { + /// IPF owner + pub owner: AccountId, + /// Original IPF author + pub author: AccountId, + /// IPF metadata + pub metadata: IpfMetadataOf, + /// IPF data + pub data: Data, +} + +// This is a struct in preparation for having more fields in the future. +#[derive(Debug, Clone, Encode, Decode, Eq, PartialEq, MaxEncodedLen, TypeInfo)] +pub struct SubTokenInfo { + pub id: IptId, + pub metadata: SubAssetMetadata, +} + +#[derive(Debug, Clone, Encode, Decode, Eq, PartialEq, MaxEncodedLen, TypeInfo)] +pub struct CallInfo { + pub pallet: Data, + pub function: Data, +} diff --git a/pallets/rust-toolchain.toml b/pallets/rust-toolchain.toml new file mode 100644 index 00000000..fb7b5e92 --- /dev/null +++ b/pallets/rust-toolchain.toml @@ -0,0 +1,4 @@ +[toolchain] +channel = "nightly-2024-07-15" +targets = ["wasm32-unknown-unknown"] +components = [ "rustfmt", "rustc", "rust-std", "cargo", "clippy", "llvm-tools-preview"] diff --git a/pallets/rustfmt.toml b/pallets/rustfmt.toml new file mode 100644 index 00000000..c3c8c375 --- /dev/null +++ b/pallets/rustfmt.toml @@ -0,0 +1 @@ +imports_granularity = "Crate" diff --git a/tinkernet/Cargo.lock b/tinkernet/Cargo.lock index 4fcceabb..36b270c5 100644 --- a/tinkernet/Cargo.lock +++ b/tinkernet/Cargo.lock @@ -4302,7 +4302,6 @@ dependencies = [ [[package]] name = "invarch-primitives" version = "0.1.0-dev" -source = "git+https://github.com/InvArch/InvArch-Frames?branch=francisco-weight_fixes#c7bd7bb82384fcd4cd75d4030dfc0c637dd6f58a" dependencies = [ "frame-system", "parity-scale-codec", @@ -6543,7 +6542,6 @@ dependencies = [ [[package]] name = "pallet-checked-inflation" version = "0.1.0-dev" -source = "git+https://github.com/InvArch/InvArch-Frames?branch=francisco-weight_fixes#c7bd7bb82384fcd4cd75d4030dfc0c637dd6f58a" dependencies = [ "frame-benchmarking", "frame-support", @@ -6806,7 +6804,6 @@ dependencies = [ [[package]] name = "pallet-inv4" version = "0.1.0-dev" -source = "git+https://github.com/InvArch/InvArch-Frames?branch=francisco-weight_fixes#c7bd7bb82384fcd4cd75d4030dfc0c637dd6f58a" dependencies = [ "frame-benchmarking", "frame-support", @@ -6984,7 +6981,6 @@ dependencies = [ [[package]] name = "pallet-ocif-staking" version = "0.1.0-dev" -source = "git+https://github.com/InvArch/InvArch-Frames?branch=francisco-weight_fixes#c7bd7bb82384fcd4cd75d4030dfc0c637dd6f58a" dependencies = [ "cumulus-primitives-core", "frame-benchmarking", @@ -7135,7 +7131,6 @@ dependencies = [ [[package]] name = "pallet-rings" version = "0.1.0-dev" -source = "git+https://github.com/InvArch/InvArch-Frames?branch=francisco-weight_fixes#c7bd7bb82384fcd4cd75d4030dfc0c637dd6f58a" dependencies = [ "frame-benchmarking", "frame-support", diff --git a/tinkernet/Cargo.toml b/tinkernet/Cargo.toml index d159ae67..2816f3ba 100644 --- a/tinkernet/Cargo.toml +++ b/tinkernet/Cargo.toml @@ -43,11 +43,10 @@ derive_more = "0.99.2" ## InvArch Pallets -pallet-inv4 = { git = "https://github.com/InvArch/InvArch-Frames", branch="francisco-weight_fixes", default-features = false } -pallet-ocif-staking = { git = "https://github.com/InvArch/InvArch-Frames", branch="francisco-weight_fixes", default-features = false } -pallet-checked-inflation = { git = "https://github.com/InvArch/InvArch-Frames", branch="francisco-weight_fixes", default-features = false } -pallet-rings = { git = "https://github.com/InvArch/InvArch-Frames", branch="francisco-weight_fixes", default-features = false } - +pallet-inv4 = { path = "../pallets/INV4/pallet-inv4", default-features = false } +pallet-ocif-staking = { path = "../pallets/OCIF/staking", default-features = false } +pallet-checked-inflation = { path = "../pallets/pallet-checked-inflation", default-features = false } +pallet-rings = { path = "../pallets/pallet-rings", default-features = false } new-modified-construct-runtime = { path = "../new-modified-construct-runtime", default-features = false } pallet-maintenance-mode = { git = "https://github.com/Moonsong-Labs/moonkit", default-features = false, features = [