Compare commits

..

62 Commits

Author SHA1 Message Date
d575895841
make 1 second as a rate limit for default networks rpc endpoints
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-25 19:31:43 +03:00
47f7ae3847
separate evm structs, deserialisation functions and main logic
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-25 19:28:59 +03:00
591cce1fb1
rustfmt the ghost-slow-clap pallet
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-25 18:20:10 +03:00
f7ba592d50
rustfmt the ghost-networks pallet
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-25 18:17:55 +03:00
40a8152f69
rustfmt the ghost-claims pallet
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-25 18:17:14 +03:00
116ca39dc4
rustfmt the ghost-traits pallet
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-25 18:16:06 +03:00
8464da831f
rate limit for the rpc endpoint based on network_id, storage guard lock for the current network_id and other minor improvements
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-25 18:09:29 +03:00
0c3636fe79
bump all pallet versions
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-06-19 22:38:24 +03:00
d87184bbc2
update weights for the ghost networks pallet
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-06-19 22:37:03 +03:00
43f72ec842
update weights and add rate_limit_delay for slow claps
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-06-19 22:35:51 +03:00
ac6d70ae91
update chain specification based on new rate_limit_delay field of NetworkData
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-06-19 21:40:05 +03:00
49c5f3a9e9
update weights for the casper runtime, benchmarked with stopped ghost-node service
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-06-19 21:39:17 +03:00
060f61105c
additional network field, that represents default rate limit measured in blocks
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-06-19 21:32:40 +03:00
b53a58f431
update chain specification because of finality delay non-option type
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-06-19 15:02:07 +03:00
818f41d05e
update slow claps because of finality delay non-option type
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-06-19 15:00:30 +03:00
7bb18939bd
no need for finality delay to be an Option<u64>
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-06-19 14:37:06 +03:00
d8e934a98e
ability to avoid too big deviations between from_block and to_block
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-19 14:31:33 +03:00
d5643472ee
update chain specification based on NetworkData new fields
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-06-18 18:56:08 +03:00
a503295939
update weights for the ghost-networks on the casper runtime
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-06-18 18:54:44 +03:00
671196ebac
remove legacy release_delay and add block_distance for maximum block range for the eth_getLogs
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-06-18 18:53:19 +03:00
39a6192d28
avoid re-using of to_block during rotation of block_range
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-18 17:20:25 +03:00
6100e79ebf
make clap regardless of fail during applause
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-18 17:03:09 +03:00
99c43a0c24
runtime update, with history depth for the slow clap
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-18 14:17:02 +03:00
417de5a7b2
clear storage based on provided history depth
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-18 13:47:13 +03:00
b5845924dc
fixes for the default weights on slow-clap package
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-06-17 20:56:32 +03:00
7107283121
update casper runtime with pre-calculated weights
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-06-17 20:46:39 +03:00
f28e57cf8e
add files with weights for the slow-clap, benchmarked according to the casper reference machine
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-06-17 20:44:44 +03:00
3040dfb775
make benchmark work, issue with authorities fixed
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-06-17 20:34:42 +03:00
1196cc9faa
changes to runtime based on the new version of ghost-slow claps
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-17 13:54:32 +03:00
66fa8409fa
additional tests for the pallet
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-17 13:50:38 +03:00
5beb22f116
avoid errors from minting sub-existential balance
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-13 16:42:14 +03:00
7be24ed139
use latest version of ghost-networks
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-13 16:22:21 +03:00
b5fc86aa9e
separate bridged imbalance and gatekeeper amount. requested by @st1nky for ghost-slow-clap
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-06-13 16:16:01 +03:00
e73f3855fd
authorities stored based on the session hash map
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-11 22:56:48 +03:00
a00eec9bb9
tests for clap and applause events added
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-04 16:33:03 +03:00
2c2df5a607
ability to do self applause if claps received
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-04 15:44:53 +03:00
186fb58367
merge new functionality which will be used for benchmarking purposes
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-04 15:40:13 +03:00
1e4abbfe69
function to trigger nullification period, tests for the new functionality and expansion of NetworkData trait
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-06-04 15:35:48 +03:00
573e57dfb4
new tests based on new ghost-network functinality
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-03 20:41:51 +03:00
46d4716f67
merge extended ghost-networks with ability to nullify accumulated commission
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-03 19:48:23 +03:00
9cb7f3c782
replacing the average claps in session with median to determine a harmful authority
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-03 19:38:07 +03:00
c55d9a05d9
auto nullification during finalization and appropriate tests
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-06-03 19:06:50 +03:00
5847097e94
extend network inspect handler trait with additional function
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-06-03 18:58:21 +03:00
04a63e234d
tests updated and small tweaks of the lib
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-02 19:20:14 +03:00
2b738c009b
merge latest ghost-network version
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-02 19:17:16 +03:00
f3d8ee3ab2
make bridge imbalance fields accesible aka public
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-06-02 19:11:11 +03:00
2da07d7b24
chmod 644 Cargo.toml for ghost-slow-claps
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-05-31 14:55:30 +03:00
9ba25d6b3d
friendly merge for ghost-claims weights
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-05-31 14:51:53 +03:00
3234341fed
use benchmarked weights as a default weights for ghost-claims pallet
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-05-31 14:48:08 +03:00
fa2cb811a8
update for slow-claps: remove companions, updgrade block range storage, new way of commission accumulation
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-05-31 14:30:15 +03:00
561d4430b4
another indention fix in main Cargo.toml
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-05-31 14:21:21 +03:00
b64700fb42
fix indentation in TOML files
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-05-31 13:12:48 +03:00
b3f85f426c
extend pallet ghost-networks and create BridgedInflationCurve
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-05-30 19:03:50 +03:00
ddec108ced
chmod 644 files in runtime
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-05-29 13:09:54 +03:00
cd8ad50ac3
chmod 644 utils
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-05-29 13:04:55 +03:00
e09ce03836
chmod 644 tests
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-05-29 13:01:30 +03:00
9f6f4953f7
chmod 644 service
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-05-29 12:59:25 +03:00
40aba0e3af
chmod 644 files in rpc
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-05-29 12:58:09 +03:00
596d9a6ca7
chmod 644 files in core-primitives
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-05-29 12:57:26 +03:00
39279697f2
chmod 644 files in cli
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-05-29 12:56:11 +03:00
d3a18e298a
chmod 644 files in project root
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-05-29 12:54:26 +03:00
aede9e6e2e
change access permissions of files in pallets folder
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-05-29 12:52:37 +03:00
77 changed files with 4562 additions and 2900 deletions

26
Cargo.lock generated
View File

@ -1186,7 +1186,7 @@ dependencies = [
[[package]]
name = "casper-runtime"
version = "3.5.20"
version = "3.5.25"
dependencies = [
"casper-runtime-constants",
"frame-benchmarking",
@ -3504,7 +3504,7 @@ dependencies = [
[[package]]
name = "ghost-claims"
version = "0.2.2"
version = "0.2.4"
dependencies = [
"frame-benchmarking",
"frame-support",
@ -3528,7 +3528,7 @@ dependencies = [
[[package]]
name = "ghost-cli"
version = "0.7.197"
version = "0.7.201"
dependencies = [
"cfg-if",
"clap 4.5.4",
@ -3584,7 +3584,7 @@ dependencies = [
[[package]]
name = "ghost-machine-primitives"
version = "0.7.197"
version = "0.7.201"
dependencies = [
"lazy_static",
"sc-sysinfo",
@ -3593,7 +3593,7 @@ dependencies = [
[[package]]
name = "ghost-metrics"
version = "0.7.197"
version = "0.7.201"
dependencies = [
"assert_cmd",
"bs58 0.5.1",
@ -3648,7 +3648,7 @@ dependencies = [
[[package]]
name = "ghost-networks"
version = "0.7.197"
version = "0.1.11"
dependencies = [
"frame-benchmarking",
"frame-support",
@ -3656,6 +3656,8 @@ dependencies = [
"ghost-core-primitives",
"ghost-traits",
"pallet-balances",
"pallet-staking",
"pallet-staking-reward-curve",
"parity-scale-codec",
"scale-info",
"sp-io 30.0.0",
@ -3665,7 +3667,7 @@ dependencies = [
[[package]]
name = "ghost-node"
version = "0.7.197"
version = "0.7.201"
dependencies = [
"assert_cmd",
"color-eyre",
@ -3696,7 +3698,7 @@ dependencies = [
[[package]]
name = "ghost-rpc"
version = "0.7.197"
version = "0.7.201"
dependencies = [
"ghost-core-primitives",
"jsonrpsee",
@ -3748,7 +3750,7 @@ dependencies = [
[[package]]
name = "ghost-service"
version = "0.7.197"
version = "0.7.201"
dependencies = [
"assert_matches",
"async-trait",
@ -3832,7 +3834,7 @@ dependencies = [
[[package]]
name = "ghost-slow-clap"
version = "0.3.15"
version = "0.3.33"
dependencies = [
"frame-benchmarking",
"frame-support",
@ -3841,6 +3843,8 @@ dependencies = [
"log",
"pallet-balances",
"pallet-session",
"pallet-staking",
"pallet-staking-reward-curve",
"parity-scale-codec",
"scale-info",
"serde",
@ -3866,7 +3870,7 @@ dependencies = [
[[package]]
name = "ghost-traits"
version = "0.3.19"
version = "0.3.23"
dependencies = [
"frame-support",
"sp-runtime 31.0.1",

View File

@ -17,7 +17,7 @@ homepage.workspace = true
[workspace.package]
license = "GPL-3.0-only"
authors = ["571nky", "57r37ch", "f4750"]
version = "0.7.197"
version = "0.7.201"
edition = "2021"
homepage = "https://ghostchain.io"
repository = "https://git.ghostchain.io/ghostchain/ghost-node"
@ -258,24 +258,24 @@ substrate-build-script-utils = { workspace = true }
resolver = "2"
members = [
"core-primitives",
"core-primitives",
"cli",
"rpc",
"service",
"rpc",
"service",
"metrics",
"client/cli",
"primitives/machine",
"runtime/common",
"runtime/casper",
"runtime/casper/constants",
"pallets/networks",
"pallets/claims",
"pallets/slow-clap",
"utils/bags-list",
"utils/chain-spec-builder",
"utils/generate-bags",
"runtime/common",
"runtime/casper",
"runtime/casper/constants",
"pallets/networks",
"pallets/claims",
"pallets/slow-clap",
"utils/bags-list",
"utils/chain-spec-builder",
"utils/generate-bags",
"utils/ghostkey",
"utils/staking-miner",
"utils/staking-miner",
]
[badges]

0
LICENSE.md Executable file → Normal file
View File

0
README.md Executable file → Normal file
View File

14
cli/Cargo.toml Executable file → Normal file
View File

@ -52,14 +52,14 @@ substrate-build-script-utils = { workspace = true }
default = ["cli", "db", "full-node"]
db = ["service/db"]
cli = [
"clap",
"clap",
"frame-benchmarking-cli",
"sc-cli",
"sc-service",
"sc-tracing",
"service",
"ghost-client-cli",
"ghost-machine-primitives",
"sc-cli",
"sc-service",
"sc-tracing",
"service",
"ghost-client-cli",
"ghost-machine-primitives",
]
runtime-benchmarks = [
"frame-benchmarking-cli?/runtime-benchmarks",

0
cli/build.rs Executable file → Normal file
View File

0
cli/src/cli.rs Executable file → Normal file
View File

0
cli/src/command.rs Executable file → Normal file
View File

0
cli/src/error.rs Executable file → Normal file
View File

0
cli/src/lib.rs Executable file → Normal file
View File

6
core-primitives/Cargo.toml Executable file → Normal file
View File

@ -15,7 +15,7 @@ sp-runtime = { workspace = true }
[features]
default = ["std"]
std = [
"sp-core/std",
"sp-runtime/std",
"sp-std/std",
"sp-core/std",
"sp-runtime/std",
"sp-std/std",
]

0
core-primitives/src/lib.rs Executable file → Normal file
View File

0
file_header.txt Executable file → Normal file
View File

View File

@ -1,6 +1,6 @@
[package]
name = "ghost-claims"
version = "0.2.2"
version = "0.2.4"
description = "Ghost balance and rank claims based on EVM actions"
license.workspace = true
authors.workspace = true
@ -37,17 +37,17 @@ serde_json = { workspace = true, default-features = true }
[features]
default = ["std"]
std = [
"frame-benchmarking?/std",
"frame-benchmarking?/std",
"serde/std",
"codec/std",
"codec/std",
"scale-info/std",
"libsecp256k1/std",
"frame-support/std",
"frame-system/std",
"sp-core/std",
"sp-runtime/std",
"sp-io/std",
"sp-std/std",
"libsecp256k1/std",
"frame-support/std",
"frame-system/std",
"sp-core/std",
"sp-runtime/std",
"sp-io/std",
"sp-std/std",
"pallet-ranked-collective/std",
"pallet-vesting/std",
"pallet-balances/std",
@ -56,19 +56,19 @@ std = [
runtime-benchmarks = [
"libsecp256k1/hmac",
"libsecp256k1/static-context",
"frame-benchmarking/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"pallet-ranked-collective/runtime-benchmarks",
"pallet-vesting/runtime-benchmarks",
"pallet-balances/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
"frame-benchmarking/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"pallet-ranked-collective/runtime-benchmarks",
"pallet-vesting/runtime-benchmarks",
"pallet-balances/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
]
try-runtime = [
"frame-support/try-runtime",
"frame-system/try-runtime",
"pallet-ranked-collective/try-runtime",
"pallet-vesting/try-runtime",
"pallet-balances/try-runtime",
"sp-runtime/try-runtime",
"frame-support/try-runtime",
"frame-system/try-runtime",
"pallet-ranked-collective/try-runtime",
"pallet-vesting/try-runtime",
"pallet-balances/try-runtime",
"sp-runtime/try-runtime",
]

View File

@ -6,14 +6,14 @@ use frame_benchmarking::v2::*;
#[instance_benchmarks]
mod benchmarks {
use super::*;
use pallet_ranked_collective::Pallet as Club;
use frame_support::dispatch::RawOrigin;
use pallet_ranked_collective::Pallet as Club;
#[benchmark]
fn claim() {
let i = 1337u32;
let ethereum_secret_key = libsecp256k1::SecretKey::parse(
&keccak_256(&i.to_le_bytes())).unwrap();
let ethereum_secret_key =
libsecp256k1::SecretKey::parse(&keccak_256(&i.to_le_bytes())).unwrap();
let eth_address = crate::secp_utils::eth(&ethereum_secret_key);
let balance = CurrencyOf::<T, I>::minimum_balance();
@ -22,23 +22,30 @@ mod benchmarks {
Total::<T, I>::put(balance);
let pseudo_rank = 5u16;
let _ = Club::<T, I>::do_add_member_to_rank(
pseudo_account.clone(),
pseudo_rank,
false,
);
let _ = Club::<T, I>::do_add_member_to_rank(pseudo_account.clone(), pseudo_rank, false);
let user_account: T::AccountId = account("user", i, 0);
let signature = crate::secp_utils::sig::<T, I>(&ethereum_secret_key, &user_account.encode());
let signature =
crate::secp_utils::sig::<T, I>(&ethereum_secret_key, &user_account.encode());
let prev_balance = CurrencyOf::<T, I>::free_balance(&user_account);
let prev_rank = Club::<T, I>::rank_of(&user_account);
#[extrinsic_call]
claim(RawOrigin::Signed(user_account.clone()), eth_address, signature);
claim(
RawOrigin::Signed(user_account.clone()),
eth_address,
signature,
);
assert_eq!(CurrencyOf::<T, I>::free_balance(&user_account), prev_balance + balance);
assert_eq!(CurrencyOf::<T, I>::free_balance(&pseudo_account), balance - balance);
assert_eq!(
CurrencyOf::<T, I>::free_balance(&user_account),
prev_balance + balance
);
assert_eq!(
CurrencyOf::<T, I>::free_balance(&pseudo_account),
balance - balance
);
let rank = match prev_rank {
Some(current_rank) if pseudo_rank <= current_rank => Some(current_rank),
@ -48,9 +55,5 @@ mod benchmarks {
assert_eq!(Club::<T, I>::rank_of(&pseudo_account), None);
}
impl_benchmark_test_suite!(
Pallet,
crate::mock::new_test_ext(),
crate::mock::Test,
);
impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext(), crate::mock::Test,);
}

View File

@ -1,31 +1,33 @@
#![cfg_attr(not(feature = "std"), no_std)]
use frame_support::{
ensure, pallet_prelude::*,
ensure,
pallet_prelude::*,
traits::{
Currency, ExistenceRequirement, Get, RankedMembers,
RankedMembersSwapHandler, VestingSchedule,
Currency, ExistenceRequirement, Get, RankedMembers, RankedMembersSwapHandler,
VestingSchedule,
},
DefaultNoBound,
};
use frame_system::pallet_prelude::*;
use serde::{self, Deserialize, Deserializer, Serialize, Serializer};
pub use pallet::*;
use serde::{self, Deserialize, Deserializer, Serialize, Serializer};
use sp_io::{crypto::secp256k1_ecdsa_recover, hashing::keccak_256};
use sp_runtime::traits::{CheckedSub, CheckedDiv, BlockNumberProvider};
use sp_runtime::traits::{BlockNumberProvider, CheckedDiv, CheckedSub};
use sp_std::prelude::*;
extern crate alloc;
#[cfg(not(feature = "std"))]
use alloc::{format, string::String};
pub mod weights;
mod weights;
pub use crate::weights::WeightInfo;
mod tests;
mod mock;
mod benchmarking;
mod mock;
mod secp_utils;
mod tests;
/// An ethereum address (i.e. 20 bytes, used to represent an Ethereum account).
///
@ -55,7 +57,7 @@ impl<'de> Deserialize<'de> for EthereumAddress {
Err(serde::de::Error::custom(
"Bad length of Ethereum address (should be 42 including `0x`)",
))?;
}
}
let raw: Vec<u8> = rustc_hex::FromHex::from_hex(s)
.map_err(|e| serde::de::Error::custom(format!("{:?}", e)))?;
let mut r = Self::default();
@ -80,15 +82,14 @@ impl sp_std::fmt::Debug for EcdsaSignature {
}
type CurrencyOf<T, I> = <<T as Config<I>>::VestingSchedule as VestingSchedule<
<T as frame_system::Config>::AccountId
<T as frame_system::Config>::AccountId,
>>::Currency;
type BalanceOf<T, I> = <CurrencyOf<T, I> as Currency<
<T as frame_system::Config>::AccountId>
>::Balance;
type BalanceOf<T, I> =
<CurrencyOf<T, I> as Currency<<T as frame_system::Config>::AccountId>>::Balance;
type RankOf<T, I> = <pallet_ranked_collective::Pallet::<T, I> as RankedMembers>::Rank;
type AccountIdOf<T, I> = <pallet_ranked_collective::Pallet::<T, I> as RankedMembers>::AccountId;
type RankOf<T, I> = <pallet_ranked_collective::Pallet<T, I> as RankedMembers>::Rank;
type AccountIdOf<T, I> = <pallet_ranked_collective::Pallet<T, I> as RankedMembers>::AccountId;
#[frame_support::pallet]
pub mod pallet {
@ -99,8 +100,11 @@ pub mod pallet {
pub struct Pallet<T, I = ()>(_);
#[pallet::config]
pub trait Config<I: 'static = ()>: frame_system::Config + pallet_ranked_collective::Config<I> {
type RuntimeEvent: From<Event<Self, I>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
pub trait Config<I: 'static = ()>:
frame_system::Config + pallet_ranked_collective::Config<I>
{
type RuntimeEvent: From<Event<Self, I>>
+ IsType<<Self as frame_system::Config>::RuntimeEvent>;
type VestingSchedule: VestingSchedule<Self::AccountId, Moment = BlockNumberFor<Self>>;
type BlockNumberProvider: BlockNumberProvider<BlockNumber = BlockNumberFor<Self>>;
@ -117,13 +121,13 @@ pub mod pallet {
type WeightInfo: WeightInfo;
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config<I>, I: 'static = ()> {
Claimed {
receiver: T::AccountId,
donor: T::AccountId,
receiver: T::AccountId,
donor: T::AccountId,
amount: BalanceOf<T, I>,
rank: Option<RankOf<T, I>>,
},
@ -158,12 +162,16 @@ pub mod pallet {
.map(|(account_id, rank)| {
assert!(
pallet_ranked_collective::Pallet::<T, I>::do_add_member_to_rank(
account_id.clone(), *rank, false).is_ok(),
"error during adding and promotion"
account_id.clone(),
*rank,
false
)
.is_ok(),
"error during adding and promotion"
);
account_id
})
.collect();
.collect();
assert!(
self.members_and_ranks.len() == cult_accounts.len(),
@ -185,13 +193,13 @@ pub mod pallet {
) -> DispatchResult {
let who = ensure_signed(origin)?;
let data = who.using_encoded(to_ascii_hex);
let recovered_address = Self::recover_ethereum_address(
&ethereum_signature,
&data,
).ok_or(Error::<T, I>::InvalidEthereumSignature)?;
let recovered_address = Self::recover_ethereum_address(&ethereum_signature, &data)
.ok_or(Error::<T, I>::InvalidEthereumSignature)?;
ensure!(recovered_address == ethereum_address,
Error::<T, I>::InvalidEthereumAddress);
ensure!(
recovered_address == ethereum_address,
Error::<T, I>::InvalidEthereumAddress
);
Self::do_claim(who, ethereum_address)
}
@ -199,37 +207,37 @@ pub mod pallet {
}
fn to_ascii_hex(data: &[u8]) -> Vec<u8> {
let mut r = Vec::with_capacity(data.len() * 2);
let mut push_nibble = |n| r.push(if n < 10 { b'0' + n } else { b'a' - 10 + n });
for &b in data.iter() {
push_nibble(b / 16);
push_nibble(b % 16);
}
r
let mut r = Vec::with_capacity(data.len() * 2);
let mut push_nibble = |n| r.push(if n < 10 { b'0' + n } else { b'a' - 10 + n });
for &b in data.iter() {
push_nibble(b / 16);
push_nibble(b % 16);
}
r
}
impl<T: Config<I>, I: 'static> Pallet<T, I> {
fn ethereum_signable_message(what: &[u8]) -> Vec<u8> {
let prefix = T::Prefix::get();
let mut l = prefix.len() + what.len();
let mut rev = Vec::new();
while l > 0 {
rev.push(b'0' + (l % 10) as u8);
l /= 10;
}
let mut v = b"\x19Ethereum Signed Message:\n".to_vec();
v.extend(rev.into_iter().rev());
v.extend_from_slice(prefix);
v.extend_from_slice(what);
v
let mut l = prefix.len() + what.len();
let mut rev = Vec::new();
while l > 0 {
rev.push(b'0' + (l % 10) as u8);
l /= 10;
}
let mut v = b"\x19Ethereum Signed Message:\n".to_vec();
v.extend(rev.into_iter().rev());
v.extend_from_slice(prefix);
v.extend_from_slice(what);
v
}
fn recover_ethereum_address(s: &EcdsaSignature, what: &[u8]) -> Option<EthereumAddress> {
let msg = keccak_256(&Self::ethereum_signable_message(what));
let mut res = EthereumAddress::default();
res.0
.copy_from_slice(&keccak_256(&secp256k1_ecdsa_recover(&s.0, &msg).ok()?[..])[12..]);
Some(res)
let mut res = EthereumAddress::default();
res.0
.copy_from_slice(&keccak_256(&secp256k1_ecdsa_recover(&s.0, &msg).ok()?[..])[12..]);
Some(res)
}
fn into_account_id(address: EthereumAddress) -> Result<T::AccountId, codec::Error> {
@ -242,21 +250,24 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
}
fn do_claim(receiver: T::AccountId, ethereum_address: EthereumAddress) -> DispatchResult {
let donor = Self::into_account_id(ethereum_address).ok()
let donor = Self::into_account_id(ethereum_address)
.ok()
.ok_or(Error::<T, I>::AddressDecodingFailed)?;
let balance_due = CurrencyOf::<T, I>::free_balance(&donor);
ensure!(balance_due >= CurrencyOf::<T, I>::minimum_balance(),
Error::<T, I>::NoBalanceToClaim);
ensure!(
balance_due >= CurrencyOf::<T, I>::minimum_balance(),
Error::<T, I>::NoBalanceToClaim
);
let new_total = Total::<T, I>::get()
.checked_sub(&balance_due)
.ok_or(Error::<T, I>::PotUnderflow)?;
CurrencyOf::<T, I>::transfer(
&donor,
&receiver,
balance_due,
&donor,
&receiver,
balance_due,
ExistenceRequirement::AllowDeath,
)?;
@ -272,28 +283,40 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
.ok_or(Error::<T, I>::ArithmeticError)?;
T::VestingSchedule::add_vesting_schedule(
&receiver,
&receiver,
vesting_balance,
per_block_balance,
T::BlockNumberProvider::current_block_number(),
)?;
}
let rank = if let Some(rank) = <pallet_ranked_collective::Pallet::<T, I> as RankedMembers>::rank_of(&donor) {
let rank = if let Some(rank) =
<pallet_ranked_collective::Pallet<T, I> as RankedMembers>::rank_of(&donor)
{
pallet_ranked_collective::Pallet::<T, I>::do_remove_member_from_rank(&donor, rank)?;
let new_rank = match <pallet_ranked_collective::Pallet::<T, I> as RankedMembers>::rank_of(&receiver) {
Some(current_rank) if current_rank >= rank => current_rank,
Some(current_rank) if current_rank < rank => {
for _ in 0..rank - current_rank {
pallet_ranked_collective::Pallet::<T, I>::do_promote_member(receiver.clone(), None, false)?;
let new_rank =
match <pallet_ranked_collective::Pallet<T, I> as RankedMembers>::rank_of(&receiver)
{
Some(current_rank) if current_rank >= rank => current_rank,
Some(current_rank) if current_rank < rank => {
for _ in 0..rank - current_rank {
pallet_ranked_collective::Pallet::<T, I>::do_promote_member(
receiver.clone(),
None,
false,
)?;
}
rank
}
rank
},
_ => {
pallet_ranked_collective::Pallet::<T, I>::do_add_member_to_rank(receiver.clone(), rank, false)?;
rank
},
};
_ => {
pallet_ranked_collective::Pallet::<T, I>::do_add_member_to_rank(
receiver.clone(),
rank,
false,
)?;
rank
}
};
<T as pallet::Config<I>>::MemberSwappedHandler::swapped(&donor, &receiver, new_rank);
Some(new_rank)
} else {
@ -302,7 +325,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
Total::<T, I>::put(new_total);
Self::deposit_event(Event::<T, I>::Claimed {
receiver,
receiver,
donor,
amount: balance_due,
rank,

View File

@ -4,51 +4,113 @@ use super::*;
pub use crate as ghost_claims;
use frame_support::{
parameter_types, derive_impl,
traits::{PollStatus, Polling, WithdrawReasons, ConstU16, ConstU64},
derive_impl, parameter_types,
traits::{ConstU16, ConstU64, PollStatus, Polling, WithdrawReasons},
};
use frame_system::EnsureRootWithSuccess;
use sp_runtime::{BuildStorage, traits::Convert};
pub use pallet_ranked_collective::{TallyOf, Rank};
pub use pallet_ranked_collective::{Rank, TallyOf};
use sp_runtime::{traits::Convert, BuildStorage};
pub mod eth_keys {
use crate::{
mock::Test,
EcdsaSignature, EthereumAddress,
};
use hex_literal::hex;
use crate::{mock::Test, EcdsaSignature, EthereumAddress};
use codec::Encode;
use hex_literal::hex;
pub fn total_claims() -> u64 { 10 + 100 + 1000 }
pub fn alice_account_id() -> <Test as frame_system::Config>::AccountId { 69 }
pub fn bob_account_id() -> <Test as frame_system::Config>::AccountId { 1337 }
pub fn total_claims() -> u64 {
10 + 100 + 1000
}
pub fn alice_account_id() -> <Test as frame_system::Config>::AccountId {
69
}
pub fn bob_account_id() -> <Test as frame_system::Config>::AccountId {
1337
}
pub fn first_eth_public_known() -> EthereumAddress { EthereumAddress(hex!("1A69d2D5568D1878023EeB121a73d33B9116A760")) }
pub fn second_eth_public_known() -> EthereumAddress { EthereumAddress(hex!("2f86cfBED3fbc1eCf2989B9aE5fc019a837A9C12")) }
pub fn third_eth_public_known() -> EthereumAddress { EthereumAddress(hex!("e83f67361Ac74D42A48E2DAfb6706eb047D8218D")) }
pub fn fourth_eth_public_known() -> EthereumAddress { EthereumAddress(hex!("827ee4ad9b259b6fa1390ed60921508c78befd63")) }
pub fn first_eth_public_known() -> EthereumAddress {
EthereumAddress(hex!("1A69d2D5568D1878023EeB121a73d33B9116A760"))
}
pub fn second_eth_public_known() -> EthereumAddress {
EthereumAddress(hex!("2f86cfBED3fbc1eCf2989B9aE5fc019a837A9C12"))
}
pub fn third_eth_public_known() -> EthereumAddress {
EthereumAddress(hex!("e83f67361Ac74D42A48E2DAfb6706eb047D8218D"))
}
pub fn fourth_eth_public_known() -> EthereumAddress {
EthereumAddress(hex!("827ee4ad9b259b6fa1390ed60921508c78befd63"))
}
fn first_eth_private_key() -> libsecp256k1::SecretKey { libsecp256k1::SecretKey::parse(&hex!("01c928771aea942a1e7ac06adf2b73dfbc9a25d9eaa516e3673116af7f345198")).unwrap() }
fn second_eth_private_key() -> libsecp256k1::SecretKey { libsecp256k1::SecretKey::parse(&hex!("b19a435901872f817185f7234a1484eae837613f9d10cf21927a23c2d8cb9139")).unwrap() }
fn third_eth_private_key() -> libsecp256k1::SecretKey { libsecp256k1::SecretKey::parse(&hex!("d3baf57b74d65719b2dc33f5a464176022d0cc5edbca002234229f3e733875fc")).unwrap() }
fn fourth_eth_private_key() -> libsecp256k1::SecretKey { libsecp256k1::SecretKey::parse(&hex!("c4683d566436af6b58b4a59c8f501319226e85b21869bf93d5eeb4596d4791d4")).unwrap() }
fn wrong_eth_private_key() -> libsecp256k1::SecretKey { libsecp256k1::SecretKey::parse(&hex!("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef")).unwrap() }
fn first_eth_private_key() -> libsecp256k1::SecretKey {
libsecp256k1::SecretKey::parse(&hex!(
"01c928771aea942a1e7ac06adf2b73dfbc9a25d9eaa516e3673116af7f345198"
))
.unwrap()
}
fn second_eth_private_key() -> libsecp256k1::SecretKey {
libsecp256k1::SecretKey::parse(&hex!(
"b19a435901872f817185f7234a1484eae837613f9d10cf21927a23c2d8cb9139"
))
.unwrap()
}
fn third_eth_private_key() -> libsecp256k1::SecretKey {
libsecp256k1::SecretKey::parse(&hex!(
"d3baf57b74d65719b2dc33f5a464176022d0cc5edbca002234229f3e733875fc"
))
.unwrap()
}
fn fourth_eth_private_key() -> libsecp256k1::SecretKey {
libsecp256k1::SecretKey::parse(&hex!(
"c4683d566436af6b58b4a59c8f501319226e85b21869bf93d5eeb4596d4791d4"
))
.unwrap()
}
fn wrong_eth_private_key() -> libsecp256k1::SecretKey {
libsecp256k1::SecretKey::parse(&hex!(
"deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef"
))
.unwrap()
}
pub fn first_eth_public_key() -> EthereumAddress { crate::secp_utils::eth(&first_eth_private_key()) }
pub fn second_eth_public_key() -> EthereumAddress { crate::secp_utils::eth(&second_eth_private_key()) }
pub fn third_eth_public_key() -> EthereumAddress { crate::secp_utils::eth(&third_eth_private_key()) }
pub fn fourth_eth_public_key() -> EthereumAddress { crate::secp_utils::eth(&fourth_eth_private_key()) }
pub fn first_eth_public_key() -> EthereumAddress {
crate::secp_utils::eth(&first_eth_private_key())
}
pub fn second_eth_public_key() -> EthereumAddress {
crate::secp_utils::eth(&second_eth_private_key())
}
pub fn third_eth_public_key() -> EthereumAddress {
crate::secp_utils::eth(&third_eth_private_key())
}
pub fn fourth_eth_public_key() -> EthereumAddress {
crate::secp_utils::eth(&fourth_eth_private_key())
}
pub fn first_account_id() -> <Test as frame_system::Config>::AccountId { crate::secp_utils::into_account_id::<Test, ()>(first_eth_public_key()) }
pub fn second_account_id() -> <Test as frame_system::Config>::AccountId { crate::secp_utils::into_account_id::<Test, ()>(second_eth_public_key()) }
pub fn third_account_id() -> <Test as frame_system::Config>::AccountId { crate::secp_utils::into_account_id::<Test, ()>(third_eth_public_key()) }
pub fn fourth_account_id() -> <Test as frame_system::Config>::AccountId { crate::secp_utils::into_account_id::<Test, ()>(fourth_eth_public_key()) }
pub fn first_account_id() -> <Test as frame_system::Config>::AccountId {
crate::secp_utils::into_account_id::<Test, ()>(first_eth_public_key())
}
pub fn second_account_id() -> <Test as frame_system::Config>::AccountId {
crate::secp_utils::into_account_id::<Test, ()>(second_eth_public_key())
}
pub fn third_account_id() -> <Test as frame_system::Config>::AccountId {
crate::secp_utils::into_account_id::<Test, ()>(third_eth_public_key())
}
pub fn fourth_account_id() -> <Test as frame_system::Config>::AccountId {
crate::secp_utils::into_account_id::<Test, ()>(fourth_eth_public_key())
}
pub fn first_signature() -> EcdsaSignature { crate::secp_utils::sig::<Test, ()>(&first_eth_private_key(), &alice_account_id().encode()) }
pub fn second_signature() -> EcdsaSignature { crate::secp_utils::sig::<Test, ()>(&second_eth_private_key(), &alice_account_id().encode()) }
pub fn third_signature() -> EcdsaSignature { crate::secp_utils::sig::<Test, ()>(&third_eth_private_key(), &alice_account_id().encode()) }
pub fn fourth_signature() -> EcdsaSignature { crate::secp_utils::sig::<Test, ()>(&fourth_eth_private_key(), &bob_account_id().encode()) }
pub fn wrong_signature() -> EcdsaSignature { crate::secp_utils::sig::<Test, ()>(&wrong_eth_private_key(), &alice_account_id().encode()) }
pub fn first_signature() -> EcdsaSignature {
crate::secp_utils::sig::<Test, ()>(&first_eth_private_key(), &alice_account_id().encode())
}
pub fn second_signature() -> EcdsaSignature {
crate::secp_utils::sig::<Test, ()>(&second_eth_private_key(), &alice_account_id().encode())
}
pub fn third_signature() -> EcdsaSignature {
crate::secp_utils::sig::<Test, ()>(&third_eth_private_key(), &alice_account_id().encode())
}
pub fn fourth_signature() -> EcdsaSignature {
crate::secp_utils::sig::<Test, ()>(&fourth_eth_private_key(), &bob_account_id().encode())
}
pub fn wrong_signature() -> EcdsaSignature {
crate::secp_utils::sig::<Test, ()>(&wrong_eth_private_key(), &alice_account_id().encode())
}
}
#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
@ -66,10 +128,9 @@ impl pallet_balances::Config for Test {
type AccountStore = System;
}
parameter_types! {
pub const MinVestedTransfer: u64 = 1;
pub UnvestedFundsAllowedWithdrawReasons: WithdrawReasons =
pub UnvestedFundsAllowedWithdrawReasons: WithdrawReasons =
WithdrawReasons::except(WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE);
}
@ -79,9 +140,8 @@ impl pallet_vesting::Config for Test {
type BlockNumberToBalance = sp_runtime::traits::ConvertInto;
type MinVestedTransfer = MinVestedTransfer;
type WeightInfo = ();
type UnvestedFundsAllowedWithdrawReasons =
UnvestedFundsAllowedWithdrawReasons;
type UnvestedFundsAllowedWithdrawReasons = UnvestedFundsAllowedWithdrawReasons;
type BlockNumberProvider = System;
const MAX_VESTING_SCHEDULES: u32 = 28;
}
@ -148,7 +208,7 @@ impl pallet_ranked_collective::Config for Test {
type PromoteOrigin = EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>;
type DemoteOrigin = EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>;
type ExchangeOrigin = EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>;
type Polls = TestPolls;
type MemberSwappedHandler = ();
type MinRankOfClass = MinRankOfClass<MinRankOfClassDelta>;
@ -200,8 +260,8 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
(crate::mock::eth_keys::third_account_id(), 1000),
],
}
.assimilate_storage(&mut t)
.unwrap();
.assimilate_storage(&mut t)
.unwrap();
ghost_claims::GenesisConfig::<Test> {
total: crate::mock::eth_keys::total_claims(),
@ -210,8 +270,8 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
(crate::mock::eth_keys::third_account_id(), 3),
],
}
.assimilate_storage(&mut t)
.unwrap();
.assimilate_storage(&mut t)
.unwrap();
let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(|| {

View File

@ -8,7 +8,8 @@ pub fn public(secret: &libsecp256k1::SecretKey) -> libsecp256k1::PublicKey {
pub fn eth(secret: &libsecp256k1::SecretKey) -> EthereumAddress {
let mut res = EthereumAddress::default();
res.0.copy_from_slice(&keccak_256(&public(secret).serialize()[1..65])[12..]);
res.0
.copy_from_slice(&keccak_256(&public(secret).serialize()[1..65])[12..]);
res
}
@ -18,17 +19,14 @@ pub fn into_account_id<T: Config<I>, I: 'static>(address: EthereumAddress) -> T:
}
pub fn sig<T: Config<I>, I: 'static>(
secret: &libsecp256k1::SecretKey,
secret: &libsecp256k1::SecretKey,
what: &[u8],
) -> EcdsaSignature {
let msg = keccak_256(&super::Pallet::<T, I>::ethereum_signable_message(
&crate::to_ascii_hex(what)[..],
&crate::to_ascii_hex(what)[..],
));
let (sig, recovery_id) = libsecp256k1::sign(
&libsecp256k1::Message::parse(&msg),
secret,
);
let (sig, recovery_id) = libsecp256k1::sign(&libsecp256k1::Message::parse(&msg), secret);
let mut r = [0u8; 65];
r[0..64].copy_from_slice(&sig.serialize()[..]);

View File

@ -1,21 +1,19 @@
#![cfg(test)]
use mock::{
new_test_ext, ghost_claims,
Test, System, Balances, Club, Vesting, Claims, RuntimeOrigin, RuntimeEvent,
eth_keys::{
alice_account_id, total_claims, first_eth_public_known,
first_eth_public_key, first_account_id, first_signature,
second_eth_public_known, second_eth_public_key, second_account_id,
second_signature, third_eth_public_known, third_eth_public_key,
third_account_id, third_signature, fourth_eth_public_known,
fourth_eth_public_key, fourth_account_id, fourth_signature,
wrong_signature, bob_account_id,
}
};
use hex_literal::hex;
use frame_support::{assert_err, assert_ok};
use super::*;
use frame_support::{assert_err, assert_ok};
use hex_literal::hex;
use mock::{
eth_keys::{
alice_account_id, bob_account_id, first_account_id, first_eth_public_key,
first_eth_public_known, first_signature, fourth_account_id, fourth_eth_public_key,
fourth_eth_public_known, fourth_signature, second_account_id, second_eth_public_key,
second_eth_public_known, second_signature, third_account_id, third_eth_public_key,
third_eth_public_known, third_signature, total_claims, wrong_signature,
},
ghost_claims, new_test_ext, Balances, Claims, Club, RuntimeEvent, RuntimeOrigin, System, Test,
Vesting,
};
#[test]
fn serde_works() {
@ -41,12 +39,12 @@ fn basic_setup_works() {
assert_eq!(Balances::usable_balance(&first_account_id()), 10);
assert_eq!(Balances::usable_balance(&second_account_id()), 100);
assert_eq!(Balances::usable_balance(&third_account_id()), 1000);
assert_eq!(Club::rank_of(&alice_account_id()), None);
assert_eq!(Club::rank_of(&first_account_id()), None);
assert_eq!(Club::rank_of(&second_account_id()), Some(1));
assert_eq!(Club::rank_of(&third_account_id()), Some(3));
assert_eq!(Vesting::vesting_balance(&alice_account_id()), None);
assert_eq!(ghost_claims::Total::<Test, ()>::get(), total_claims());
});
@ -56,9 +54,10 @@ fn basic_setup_works() {
fn small_claiming_works() {
new_test_ext().execute_with(|| {
assert_ok!(Claims::claim(
RuntimeOrigin::signed(alice_account_id()),
first_eth_public_key(),
first_signature()));
RuntimeOrigin::signed(alice_account_id()),
first_eth_public_key(),
first_signature()
));
assert_eq!(Balances::usable_balance(&alice_account_id()), 10);
assert_eq!(Balances::usable_balance(&first_account_id()), 0);
@ -77,9 +76,9 @@ fn small_claiming_works() {
fn medium_claiming_works() {
new_test_ext().execute_with(|| {
assert_ok!(Claims::claim(
RuntimeOrigin::signed(alice_account_id()),
second_eth_public_key(),
second_signature(),
RuntimeOrigin::signed(alice_account_id()),
second_eth_public_key(),
second_signature(),
));
assert_eq!(Balances::usable_balance(&alice_account_id()), 100);
@ -99,9 +98,9 @@ fn medium_claiming_works() {
fn big_claiming_works() {
new_test_ext().execute_with(|| {
assert_ok!(Claims::claim(
RuntimeOrigin::signed(alice_account_id()),
third_eth_public_key(),
third_signature(),
RuntimeOrigin::signed(alice_account_id()),
third_eth_public_key(),
third_signature(),
));
assert_eq!(Balances::usable_balance(&alice_account_id()), 200);
@ -113,11 +112,15 @@ fn big_claiming_works() {
assert_eq!(Club::rank_of(&third_account_id()), None);
assert_eq!(Vesting::vesting_balance(&alice_account_id()), Some(800));
assert_eq!(ghost_claims::Total::<Test, ()>::get(), total_claims() - 1000);
assert_eq!(
ghost_claims::Total::<Test, ()>::get(),
total_claims() - 1000
);
assert_ok!(Balances::transfer_allow_death(
RuntimeOrigin::signed(alice_account_id()),
bob_account_id(),
200));
RuntimeOrigin::signed(alice_account_id()),
bob_account_id(),
200
));
})
}
@ -125,19 +128,19 @@ fn big_claiming_works() {
fn multiple_accounts_claiming_works() {
new_test_ext().execute_with(|| {
assert_ok!(Claims::claim(
RuntimeOrigin::signed(alice_account_id()),
first_eth_public_key(),
first_signature(),
RuntimeOrigin::signed(alice_account_id()),
first_eth_public_key(),
first_signature(),
));
assert_ok!(Claims::claim(
RuntimeOrigin::signed(alice_account_id()),
second_eth_public_key(),
second_signature(),
RuntimeOrigin::signed(alice_account_id()),
second_eth_public_key(),
second_signature(),
));
assert_ok!(Claims::claim(
RuntimeOrigin::signed(alice_account_id()),
third_eth_public_key(),
third_signature(),
RuntimeOrigin::signed(alice_account_id()),
third_eth_public_key(),
third_signature(),
));
assert_eq!(Balances::usable_balance(&alice_account_id()), 310);
@ -157,19 +160,19 @@ fn multiple_accounts_claiming_works() {
fn multiple_accounts_reverese_claiming_works() {
new_test_ext().execute_with(|| {
assert_ok!(Claims::claim(
RuntimeOrigin::signed(alice_account_id()),
third_eth_public_key(),
third_signature(),
RuntimeOrigin::signed(alice_account_id()),
third_eth_public_key(),
third_signature(),
));
assert_ok!(Claims::claim(
RuntimeOrigin::signed(alice_account_id()),
second_eth_public_key(),
second_signature(),
RuntimeOrigin::signed(alice_account_id()),
second_eth_public_key(),
second_signature(),
));
assert_ok!(Claims::claim(
RuntimeOrigin::signed(alice_account_id()),
first_eth_public_key(),
first_signature(),
RuntimeOrigin::signed(alice_account_id()),
first_eth_public_key(),
first_signature(),
));
assert_eq!(Balances::usable_balance(&alice_account_id()), 310);
@ -188,11 +191,14 @@ fn multiple_accounts_reverese_claiming_works() {
#[test]
fn cannot_claim_with_bad_signature() {
new_test_ext().execute_with(|| {
assert_err!(Claims::claim(
assert_err!(
Claims::claim(
RuntimeOrigin::signed(alice_account_id()),
first_eth_public_key(),
wrong_signature()),
crate::Error::<Test>::InvalidEthereumAddress);
wrong_signature()
),
crate::Error::<Test>::InvalidEthereumAddress
);
assert_eq!(Balances::usable_balance(&alice_account_id()), 0);
assert_eq!(Balances::usable_balance(&first_account_id()), 10);
@ -212,11 +218,14 @@ fn cannot_claim_with_bad_signature() {
#[test]
fn cannot_claim_with_wrong_address() {
new_test_ext().execute_with(|| {
assert_err!(Claims::claim(
assert_err!(
Claims::claim(
RuntimeOrigin::signed(bob_account_id()),
first_eth_public_key(),
first_signature()),
crate::Error::<Test>::InvalidEthereumAddress);
first_signature()
),
crate::Error::<Test>::InvalidEthereumAddress
);
assert_eq!(Balances::usable_balance(&bob_account_id()), 0);
assert_eq!(Balances::usable_balance(&alice_account_id()), 0);
@ -237,11 +246,14 @@ fn cannot_claim_with_wrong_address() {
#[test]
fn cannot_claim_nothing() {
new_test_ext().execute_with(|| {
assert_err!(Claims::claim(
assert_err!(
Claims::claim(
RuntimeOrigin::signed(bob_account_id()),
fourth_eth_public_key(),
fourth_signature()),
crate::Error::<Test>::NoBalanceToClaim);
fourth_signature()
),
crate::Error::<Test>::NoBalanceToClaim
);
assert_eq!(Balances::usable_balance(&bob_account_id()), 0);
assert_eq!(Balances::usable_balance(&fourth_account_id()), 0);
assert_eq!(Vesting::vesting_balance(&bob_account_id()), None);
@ -259,16 +271,15 @@ fn event_emitted_during_claim() {
System::reset_events();
assert_eq!(System::event_count(), 0);
assert_ok!(Claims::claim(
RuntimeOrigin::signed(alice_account_id()),
third_eth_public_key(),
third_signature(),
RuntimeOrigin::signed(alice_account_id()),
third_eth_public_key(),
third_signature(),
));
System::assert_has_event(RuntimeEvent::Claims(
crate::Event::Claimed {
receiver: alice_account_id(),
donor: account,
amount,
rank,
}));
System::assert_has_event(RuntimeEvent::Claims(crate::Event::Claimed {
receiver: alice_account_id(),
donor: account,
amount,
rank,
}));
})
}

View File

@ -1,9 +1,104 @@
use frame_support::weights::Weight;
// This file is part of Ghost Network.
// Ghost Network 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.
// Ghost Network 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 Ghost Network. If not, see <http://www.gnu.org/licenses/>.
//! Autogenerated weights for `ghost_claims`
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0
//! DATE: 2024-08-02, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! WORST CASE MAP SIZE: `1000000`
//! HOSTNAME: `ghostown`, CPU: `Intel(R) Core(TM) i3-2310M CPU @ 2.10GHz`
//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("casper-dev")`, DB CACHE: 1024
// Executed Command:
// ./target/release/ghost
// benchmark
// pallet
// --chain=casper-dev
// --steps=50
// --repeat=20
// --pallet=ghost_claims
// --extrinsic=*
// --wasm-execution=compiled
// --heap-pages=4096
// --header=./file_header.txt
// --output=./runtime/casper/src/weights/ghost_claims.rs
#![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 `ghost_claims`.
pub trait WeightInfo {
fn claim() -> Weight;
fn claim() -> Weight;
}
/// Weight for ghost_claims using the Substrate node and recommended hardware.
pub struct SubstrateWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
/// Storage: `System::Account` (r:2 w:2)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
/// Storage: `GhostClaims::Total` (r:1 w:1)
/// Proof: `GhostClaims::Total` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `CultCollective::Members` (r:2 w:2)
/// Proof: `CultCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`)
/// Storage: `CultCollective::MemberCount` (r:6 w:6)
/// Proof: `CultCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`)
/// Storage: `CultCollective::IdToIndex` (r:6 w:12)
/// Proof: `CultCollective::IdToIndex` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`)
/// Storage: `CultCollective::IndexToId` (r:0 w:6)
/// Proof: `CultCollective::IndexToId` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`)
fn claim() -> Weight {
// Proof Size summary in bytes:
// Measured: `896`
// Estimated: `16164`
// Minimum execution time: 754_086_000 picoseconds.
Weight::from_parts(756_147_000, 0)
.saturating_add(Weight::from_parts(0, 16164))
.saturating_add(T::DbWeight::get().reads(17))
.saturating_add(T::DbWeight::get().writes(29))
}
}
impl WeightInfo for () {
fn claim() -> Weight { Weight::zero() }
/// Storage: `System::Account` (r:2 w:2)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
/// Storage: `GhostClaims::Total` (r:1 w:1)
/// Proof: `GhostClaims::Total` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `CultCollective::Members` (r:2 w:2)
/// Proof: `CultCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`)
/// Storage: `CultCollective::MemberCount` (r:6 w:6)
/// Proof: `CultCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`)
/// Storage: `CultCollective::IdToIndex` (r:6 w:12)
/// Proof: `CultCollective::IdToIndex` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`)
/// Storage: `CultCollective::IndexToId` (r:0 w:6)
/// Proof: `CultCollective::IndexToId` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`)
fn claim() -> Weight {
// Proof Size summary in bytes:
// Measured: `896`
// Estimated: `16164`
// Minimum execution time: 754_086_000 picoseconds.
Weight::from_parts(756_147_000, 0)
.saturating_add(Weight::from_parts(0, 16164))
.saturating_add(RocksDbWeight::get().reads(17))
.saturating_add(RocksDbWeight::get().writes(29))
}
}

42
pallets/networks/Cargo.toml Executable file → Normal file
View File

@ -1,8 +1,8 @@
[package]
name = "ghost-networks"
version = "0.1.11"
license.workspace = true
authors.workspace = true
version.workspace = true
edition.workspace = true
homepage.workspace = true
repository.workspace = true
@ -14,36 +14,42 @@ codec = { workspace = true, features = ["max-encoded-len"] }
frame-benchmarking = { workspace = true, optional = true }
frame-support = { workspace = true }
frame-system = { workspace = true }
pallet-staking = { workspace = true }
sp-runtime = { workspace = true }
sp-std = { workspace = true }
ghost-traits = { workspace = true }
[dev-dependencies]
primitives = { workspace = true }
pallet-balances = { workspace = true }
sp-io = { workspace = true }
pallet-balances = { workspace = true }
pallet-staking-reward-curve = { workspace = true }
[features]
default = ["std"]
std = [
"scale-info/std",
"codec/std",
"frame-support/std",
"frame-system/std",
"frame-benchmarking?/std",
"sp-runtime/std",
"sp-std/std",
"sp-io/std",
"ghost-traits/std",
"pallet-balances/std",
"scale-info/std",
"codec/std",
"frame-support/std",
"frame-system/std",
"frame-benchmarking?/std",
"sp-runtime/std",
"sp-std/std",
"sp-io/std",
"ghost-traits/std",
"pallet-staking/std",
"pallet-balances/std",
]
runtime-benchmarks = [
"frame-benchmarking/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
"frame-benchmarking/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
"pallet-staking/runtime-benchmarks",
]
try-runtime = [
"frame-support/try-runtime",
"frame-system/try-runtime",
"frame-support/try-runtime",
"frame-system/try-runtime",
"pallet-staking/try-runtime",
"pallet-balances/try-runtime",
]

50
pallets/networks/src/benchmarking.rs Executable file → Normal file
View File

@ -13,26 +13,29 @@ fn assert_last_event<T: Config>(generic_event: <T as Config>::RuntimeEvent) {
frame_system::Pallet::<T>::assert_last_event(generic_event.into());
}
fn prepare_network<T: Config>(
n: u32, m: u32,
) -> (<T as module::Config>::NetworkId, NetworkData) {
fn prepare_network<T: Config>(n: u32, m: u32) -> (<T as module::Config>::NetworkId, NetworkData) {
let chain_id: <T as module::Config>::NetworkId = Default::default();
let chain_id = chain_id.saturating_add((n + m).into());
let mut gatekeeper = b"0x".to_vec();
for i in 0..40 { gatekeeper.push(i); }
for i in 0..40 {
gatekeeper.push(i);
}
let mut topic_name = b"0x".to_vec();
for i in 0..64 { topic_name.push(i); }
for i in 0..64 {
topic_name.push(i);
}
let network = NetworkData {
chain_name: sp_std::vec![0x69; n as usize],
default_endpoint: sp_std::vec![0x69; m as usize],
gatekeeper,
topic_name,
finality_delay: Some(69),
release_delay: Some(69),
network_type: NetworkType::Evm,
finality_delay: 69,
rate_limit_delay: 69,
block_distance: 69,
incoming_fee: 0,
outgoing_fee: 0,
};
@ -50,8 +53,11 @@ fn create_network<T: Config>(
let authority = T::RegisterOrigin::try_successful_origin()
.map_err(|_| BenchmarkError::Weightless)?;
GhostNetworks::<T>::register_network(
authority.clone(), chain_id.clone(), network.clone()
).map_err(|_| BenchmarkError::Weightless)?;
authority.clone(),
chain_id.clone(),
network.clone(),
)
.map_err(|_| BenchmarkError::Weightless)?;
network
}
};
@ -107,7 +113,7 @@ benchmarks! {
}
update_network_finality_delay {
let delay = Some(1337);
let delay = 1337;
let (chain_id, network) = prepare_network::<T>(1, 1);
let authority = T::UpdateOrigin::try_successful_origin()
.map_err(|_| BenchmarkError::Weightless)?;
@ -120,16 +126,30 @@ benchmarks! {
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
update_network_release_delay {
let delay = Some(1337);
update_network_rate_limit_delay {
let rate_limit = 1337;
let (chain_id, network) = prepare_network::<T>(1, 1);
let authority = T::UpdateOrigin::try_successful_origin()
.map_err(|_| BenchmarkError::Weightless)?;
let prev_network = create_network::<T>(chain_id.clone(), network.clone())?;
}: _<T::RuntimeOrigin>(authority, chain_id.clone(), delay)
}: _<T::RuntimeOrigin>(authority, chain_id.clone(), rate_limit)
verify {
assert_last_event::<T>(Event::NetworkReleaseDelayUpdated {
chain_id: chain_id.clone(), release_delay: delay,
assert_last_event::<T>(Event::NetworkRateLimitDelayUpdated {
chain_id: chain_id.clone(), rate_limit_delay: rate_limit,
}.into());
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
update_network_block_distance {
let block_distance = 1337;
let (chain_id, network) = prepare_network::<T>(1, 1);
let authority = T::UpdateOrigin::try_successful_origin()
.map_err(|_| BenchmarkError::Weightless)?;
let prev_network = create_network::<T>(chain_id.clone(), network.clone())?;
}: _<T::RuntimeOrigin>(authority, chain_id.clone(), block_distance)
verify {
assert_last_event::<T>(Event::NetworkBlockDistanceUpdated {
chain_id: chain_id.clone(), block_distance,
}.into());
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}

417
pallets/networks/src/lib.rs Executable file → Normal file
View File

@ -4,25 +4,27 @@
use frame_support::{
pallet_prelude::*,
storage::PrefixIterator, traits::EnsureOrigin,
storage::PrefixIterator,
traits::{tokens::fungible::Inspect, EnsureOrigin},
};
use frame_system::pallet_prelude::*;
use scale_info::TypeInfo;
use sp_runtime::{
traits::{AtLeast32BitUnsigned, Member},
curve::PiecewiseLinear,
traits::{AtLeast32BitUnsigned, CheckedAdd, CheckedSub, Member},
DispatchResult,
};
use sp_std::prelude::*;
use sp_std::{convert::TryInto, prelude::*};
pub use ghost_traits::networks::{
NetworkDataBasicHandler, NetworkDataInspectHandler,
NetworkDataMutateHandler,
NetworkDataBasicHandler, NetworkDataInspectHandler, NetworkDataMutateHandler,
};
mod weights;
pub use module::*;
pub use crate::weights::WeightInfo;
pub use module::*;
#[cfg(any(feature = "runtime-benchmarks", test))]
mod benchmarking;
@ -31,6 +33,9 @@ mod mock;
#[cfg(all(feature = "std", test))]
mod tests;
pub type BalanceOf<T> =
<<T as Config>::Currency as Inspect<<T as frame_system::Config>::AccountId>>::Balance;
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub enum NetworkType {
Evm = 0,
@ -39,7 +44,9 @@ pub enum NetworkType {
}
impl Default for NetworkType {
fn default() -> Self { NetworkType::Evm }
fn default() -> Self {
NetworkType::Evm
}
}
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
@ -48,13 +55,60 @@ pub struct NetworkData {
pub default_endpoint: Vec<u8>,
pub gatekeeper: Vec<u8>,
pub topic_name: Vec<u8>,
pub finality_delay: Option<u64>,
pub release_delay: Option<u64>,
pub network_type: NetworkType,
pub finality_delay: u64,
pub rate_limit_delay: u64,
pub block_distance: u64,
pub incoming_fee: u32,
pub outgoing_fee: u32,
}
#[derive(Default, Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub struct BridgeAdjustment<Balance> {
pub bridged_out: Balance,
pub bridged_in: Balance,
}
pub struct BridgedInflationCurve<RewardCurve, T>(core::marker::PhantomData<(RewardCurve, T)>);
impl<Balance, RewardCurve, T> pallet_staking::EraPayout<Balance>
for BridgedInflationCurve<RewardCurve, T>
where
Balance: Default + AtLeast32BitUnsigned + Clone + Copy + From<u128>,
RewardCurve: Get<&'static PiecewiseLinear<'static>>,
T: Config,
{
fn era_payout(
total_staked: Balance,
total_issuance: Balance,
_era_duration_in_millis: u64,
) -> (Balance, Balance) {
let piecewise_linear = RewardCurve::get();
let bridge_adjustment = BridgedImbalance::<T>::get();
let accumulated_commission = AccumulatedCommission::<T>::get();
let bridged_out: u128 = bridge_adjustment.bridged_out.try_into().unwrap_or_default();
let bridged_in: u128 = bridge_adjustment.bridged_in.try_into().unwrap_or_default();
let accumulated_commission: u128 = accumulated_commission.try_into().unwrap_or_default();
let accumulated_balance = Balance::from(accumulated_commission);
let adjusted_issuance = match bridged_out > bridged_in {
true => total_issuance.saturating_add(Balance::from(bridged_out - bridged_in)),
false => total_issuance.saturating_sub(Balance::from(bridged_in - bridged_out)),
};
NullifyNeeded::<T>::set(true);
match piecewise_linear
.calculate_for_fraction_times_denominator(total_staked, adjusted_issuance)
.checked_mul(&accumulated_balance)
.and_then(|product| product.checked_div(&adjusted_issuance))
{
Some(payout) => (payout, accumulated_balance.saturating_sub(payout)),
None => (Balance::default(), Balance::default()),
}
}
}
#[frame_support::pallet]
pub mod module {
use super::*;
@ -63,6 +117,9 @@ pub mod module {
pub trait Config: frame_system::Config {
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// The type used for the internal balance storage.
type Currency: Inspect<Self::AccountId>;
/// The type used as a unique network id.
type NetworkId: Parameter
+ Member
@ -74,7 +131,7 @@ pub mod module {
+ TypeInfo
+ MaybeSerializeDeserialize
+ MaxEncodedLen;
/// The origin required to register new network.
type RegisterOrigin: EnsureOrigin<Self::RuntimeOrigin>;
/// The origin required to update network information.
@ -101,24 +158,78 @@ pub mod module {
#[pallet::event]
#[pallet::generate_deposit(pub(crate) fn deposit_event)]
pub enum Event<T: Config> {
NetworkRegistered { chain_id: T::NetworkId, network: NetworkData },
NetworkNameUpdated { chain_id: T::NetworkId, chain_name: Vec<u8> },
NetworkEndpointUpdated { chain_id: T::NetworkId, default_endpoint: Vec<u8> },
NetworkFinalityDelayUpdated { chain_id: T::NetworkId, finality_delay: Option<u64> },
NetworkReleaseDelayUpdated { chain_id: T::NetworkId, release_delay: Option<u64> },
NetworkTypeUpdated { chain_id: T::NetworkId, network_type: NetworkType },
NetworkGatekeeperUpdated { chain_id: T::NetworkId, gatekeeper: Vec<u8> },
NetworkTopicNameUpdated { chain_id: T::NetworkId, topic_name: Vec<u8> },
NetworkIncomingFeeUpdated { chain_id: T::NetworkId, incoming_fee: u32 },
NetworkOutgoingFeeUpdated { chain_id: T::NetworkId, outgoing_fee: u32 },
NetworkRemoved { chain_id: T::NetworkId },
NetworkRegistered {
chain_id: T::NetworkId,
network: NetworkData,
},
NetworkNameUpdated {
chain_id: T::NetworkId,
chain_name: Vec<u8>,
},
NetworkEndpointUpdated {
chain_id: T::NetworkId,
default_endpoint: Vec<u8>,
},
NetworkFinalityDelayUpdated {
chain_id: T::NetworkId,
finality_delay: u64,
},
NetworkRateLimitDelayUpdated {
chain_id: T::NetworkId,
rate_limit_delay: u64,
},
NetworkBlockDistanceUpdated {
chain_id: T::NetworkId,
block_distance: u64,
},
NetworkTypeUpdated {
chain_id: T::NetworkId,
network_type: NetworkType,
},
NetworkGatekeeperUpdated {
chain_id: T::NetworkId,
gatekeeper: Vec<u8>,
},
NetworkTopicNameUpdated {
chain_id: T::NetworkId,
topic_name: Vec<u8>,
},
NetworkIncomingFeeUpdated {
chain_id: T::NetworkId,
incoming_fee: u32,
},
NetworkOutgoingFeeUpdated {
chain_id: T::NetworkId,
outgoing_fee: u32,
},
NetworkRemoved {
chain_id: T::NetworkId,
},
}
#[pallet::storage]
#[pallet::getter(fn nullify_needed)]
pub type NullifyNeeded<T: Config> = StorageValue<_, bool, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn bridged_imbalance)]
pub type BridgedImbalance<T: Config> =
StorageValue<_, BridgeAdjustment<BalanceOf<T>>, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn accumulated_commission)]
pub type AccumulatedCommission<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn networks)]
pub type Networks<T: Config> =
StorageMap<_, Twox64Concat, T::NetworkId, NetworkData, OptionQuery>;
#[pallet::storage]
#[pallet::getter(fn gatekeeper_amount)]
pub type GatekeeperAmount<T: Config> =
StorageMap<_, Twox64Concat, T::NetworkId, BalanceOf<T>, ValueQuery>;
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
pub networks: Vec<(T::NetworkId, Vec<u8>)>,
@ -126,7 +237,7 @@ pub mod module {
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
Self { networks: vec![] }
Self { networks: vec![] }
}
}
@ -134,12 +245,13 @@ pub mod module {
impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
fn build(&self) {
if !self.networks.is_empty() {
self.networks.iter().for_each(|(chain_id, network_metadata)| {
let network =
NetworkData::decode(&mut &network_metadata[..])
.expect("Error decoding NetworkData");
Pallet::<T>::do_register_network(chain_id.clone(), network)
.expect("Error registering network");
self.networks
.iter()
.for_each(|(chain_id, network_metadata)| {
let network = NetworkData::decode(&mut &network_metadata[..])
.expect("Error decoding NetworkData");
Pallet::<T>::do_register_network(chain_id.clone(), network)
.expect("Error registering network");
});
}
}
@ -150,7 +262,18 @@ pub mod module {
pub struct Pallet<T>(PhantomData<T>);
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn on_initialize(_: BlockNumberFor<T>) -> Weight {
T::DbWeight::get().reads_writes(1, 1)
}
fn on_finalize(_: BlockNumberFor<T>) {
if Self::nullify_needed() {
Self::nullify_commission();
NullifyNeeded::<T>::put(false);
}
}
}
#[pallet::call]
impl<T: Config> Pallet<T> {
@ -178,10 +301,7 @@ pub mod module {
chain_name: Vec<u8>,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_name(
chain_id,
chain_name,
)
Self::do_update_network_name(chain_id, chain_name)
}
#[pallet::call_index(2)]
@ -194,10 +314,7 @@ pub mod module {
default_endpoint: Vec<u8>,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_endpoint(
chain_id,
default_endpoint,
)
Self::do_update_network_endpoint(chain_id, default_endpoint)
}
#[pallet::call_index(3)]
@ -205,30 +322,35 @@ pub mod module {
pub fn update_network_finality_delay(
origin: OriginFor<T>,
chain_id: T::NetworkId,
finality_delay: Option<u64>,
finality_delay: u64,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_finality_delay(
chain_id,
finality_delay,
)
Self::do_update_network_finality_delay(chain_id, finality_delay)
}
#[pallet::call_index(4)]
#[pallet::weight(T::WeightInfo::update_network_release_delay())]
pub fn update_network_release_delay(
#[pallet::weight(T::WeightInfo::update_network_rate_limit_delay())]
pub fn update_network_rate_limit_delay(
origin: OriginFor<T>,
chain_id: T::NetworkId,
release_delay: Option<u64>,
rate_limit_delay: u64,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_release_delay(
chain_id,
release_delay,
)
Self::do_update_network_rate_limit_delay(chain_id, rate_limit_delay)
}
#[pallet::call_index(5)]
#[pallet::weight(T::WeightInfo::update_network_block_distance())]
pub fn update_network_block_distance(
origin: OriginFor<T>,
chain_id: T::NetworkId,
block_distance: u64,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_block_distance(chain_id, block_distance)
}
#[pallet::call_index(6)]
#[pallet::weight(T::WeightInfo::update_network_type())]
pub fn update_network_type(
origin: OriginFor<T>,
@ -236,13 +358,10 @@ pub mod module {
network_type: NetworkType,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_type(
chain_id,
network_type,
)
Self::do_update_network_type(chain_id, network_type)
}
#[pallet::call_index(6)]
#[pallet::call_index(7)]
#[pallet::weight(T::WeightInfo::update_network_gatekeeper())]
pub fn update_network_gatekeeper(
origin: OriginFor<T>,
@ -250,13 +369,10 @@ pub mod module {
gatekeeper: Vec<u8>,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_gatekeeper(
chain_id,
gatekeeper,
)
Self::do_update_network_gatekeeper(chain_id, gatekeeper)
}
#[pallet::call_index(7)]
#[pallet::call_index(8)]
#[pallet::weight(T::WeightInfo::update_network_topic_name())]
pub fn update_network_topic_name(
origin: OriginFor<T>,
@ -264,13 +380,10 @@ pub mod module {
topic_name: Vec<u8>,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_topic_name(
chain_id,
topic_name,
)
Self::do_update_network_topic_name(chain_id, topic_name)
}
#[pallet::call_index(8)]
#[pallet::call_index(9)]
#[pallet::weight(T::WeightInfo::update_incoming_network_fee())]
pub fn update_incoming_network_fee(
origin: OriginFor<T>,
@ -278,13 +391,10 @@ pub mod module {
incoming_fee: u32,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_incoming_network_fee(
chain_id,
incoming_fee,
)
Self::do_update_incoming_network_fee(chain_id, incoming_fee)
}
#[pallet::call_index(9)]
#[pallet::call_index(10)]
#[pallet::weight(T::WeightInfo::update_outgoing_network_fee())]
pub fn update_outgoing_network_fee(
origin: OriginFor<T>,
@ -292,18 +402,12 @@ pub mod module {
outgoing_fee: u32,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_outgoing_network_fee(
chain_id,
outgoing_fee,
)
Self::do_update_outgoing_network_fee(chain_id, outgoing_fee)
}
#[pallet::call_index(10)]
#[pallet::call_index(11)]
#[pallet::weight(T::WeightInfo::remove_network())]
pub fn remove_network(
origin: OriginFor<T>,
chain_id: T::NetworkId,
) -> DispatchResult {
pub fn remove_network(origin: OriginFor<T>, chain_id: T::NetworkId) -> DispatchResult {
T::RemoveOrigin::ensure_origin_or_root(origin)?;
Self::do_remove_network(chain_id)
}
@ -312,12 +416,12 @@ pub mod module {
impl<T: Config> Pallet<T> {
/// Register a new network.
pub fn do_register_network(
chain_id: T::NetworkId,
network: NetworkData,
) -> DispatchResult {
pub fn do_register_network(chain_id: T::NetworkId, network: NetworkData) -> DispatchResult {
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_none(), Error::<T>::NetworkAlreadyRegistered);
ensure!(
maybe_network.is_none(),
Error::<T>::NetworkAlreadyRegistered
);
*maybe_network = Some(network.clone());
Ok(())
})?;
@ -339,10 +443,7 @@ impl<T: Config> Pallet<T> {
}
/// Update existent network name.
pub fn do_update_network_name(
chain_id: T::NetworkId,
chain_name: Vec<u8>,
) -> DispatchResult {
pub fn do_update_network_name(chain_id: T::NetworkId, chain_name: Vec<u8>) -> DispatchResult {
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist);
let net = maybe_network.as_mut().unwrap();
@ -377,10 +478,10 @@ impl<T: Config> Pallet<T> {
Ok(())
}
/// Update existent network default endpoint.
/// Update existent network default finality delay.
pub fn do_update_network_finality_delay(
chain_id: T::NetworkId,
finality_delay: Option<u64>,
finality_delay: u64,
) -> DispatchResult {
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist);
@ -396,21 +497,40 @@ impl<T: Config> Pallet<T> {
Ok(())
}
/// Update existent network default endpoint.
pub fn do_update_network_release_delay(
/// Update existent network default rate limit delay.
pub fn do_update_network_rate_limit_delay(
chain_id: T::NetworkId,
release_delay: Option<u64>,
rate_limit_delay: u64,
) -> DispatchResult {
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist);
let net = maybe_network.as_mut().unwrap();
net.release_delay = release_delay;
net.rate_limit_delay = rate_limit_delay;
*maybe_network = Some(net.clone());
Ok(())
})?;
Self::deposit_event(Event::<T>::NetworkReleaseDelayUpdated {
Self::deposit_event(Event::<T>::NetworkRateLimitDelayUpdated {
chain_id,
release_delay,
rate_limit_delay,
});
Ok(())
}
/// Update existent network default max distance between blocks.
pub fn do_update_network_block_distance(
chain_id: T::NetworkId,
block_distance: u64,
) -> DispatchResult {
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist);
let net = maybe_network.as_mut().unwrap();
net.block_distance = block_distance;
*maybe_network = Some(net.clone());
Ok(())
})?;
Self::deposit_event(Event::<T>::NetworkBlockDistanceUpdated {
chain_id,
block_distance,
});
Ok(())
}
@ -439,8 +559,10 @@ impl<T: Config> Pallet<T> {
chain_id: T::NetworkId,
gatekeeper: Vec<u8>,
) -> DispatchResult {
ensure!(gatekeeper.len() == 42 && gatekeeper[0] == 48 && gatekeeper[1] == 120,
Error::<T>::WrongGatekeeperAddress);
ensure!(
gatekeeper.len() == 42 && gatekeeper[0] == 48 && gatekeeper[1] == 120,
Error::<T>::WrongGatekeeperAddress
);
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist);
let net = maybe_network.as_mut().unwrap();
@ -460,8 +582,10 @@ impl<T: Config> Pallet<T> {
chain_id: T::NetworkId,
topic_name: Vec<u8>,
) -> DispatchResult {
ensure!(topic_name.len() == 66 && topic_name[0] == 48 && topic_name[1] == 120,
Error::<T>::WrongTopicName);
ensure!(
topic_name.len() == 66 && topic_name[0] == 48 && topic_name[1] == 120,
Error::<T>::WrongTopicName
);
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist);
let net = maybe_network.as_mut().unwrap();
@ -525,9 +649,13 @@ impl<T: Config> NetworkDataInspectHandler<NetworkData> for Pallet<T> {
fn iter() -> PrefixIterator<(Self::NetworkId, NetworkData)> {
Networks::<T>::iter()
}
fn is_nullification_period() -> bool {
NullifyNeeded::<T>::get()
}
}
impl<T: Config> NetworkDataMutateHandler<NetworkData> for Pallet<T> {
impl<T: Config> NetworkDataMutateHandler<NetworkData, BalanceOf<T>> for Pallet<T> {
fn register(chain_id: Self::NetworkId, network: NetworkData) -> DispatchResult {
Self::do_register_network(chain_id, network)
}
@ -535,4 +663,93 @@ impl<T: Config> NetworkDataMutateHandler<NetworkData> for Pallet<T> {
fn remove(chain_id: Self::NetworkId) -> DispatchResult {
Self::do_remove_network(chain_id)
}
fn increase_gatekeeper_amount(
network_id: &T::NetworkId,
amount: &BalanceOf<T>,
) -> Result<BalanceOf<T>, ()> {
let new_gatekeeper_amount =
GatekeeperAmount::<T>::mutate(network_id, |gatekeeper_amount| match gatekeeper_amount
.checked_add(amount)
{
Some(value) => {
*gatekeeper_amount = value;
Ok(value)
}
None => Err(()),
})?;
Ok(new_gatekeeper_amount)
}
fn decrease_gatekeeper_amount(
network_id: &T::NetworkId,
amount: &BalanceOf<T>,
) -> Result<BalanceOf<T>, ()> {
let new_gatekeeper_amount =
GatekeeperAmount::<T>::mutate(network_id, |gatekeeper_amount| match gatekeeper_amount
.checked_sub(amount)
{
Some(value) => {
*gatekeeper_amount = value;
Ok(value)
}
None => Err(()),
})?;
Ok(new_gatekeeper_amount)
}
fn accumulate_outgoing_imbalance(amount: &BalanceOf<T>) -> Result<BalanceOf<T>, ()> {
let new_bridged_out_amount = BridgedImbalance::<T>::mutate(|bridged_imbalance| {
match bridged_imbalance.bridged_out.checked_add(amount) {
Some(value) => {
(*bridged_imbalance).bridged_out = value;
Ok(value)
}
None => Err(()),
}
})?;
Ok(new_bridged_out_amount)
}
fn accumulate_incoming_imbalance(amount: &BalanceOf<T>) -> Result<BalanceOf<T>, ()> {
let new_bridged_in_amount = BridgedImbalance::<T>::mutate(|bridged_imbalance| {
match bridged_imbalance.bridged_in.checked_add(amount) {
Some(value) => {
(*bridged_imbalance).bridged_in = value;
Ok(value)
}
None => Err(()),
}
})?;
Ok(new_bridged_in_amount)
}
fn accumulate_commission(commission: &BalanceOf<T>) -> Result<BalanceOf<T>, ()> {
AccumulatedCommission::<T>::mutate(|accumulated| {
match accumulated.checked_add(commission) {
Some(value) => {
*accumulated = value;
Ok(value)
}
None => Err(()),
}
})
}
fn nullify_commission() {
AccumulatedCommission::<T>::set(Default::default());
}
fn trigger_nullification() {
if NullifyNeeded::<T>::get() {
Self::nullify_commission();
NullifyNeeded::<T>::put(false);
} else {
NullifyNeeded::<T>::put(true);
}
}
}

41
pallets/networks/src/mock.rs Executable file → Normal file
View File

@ -1,19 +1,24 @@
use crate as ghost_networks;
use frame_system::EnsureSignedBy;
use crate::{self as ghost_networks};
use frame_support::{
construct_runtime, ord_parameter_types, parameter_types, traits::{ConstU128, ConstU32, Everything}
construct_runtime, ord_parameter_types, parameter_types,
traits::{ConstU128, ConstU32, Everything},
};
use frame_system::EnsureSignedBy;
pub use primitives::{
AccountId, Balance, Nonce, BlockNumber, Hash,
ReserveIdentifier, FreezeIdentifier,
AccountId, Balance, BlockNumber, FreezeIdentifier, Hash, Nonce, ReserveIdentifier,
};
use sp_runtime::{
traits::{BlakeTwo256, AccountIdLookup},
curve::PiecewiseLinear,
traits::{AccountIdLookup, BlakeTwo256},
BuildStorage,
};
parameter_types! {
pub const BlockHashCount: BlockNumber = 250;
pub static SlashDeferDuration: u32 = 0;
pub static Period: BlockNumber = 5;
pub static Offset: BlockNumber = 0;
pub static MaxControllersInDeprecationBatch: u32 = 5_000;
}
impl frame_system::Config for Test {
@ -64,6 +69,21 @@ impl pallet_balances::Config for Test {
type MaxFreezes = ConstU32<50>;
}
pallet_staking_reward_curve::build! {
const REWARD_CURVE: PiecewiseLinear<'static> = curve!(
min_inflation: 0_006_900,
max_inflation: 1_000_000,
ideal_stake: 0_690_000,
falloff: 0_050_000,
max_piece_count: 100,
test_precision: 0_005_000,
);
}
parameter_types! {
pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE;
}
ord_parameter_types! {
pub const RegistererAccount: AccountId = AccountId::from([1u8; 32]);
pub const UpdaterAccount: AccountId = AccountId::from([2u8; 32]);
@ -73,14 +93,15 @@ ord_parameter_types! {
impl ghost_networks::Config for Test {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type NetworkId = u32;
type RegisterOrigin = EnsureSignedBy::<RegistererAccount, AccountId>;
type UpdateOrigin = EnsureSignedBy::<UpdaterAccount, AccountId>;
type RemoveOrigin = EnsureSignedBy::<RemoverAccount, AccountId>;
type RegisterOrigin = EnsureSignedBy<RegistererAccount, AccountId>;
type UpdateOrigin = EnsureSignedBy<UpdaterAccount, AccountId>;
type RemoveOrigin = EnsureSignedBy<RemoverAccount, AccountId>;
type WeightInfo = crate::weights::SubstrateWeight<Test>;
}
type Block = frame_system::mocking::MockBlockU32<Test>;
type Block = frame_system::mocking::MockBlock<Test>;
construct_runtime!(
pub enum Test {

1725
pallets/networks/src/tests.rs Executable file → Normal file

File diff suppressed because it is too large Load Diff

379
pallets/networks/src/weights.rs Executable file → Normal file
View File

@ -7,7 +7,7 @@
// Ghost Network 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
// 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
@ -15,14 +15,14 @@
//! Autogenerated weights for `ghost_networks`
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
//! DATE: 2023-11-29, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0
//! DATE: 2025-06-19, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! WORST CASE MAP SIZE: `1000000`
//! HOSTNAME: `ghost`, CPU: `Intel(R) Core(TM) i3-2310M CPU @ 2.10GHz`
//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("casper-dev"), DB CACHE: 1024
//! HOSTNAME: `ghostown`, CPU: `Intel(R) Core(TM) i3-2310M CPU @ 2.10GHz`
//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("casper-dev")`, DB CACHE: 1024
// Executed Command:
// ./target/production/ghost
// ./target/release/ghost
// benchmark
// pallet
// --chain=casper-dev
@ -30,8 +30,8 @@
// --repeat=20
// --pallet=ghost_networks
// --extrinsic=*
// --execution=wasm
// --wasm-execution=compiled
// --heap-pages=4096
// --header=./file_header.txt
// --output=./runtime/casper/src/weights/ghost_networks.rs
@ -53,7 +53,8 @@ pub trait WeightInfo {
fn update_network_name(n: u32, ) -> Weight;
fn update_network_endpoint(n: u32, ) -> Weight;
fn update_network_finality_delay() -> Weight;
fn update_network_release_delay() -> Weight;
fn update_network_rate_limit_delay() -> Weight;
fn update_network_block_distance() -> Weight;
fn update_network_type() -> Weight;
fn update_network_gatekeeper() -> Weight;
fn update_network_topic_name() -> Weight;
@ -65,260 +66,314 @@ pub trait WeightInfo {
/// Weight for ghost_networks using the Substrate node and recommended hardware.
pub struct SubstrateWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
/// The range of component `n` is `[1, 20]`.
/// The range of component `m` is `[1, 150]`.
fn register_network(_n: u32, _m: u32, ) -> Weight {
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// The range of component `i` is `[1, 20]`.
/// The range of component `j` is `[1, 150]`.
fn register_network(_i: u32, j: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `76`
// Estimated: `2551`
// Minimum execution time: 32_086 nanoseconds.
Weight::from_parts(33_092_855, 2551)
// Measured: `109`
// Estimated: `3574`
// Minimum execution time: 43_753_000 picoseconds.
Weight::from_parts(45_805_520, 0)
.saturating_add(Weight::from_parts(0, 3574))
// Standard Error: 412
.saturating_add(Weight::from_parts(1_586, 0).saturating_mul(j.into()))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// The range of component `n` is `[1, 20]`.
fn update_network_name(_n: u32, ) -> Weight {
fn update_network_name(n: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_496 nanoseconds.
Weight::from_parts(35_728_230, 2616)
// Standard Error: 2_591
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 49_412_000 picoseconds.
Weight::from_parts(50_617_210, 0)
.saturating_add(Weight::from_parts(0, 3766))
// Standard Error: 3_074
.saturating_add(Weight::from_parts(6_017, 0).saturating_mul(n.into()))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// The range of component `n` is `[1, 150]`.
fn update_network_endpoint(_n: u32, ) -> Weight {
fn update_network_endpoint(n: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_666 nanoseconds.
Weight::from_parts(35_959_961, 2616)
// Standard Error: 381
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 49_485_000 picoseconds.
Weight::from_parts(50_716_057, 0)
.saturating_add(Weight::from_parts(0, 3766))
// Standard Error: 453
.saturating_add(Weight::from_parts(4_916, 0).saturating_mul(n.into()))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_finality_delay() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 33_860 nanoseconds.
Weight::from_parts(34_995_000, 2616)
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 48_061_000 picoseconds.
Weight::from_parts(49_072_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
fn update_network_release_delay() -> Weight {
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_rate_limit_delay() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 33_860 nanoseconds.
Weight::from_parts(34_995_000, 2616)
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 49_066_000 picoseconds.
Weight::from_parts(52_137_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_block_distance() -> Weight {
// Proof Size summary in bytes:
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 48_085_000 picoseconds.
Weight::from_parts(48_838_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_type() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_976 nanoseconds.
Weight::from_parts(36_182_000, 2616)
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 47_872_000 picoseconds.
Weight::from_parts(48_972_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_gatekeeper() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_768 nanoseconds.
Weight::from_parts(35_580_000, 2616)
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 50_029_000 picoseconds.
Weight::from_parts(50_768_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_topic_name() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_768 nanoseconds.
Weight::from_parts(35_580_000, 2616)
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 50_151_000 picoseconds.
Weight::from_parts(51_573_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_incoming_network_fee() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_768 nanoseconds.
Weight::from_parts(35_580_000, 2616)
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 48_017_000 picoseconds.
Weight::from_parts(49_513_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_outgoing_network_fee() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_768 nanoseconds.
Weight::from_parts(35_580_000, 2616)
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 48_714_000 picoseconds.
Weight::from_parts(49_777_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn remove_network() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 33_336 nanoseconds.
Weight::from_parts(34_609_000, 2616)
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 44_583_000 picoseconds.
Weight::from_parts(45_681_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
}
impl WeightInfo for () {
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
/// The range of component `n` is `[1, 20]`.
/// The range of component `m` is `[1, 150]`.
fn register_network(_n: u32, _m: u32, ) -> Weight {
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// The range of component `i` is `[1, 20]`.
/// The range of component `j` is `[1, 150]`.
fn register_network(_i: u32, j: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `76`
// Estimated: `2551`
// Minimum execution time: 32_086 nanoseconds.
Weight::from_parts(33_092_855, 2551)
// Measured: `109`
// Estimated: `3574`
// Minimum execution time: 43_753_000 picoseconds.
Weight::from_parts(45_805_520, 0)
.saturating_add(Weight::from_parts(0, 3574))
// Standard Error: 412
.saturating_add(Weight::from_parts(1_586, 0).saturating_mul(j.into()))
.saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// The range of component `n` is `[1, 20]`.
fn update_network_name(_n: u32, ) -> Weight {
fn update_network_name(n: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_496 nanoseconds.
Weight::from_parts(35_728_230, 2616)
// Standard Error: 2_591
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 49_412_000 picoseconds.
Weight::from_parts(50_617_210, 0)
.saturating_add(Weight::from_parts(0, 3766))
// Standard Error: 3_074
.saturating_add(Weight::from_parts(6_017, 0).saturating_mul(n.into()))
.saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// The range of component `n` is `[1, 150]`.
fn update_network_endpoint(_n: u32, ) -> Weight {
fn update_network_endpoint(n: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_666 nanoseconds.
Weight::from_parts(35_959_961, 2616)
// Standard Error: 381
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 49_485_000 picoseconds.
Weight::from_parts(50_716_057, 0)
.saturating_add(Weight::from_parts(0, 3766))
// Standard Error: 453
.saturating_add(Weight::from_parts(4_916, 0).saturating_mul(n.into()))
.saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_finality_delay() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 33_860 nanoseconds.
Weight::from_parts(34_995_000, 2616)
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 48_061_000 picoseconds.
Weight::from_parts(49_072_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
fn update_network_release_delay() -> Weight {
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_rate_limit_delay() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 33_860 nanoseconds.
Weight::from_parts(34_995_000, 2616)
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 49_066_000 picoseconds.
Weight::from_parts(52_137_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_block_distance() -> Weight {
// Proof Size summary in bytes:
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 48_085_000 picoseconds.
Weight::from_parts(48_838_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_type() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_976 nanoseconds.
Weight::from_parts(36_182_000, 2616)
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 47_872_000 picoseconds.
Weight::from_parts(48_972_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_gatekeeper() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_768 nanoseconds.
Weight::from_parts(35_580_000, 2616)
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 50_029_000 picoseconds.
Weight::from_parts(50_768_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_topic_name() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_768 nanoseconds.
Weight::from_parts(35_580_000, 2616)
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 50_151_000 picoseconds.
Weight::from_parts(51_573_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_incoming_network_fee() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_768 nanoseconds.
Weight::from_parts(35_580_000, 2616)
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 48_017_000 picoseconds.
Weight::from_parts(49_513_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_outgoing_network_fee() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_768 nanoseconds.
Weight::from_parts(35_580_000, 2616)
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 48_714_000 picoseconds.
Weight::from_parts(49_777_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1))
}
/// Storage: GhostNetworks Networks (r:1 w:1)
/// Proof Skipped: GhostNetworks Networks (max_values: None, max_size: None, mode: Measured)
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn remove_network() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 33_336 nanoseconds.
Weight::from_parts(34_609_000, 2616)
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 44_583_000 picoseconds.
Weight::from_parts(45_681_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1))
}

9
pallets/slow-clap/Cargo.toml Executable file → Normal file
View File

@ -1,6 +1,6 @@
[package]
name = "ghost-slow-clap"
version = "0.3.15"
version = "0.3.33"
description = "Applause protocol for the EVM bridge"
license.workspace = true
authors.workspace = true
@ -27,11 +27,13 @@ sp-staking = { workspace = true }
sp-io = { workspace = true }
sp-std = { workspace = true }
pallet-balances = { workspace = true }
ghost-networks = { workspace = true }
[dev-dependencies]
pallet-session = { workspace = true, default-features = true }
pallet-balances = { workspace = true }
pallet-session = { workspace = true }
pallet-staking = { workspace = true }
pallet-staking-reward-curve = { workspace = true }
[features]
default = ["std"]
@ -49,6 +51,7 @@ std = [
"sp-io/std",
"sp-std/std",
"pallet-session/std",
"pallet-staking/std",
"pallet-balances/std",
"ghost-networks/std",
]

View File

@ -3,13 +3,8 @@
use super::*;
use frame_benchmarking::v1::*;
use frame_support::traits::fungible::Inspect;
use frame_system::RawOrigin;
use frame_support::traits::fungible::{Inspect, Mutate};
use crate::Pallet as SlowClap;
const MAX_CLAPS: u32 = 100;
const MAX_COMPANIONS: u32 = 20;
pub fn create_account<T: Config>() -> T::AccountId {
let account_bytes = Vec::from([1u8; 32]);
@ -17,184 +12,89 @@ pub fn create_account<T: Config>() -> T::AccountId {
.expect("32 bytes always construct an AccountId32")
}
pub fn create_companions<T: Config>(
total: usize,
network_id: NetworkIdOf<T>,
user_account: T::AccountId,
fee: H256,
receiver: H160,
) -> Result<CompanionId, &'static str> {
T::NetworkDataHandler::register(network_id.into(), NetworkData {
chain_name: "Ethereum".into(),
default_endpoint:
"https://base-mainnet.core.chainstack.com/2fc1de7f08c0465f6a28e3c355e0cb14/".into(),
finality_delay: Some(0),
release_delay: Some(0),
network_type: Default::default(),
gatekeeper: b"0x1234567891234567891234567891234567891234".to_vec(),
topic_name: b"0x12345678912345678912345678912345678912345678912345678912345678".to_vec(),
incoming_fee: 0,
outgoing_fee: 0,
}).map_err(|_| BenchmarkError::Weightless)?;
let mut last_companion_id = 0;
for _ in 0..total {
let minimum_balance = <<T as pallet::Config>::Currency>::minimum_balance();
let balance = minimum_balance + minimum_balance;
let companion = Companion::<NetworkIdOf::<T>, BalanceOf::<T>> {
network_id: network_id.into(), receiver,
fee, amount: balance,
};
let _ = <<T as pallet::Config>::Currency>::mint_into(&user_account, balance);
let companion_id = SlowClap::<T>::current_companion_id();
let _ = SlowClap::<T>::propose_companion(
RawOrigin::Signed(user_account.clone()).into(),
network_id,
companion,
)?;
last_companion_id = companion_id;
}
Ok(last_companion_id)
}
pub fn create_claps<T: Config>(i: u32, j: u32) -> Result<
(
Vec<crate::Clap<T::AccountId, NetworkIdOf<T>, BalanceOf<T>>>,
<T::AuthorityId as RuntimeAppPublic>::Signature,
),
&'static str,
> {
let minimum_balance = <<T as pallet::Config>::Currency>::minimum_balance();
let amount = minimum_balance + minimum_balance;
let total_amount = amount.saturating_mul(j.into());
let network_id = NetworkIdOf::<T>::default();
let mut claps = Vec::new();
let mut companions = BTreeMap::new();
let authorities = vec![T::AuthorityId::generate_pair(None)];
let bounded_authorities =
WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities.clone())
.map_err(|()| "more than the maximum number of keys provided")?;
Authorities::<T>::put(bounded_authorities);
for index in 0..j {
companions.insert(
index.into(),
amount,
);
}
for _ in 0..i {
claps.push(Clap {
session_index: 1,
authority_index: 0,
network_id,
transaction_hash: H256::repeat_byte(1u8),
block_number: 69,
removed: true,
receiver: create_account::<T>(),
amount: total_amount,
companions: companions.clone(),
});
}
let authority_id = authorities
.get(0usize)
.expect("first authority should exist");
let encoded_claps = claps.encode();
let signature = authority_id.sign(&encoded_claps)
.ok_or("couldn't make signature")?;
Ok((claps, signature))
}
benchmarks! {
slow_clap {
let k in 1 .. MAX_CLAPS;
let j in 1 .. MAX_COMPANIONS;
let receiver = H160::repeat_byte(69u8);
let fee = H256::repeat_byte(0u8);
let user_account: T::AccountId = whitelisted_caller();
let network_id = <<T as pallet::Config>::NetworkDataHandler as NetworkDataBasicHandler>::NetworkId::default();
let (claps, signature) = create_claps::<T>(k, j)?;
let _ = create_companions::<T>(j as usize, network_id, user_account, fee, receiver)?;
}: _(RawOrigin::None, claps, signature)
verify {
let minimum_balance = <<T as pallet::Config>::Currency>::minimum_balance();
let total_amount = (minimum_balance + minimum_balance).saturating_mul(j.into());
}
let receiver = create_account::<T>();
let amount = minimum_balance + minimum_balance;
let network_id = NetworkIdOf::<T>::default();
let session_index = T::ValidatorSet::session_index();
propose_companion {
let receiver = H160::repeat_byte(69u8);
let fee = H256::repeat_byte(0u8);
let user_account: T::AccountId = whitelisted_caller();
let network_id = <<T as pallet::Config>::NetworkDataHandler as NetworkDataBasicHandler>::NetworkId::default();
// T::NetworkDataHandler::register(network_id.into(), NetworkData {
// chain_name: "Ethereum".into(),
// // https://nd-422-757-666.p2pify.com/0a9d79d93fb2f4a4b1e04695da2b77a7/
// default_endpoint:
// "https://base-mainnet.core.chainstack.com/2fc1de7f08c0465f6a28e3c355e0cb14/".into(),
// finality_delay: Some(50),
// release_delay: Some(100),
// network_type: Default::default(),
// gatekeeper: b"0x1234567891234567891234567891234567891234".to_vec(),
// topic_name: b"0x12345678912345678912345678912345678912345678912345678912345678".to_vec(),
// incoming_fee: 0,
// outgoing_fee: 0,
// }).map_err(|_| BenchmarkError::Weightless)?;
let companion_id = create_companions::<T>(1, network_id, user_account.clone(), fee, receiver)?;
let companion_id = SlowClap::<T>::current_companion_id();
let minimum_balance = <<T as pallet::Config>::Currency>::minimum_balance();
let balance = minimum_balance + minimum_balance;
let companion = Companion::<NetworkIdOf::<T>, BalanceOf::<T>> {
network_id: network_id.into(), receiver,
fee, amount: balance,
let authorities = vec![T::AuthorityId::generate_pair(None)];
let bounded_authorities = WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities.clone())
.map_err(|()| "more than the maximum number of keys provided")?;
Authorities::<T>::set(&session_index, bounded_authorities);
let clap = Clap {
session_index: 0,
authority_index: 0,
transaction_hash: H256::repeat_byte(1u8),
block_number: 69,
removed: false,
network_id,
receiver: receiver.clone(),
amount,
};
let _ = <<T as pallet::Config>::Currency>::mint_into(&user_account, balance);
assert_eq!(SlowClap::<T>::current_companion_id(), companion_id);
}: _(RawOrigin::Signed(user_account), network_id.into(), companion)
let authority_id = authorities
.get(0usize)
.expect("first authority should exist");
let encoded_clap = clap.encode();
let signature = authority_id.sign(&encoded_clap)
.ok_or("couldn't make signature")?;
}: _(RawOrigin::None, clap, signature)
verify {
assert_eq!(SlowClap::<T>::current_companion_id(), companion_id + 1);
assert_eq!(<<T as pallet::Config>::Currency>::total_balance(&receiver), amount);
}
release_companion {
let receiver = H160::repeat_byte(69u8);
let fee = H256::repeat_byte(0u8);
let user_account: T::AccountId = whitelisted_caller();
let network_id = <<T as pallet::Config>::NetworkDataHandler as NetworkDataBasicHandler>::NetworkId::default();
let companion_id = create_companions::<T>(1, network_id, user_account.clone(), fee, receiver)?;
assert_eq!(SlowClap::<T>::release_blocks(companion_id), BlockNumberFor::<T>::default());
}: _(RawOrigin::Signed(user_account), network_id.into(), companion_id)
verify {
assert_ne!(SlowClap::<T>::release_blocks(companion_id), BlockNumberFor::<T>::default());
}
self_applause {
let session_index = T::ValidatorSet::session_index();
let authorities = vec![T::AuthorityId::generate_pair(None)];
let bounded_authorities = WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities.clone())
.map_err(|()| "more than the maximum number of keys provided")?;
Authorities::<T>::set(&session_index, bounded_authorities);
kill_companion {
let receiver = H160::repeat_byte(69u8);
let fee = H256::repeat_byte(0u8);
let user_account: T::AccountId = whitelisted_caller();
let network_id = <<T as pallet::Config>::NetworkDataHandler as NetworkDataBasicHandler>::NetworkId::default();
let companion_id = create_companions::<T>(1, network_id, user_account.clone(), fee, receiver)?;
SlowClap::<T>::release_companion(
RawOrigin::Signed(user_account.clone()).into(),
network_id,
companion_id,
)?;
let block_shift =
<<T as pallet::Config>::NetworkDataHandler as NetworkDataInspectHandler<NetworkData>>::get(&network_id)
.unwrap()
.release_delay
.unwrap();
frame_system::Pallet::<T>::set_block_number((block_shift + 1).saturated_into());
}: _(RawOrigin::Signed(user_account), network_id.into(), companion_id)
let minimum_balance = <<T as pallet::Config>::Currency>::minimum_balance();
let receiver = create_account::<T>();
let receiver_clone = receiver.clone();
let amount = minimum_balance + minimum_balance;
let network_id = NetworkIdOf::<T>::default();
let transaction_hash = H256::repeat_byte(1u8);
let unique_transaction_hash = <Pallet<T>>::generate_unique_hash(
&receiver,
&amount,
&network_id,
);
let storage_key = (session_index, &transaction_hash, &unique_transaction_hash);
<Pallet::<T>>::trigger_nullification_for_benchmark();
let clap = Clap {
session_index,
authority_index: 0,
transaction_hash,
block_number: 69,
removed: false,
network_id,
receiver: receiver.clone(),
amount,
};
let authority_id = authorities
.get(0usize)
.expect("first authority should exist");
let encoded_clap = clap.encode();
let signature = authority_id.sign(&encoded_clap).unwrap();
<Pallet<T>>::slow_clap(RawOrigin::None.into(), clap, signature)?;
<Pallet::<T>>::trigger_nullification_for_benchmark();
assert_eq!(<<T as pallet::Config>::Currency>::total_balance(&receiver), Default::default());
assert_eq!(ApplausesForTransaction::<T>::get(&storage_key), false);
}: _(RawOrigin::Signed(receiver_clone), network_id, session_index, transaction_hash, receiver_clone.clone(), amount)
verify {
assert_eq!(SlowClap::<T>::companions(network_id, companion_id), None);
assert_eq!(SlowClap::<T>::companion_details(companion_id), None);
assert_eq!(SlowClap::<T>::current_companion_id(), companion_id + 1);
assert_eq!(<<T as pallet::Config>::Currency>::total_balance(&receiver), amount);
assert_eq!(ApplausesForTransaction::<T>::get(&storage_key), true);
}
impl_benchmark_test_suite!(

View File

@ -0,0 +1,57 @@
use crate::{Deserialize, Deserializer, Vec, H256};
pub fn de_string_to_bytes<'de, D>(de: D) -> Result<Option<Vec<u8>>, D::Error>
where
D: Deserializer<'de>,
{
let s: &str = Deserialize::deserialize(de)?;
Ok(Some(s.as_bytes().to_vec()))
}
pub fn de_string_to_u64<'de, D>(de: D) -> Result<Option<u64>, D::Error>
where
D: Deserializer<'de>,
{
let s: &str = Deserialize::deserialize(de)?;
let s = if s.starts_with("0x") { &s[2..] } else { &s };
Ok(u64::from_str_radix(s, 16).ok())
}
pub fn de_string_to_u64_pure<'de, D>(de: D) -> Result<u64, D::Error>
where
D: Deserializer<'de>,
{
let s: &str = Deserialize::deserialize(de)?;
let s = if s.starts_with("0x") { &s[2..] } else { &s };
Ok(u64::from_str_radix(s, 16).unwrap_or_default())
}
pub fn de_string_to_h256<'de, D>(de: D) -> Result<Option<H256>, D::Error>
where
D: Deserializer<'de>,
{
let s: &str = Deserialize::deserialize(de)?;
let start_index = if s.starts_with("0x") { 2 } else { 0 };
let h256: Vec<_> = (start_index..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i + 2], 16).expect("valid u8 symbol; qed"))
.collect();
Ok(Some(H256::from_slice(&h256)))
}
pub fn de_string_to_vec_of_bytes<'de, D>(de: D) -> Result<Vec<Vec<u8>>, D::Error>
where
D: Deserializer<'de>,
{
let strings: Vec<&str> = Deserialize::deserialize(de)?;
Ok(strings
.iter()
.map(|s| {
let start_index = if s.starts_with("0x") { 2 } else { 0 };
(start_index..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i + 2], 16).expect("valid u8 symbol; qed"))
.collect::<Vec<u8>>()
})
.collect::<Vec<Vec<u8>>>())
}

View File

@ -0,0 +1,49 @@
use crate::{
deserialisations::{
de_string_to_bytes, de_string_to_h256, de_string_to_u64, de_string_to_u64_pure,
de_string_to_vec_of_bytes,
},
Decode, Deserialize, Encode, RuntimeDebug, Vec, H256,
};
const NUMBER_OF_TOPICS: usize = 3;
#[derive(RuntimeDebug, Clone, PartialEq, Deserialize, Encode, Decode)]
pub struct EvmResponse {
#[serde(default)]
id: Option<u32>,
#[serde(default, deserialize_with = "de_string_to_bytes")]
jsonrpc: Option<Vec<u8>>,
#[serde(default, deserialize_with = "de_string_to_bytes")]
pub error: Option<Vec<u8>>,
#[serde(default)]
pub result: Option<EvmResponseType>,
}
#[derive(RuntimeDebug, Clone, PartialEq, Deserialize, Encode, Decode)]
#[serde(untagged)]
pub enum EvmResponseType {
#[serde(deserialize_with = "de_string_to_u64_pure")]
BlockNumber(u64),
TransactionLogs(Vec<Log>),
}
#[derive(RuntimeDebug, Clone, Eq, PartialEq, Ord, PartialOrd, Deserialize, Encode, Decode)]
#[serde(rename_all = "camelCase")]
pub struct Log {
#[serde(default, deserialize_with = "de_string_to_h256")]
pub transaction_hash: Option<H256>,
#[serde(default, deserialize_with = "de_string_to_u64")]
pub block_number: Option<u64>,
#[serde(default, deserialize_with = "de_string_to_vec_of_bytes")]
pub topics: Vec<Vec<u8>>,
pub removed: bool,
}
impl Log {
pub fn is_sufficient(&self) -> bool {
self.transaction_hash.is_some()
&& self.block_number.is_some()
&& self.topics.len() == NUMBER_OF_TOPICS
}
}

1545
pallets/slow-clap/src/lib.rs Executable file → Normal file

File diff suppressed because it is too large Load Diff

View File

@ -4,20 +4,22 @@ use frame_support::{
derive_impl, parameter_types,
traits::{ConstU32, ConstU64},
weights::Weight,
PalletId,
};
use frame_system::EnsureRoot;
use pallet_session::historical as pallet_session_historical;
use sp_runtime::{
curve::PiecewiseLinear,
testing::{TestXt, UintAuthorityId},
traits::ConvertInto,
BuildStorage, Permill,
Permill,
};
use sp_staking::{
offence::{OffenceError, ReportOffence},
SessionIndex,
};
use sp_runtime::BuildStorage;
use crate as slow_clap;
use crate::Config;
@ -36,8 +38,8 @@ frame_support::construct_runtime!(
parameter_types! {
pub static Validators: Option<Vec<u64>> = Some(vec![
1,
2,
1,
2,
3,
]);
}
@ -53,13 +55,10 @@ impl pallet_session::SessionManager<u64> for TestSessionManager {
impl pallet_session::historical::SessionManager<u64, u64> for TestSessionManager {
fn new_session(_new_index: SessionIndex) -> Option<Vec<(u64, u64)>> {
Validators::mutate(|l| l
.take()
.map(|validators| validators
.iter()
.map(|v| (*v, *v))
.collect())
)
Validators::mutate(|l| {
l.take()
.map(|validators| validators.iter().map(|v| (*v, *v)).collect())
})
}
fn end_session(_: SessionIndex) {}
fn start_session(_: SessionIndex) {}
@ -84,24 +83,21 @@ impl ReportOffence<u64, IdentificationTuple, Offence> for OffenceHandler {
}
}
pub fn alice_account_id() -> <Runtime as frame_system::Config>::AccountId { 69 }
pub fn eve_account_id() -> <Runtime as frame_system::Config>::AccountId { 1337 }
pub fn new_test_ext() -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::<Runtime>::default()
let t = frame_system::GenesisConfig::<Runtime>::default()
.build_storage()
.unwrap();
pallet_balances::GenesisConfig::<Runtime> {
balances: vec![ (alice_account_id(), 100) ],
}
.assimilate_storage(&mut t)
.unwrap();
let mut result = sp_io::TestExternalities::new(t);
result.execute_with(|| {
System::set_block_number(1);
for i in 1..=3 {
System::inc_providers(&i);
assert_eq!(
Session::set_keys(RuntimeOrigin::signed(i), i.into(), vec![],),
Ok(())
);
}
});
result
@ -152,7 +148,7 @@ impl frame_support::traits::EstimateNextSessionRotation<u64> for TestNextSession
}
fn estimate_current_session_progress(now: u64) -> (Option<Permill>, Weight) {
let (estimate, weight) =
let (estimate, weight) =
pallet_session::PeriodicSessions::<Period, Offset>::estimate_current_session_progress(
now,
);
@ -167,6 +163,7 @@ impl frame_support::traits::EstimateNextSessionRotation<u64> for TestNextSession
impl ghost_networks::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type NetworkId = u32;
type RegisterOrigin = EnsureRoot<Self::AccountId>;
type UpdateOrigin = EnsureRoot<Self::AccountId>;
@ -174,9 +171,21 @@ impl ghost_networks::Config for Runtime {
type WeightInfo = ();
}
pallet_staking_reward_curve::build! {
const REWARD_CURVE: PiecewiseLinear<'static> = curve!(
min_inflation: 0_006_000,
max_inflation: 1_000_000,
ideal_stake: 0_690_000,
falloff: 0_050_000,
max_piece_count: 100,
test_precision: 0_005_000,
);
}
parameter_types! {
pub static ExistentialDeposit: u64 = 2;
pub const TreasuryPalletId: PalletId = PalletId(*b"mck/test");
pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE;
pub const HistoryDepth: u32 = 10;
}
#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)]
@ -199,23 +208,16 @@ impl Config for Runtime {
type ReportUnresponsiveness = OffenceHandler;
type MaxAuthorities = ConstU32<5>;
type MaxNumberOfClaps = ConstU32<100>;
type ApplauseThreshold = ConstU32<0>;
type MaxAuthorityInfoInSession = ConstU32<5_000>;
type OffenceThreshold = ConstU32<40>;
type ApplauseThreshold = ConstU32<50>;
type OffenceThreshold = ConstU32<75>;
type UnsignedPriority = ConstU64<{ 1 << 20 }>;
type TreasuryPalletId = TreasuryPalletId;
type HistoryDepth = HistoryDepth;
type WeightInfo = ();
}
pub type Extrinsic = TestXt<RuntimeCall, ()>;
// impl frame_system::offchain::SigningTypes for Runtime {
// type Public = <Signature as Verify>::Signer;
// type Signature = Signature;
// }
impl<LocalCall> frame_system::offchain::SendTransactionTypes<LocalCall> for Runtime
where
RuntimeCall: From<LocalCall>,
@ -224,30 +226,36 @@ where
type Extrinsic = Extrinsic;
}
// impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime
// where
// RuntimeCall: From<LocalCall>,
// {
// fn create_transaction<C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>>(
// call: Self::OverarchingCall,
// _public: Self::Public,
// _account: Self::AccountId,
// nonce: Self::Nonce,
// ) -> Option<(RuntimeCall, <Extrinsic as ExtrinsicT>::SignaturePayload)> {
// Some((call, (nonce.into(), ())))
// }
// }
pub fn advance_session() {
let now = System::block_number().max(1);
System::set_block_number(now + 1);
Session::rotate_session();
let session_index = Session::current_index();
// pub fn advance_session() {
// let now = System::block_number().max(1);
// System::set_block_number(now + 1);
// Session::rotate_session();
//
// let authorities = Session::validators()
// .into_iter()
// .map(UintAuthorityId)
// .collect();
//
// SlowClap::set_authorities(authorities);
// assert_eq!(Session::current_index(), (now / Period::get()) as u32);
// }
let authorities = Session::validators()
.into_iter()
.map(UintAuthorityId)
.collect();
SlowClap::set_test_authorities(session_index, authorities);
assert_eq!(session_index, (now / Period::get()) as u32);
}
pub fn advance_session_with_authority(authority: u64) {
let now = System::block_number().max(1);
System::set_block_number(now + 1);
Session::rotate_session();
let session_index = Session::current_index();
SlowClap::set_test_authorities(
session_index,
vec![
UintAuthorityId::from(authority),
UintAuthorityId::from(69),
UintAuthorityId::from(420),
UintAuthorityId::from(1337),
],
);
assert_eq!(session_index, (now / Period::get()) as u32);
}

File diff suppressed because it is too large Load Diff

View File

@ -1,18 +1,176 @@
use frame_support::weights::Weight;
// This file is part of Ghost Network.
// Ghost Network 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.
// Ghost Network 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 Ghost Network. If not, see <http://www.gnu.org/licenses/>.
//! Autogenerated weights for `ghost_slow_clap`
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0
//! DATE: 2025-06-19, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! WORST CASE MAP SIZE: `1000000`
//! HOSTNAME: `ghostown`, CPU: `Intel(R) Core(TM) i3-2310M CPU @ 2.10GHz`
//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("casper-dev")`, DB CACHE: 1024
// Executed Command:
// ./target/release/ghost
// benchmark
// pallet
// --chain=casper-dev
// --steps=50
// --repeat=20
// --pallet=ghost_slow_clap
// --extrinsic=*
// --wasm-execution=compiled
// --heap-pages=4096
// --header=./file_header.txt
// --output=./runtime/casper/src/weights/ghost_slow_clap.rs
#![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;
pub trait WeightInfo {
fn slow_clap(claps_len: u32, companions_len: u32) -> Weight;
fn propose_companion() -> Weight;
fn release_companion() -> Weight;
fn kill_companion() -> Weight;
fn slow_clap() -> Weight;
fn self_applause()-> Weight;
}
/// Weight functions for `ghost_slow_clap`.
pub struct SubstrateWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
/// Storage: `GhostSlowClaps::Authorities` (r:1 w:0)
/// Proof: `GhostSlowClaps::Authorities` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ReceivedClaps` (r:1 w:1)
/// Proof: `GhostSlowClaps::ReceivedClaps` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ClapsInSession` (r:1 w:1)
/// Proof: `GhostSlowClaps::ClapsInSession` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ApplausesForTransaction` (r:1 w:1)
/// Proof: `GhostSlowClaps::ApplausesForTransaction` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::NullifyNeeded` (r:1 w:0)
/// Proof: `GhostNetworks::NullifyNeeded` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::Networks` (r:1 w:0)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::GatekeeperAmount` (r:1 w:1)
/// Proof: `GhostNetworks::GatekeeperAmount` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::BridgedImbalance` (r:1 w:1)
/// Proof: `GhostNetworks::BridgedImbalance` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::AccumulatedCommission` (r:1 w:1)
/// Proof: `GhostNetworks::AccumulatedCommission` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `System::Account` (r:1 w:1)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
fn slow_clap() -> Weight {
// Proof Size summary in bytes:
// Measured: `355`
// Estimated: `3820`
// Minimum execution time: 213_817_000 picoseconds.
Weight::from_parts(216_977_000, 0)
.saturating_add(Weight::from_parts(0, 3820))
.saturating_add(T::DbWeight::get().reads(10))
.saturating_add(T::DbWeight::get().writes(7))
}
/// Storage: `GhostSlowClaps::ReceivedClaps` (r:1 w:0)
/// Proof: `GhostSlowClaps::ReceivedClaps` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::Authorities` (r:1 w:0)
/// Proof: `GhostSlowClaps::Authorities` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ApplausesForTransaction` (r:1 w:1)
/// Proof: `GhostSlowClaps::ApplausesForTransaction` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::NullifyNeeded` (r:1 w:0)
/// Proof: `GhostNetworks::NullifyNeeded` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::Networks` (r:1 w:0)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::GatekeeperAmount` (r:1 w:1)
/// Proof: `GhostNetworks::GatekeeperAmount` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::BridgedImbalance` (r:1 w:1)
/// Proof: `GhostNetworks::BridgedImbalance` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::AccumulatedCommission` (r:1 w:1)
/// Proof: `GhostNetworks::AccumulatedCommission` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `System::Account` (r:1 w:1)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
fn self_applause() -> Weight {
// Proof Size summary in bytes:
// Measured: `655`
// Estimated: `4120`
// Minimum execution time: 210_676_000 picoseconds.
Weight::from_parts(212_905_000, 0)
.saturating_add(Weight::from_parts(0, 4120))
.saturating_add(T::DbWeight::get().reads(9))
.saturating_add(T::DbWeight::get().writes(5))
}
}
impl WeightInfo for () {
fn slow_clap(
_claps_len: u32,
_companions_len: u32,
) -> Weight { Weight::zero() }
fn propose_companion() -> Weight { Weight::zero() }
fn release_companion() -> Weight { Weight::zero() }
fn kill_companion() -> Weight { Weight::zero() }
/// Storage: `GhostSlowClaps::Authorities` (r:1 w:0)
/// Proof: `GhostSlowClaps::Authorities` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ReceivedClaps` (r:1 w:1)
/// Proof: `GhostSlowClaps::ReceivedClaps` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ClapsInSession` (r:1 w:1)
/// Proof: `GhostSlowClaps::ClapsInSession` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ApplausesForTransaction` (r:1 w:1)
/// Proof: `GhostSlowClaps::ApplausesForTransaction` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::NullifyNeeded` (r:1 w:0)
/// Proof: `GhostNetworks::NullifyNeeded` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::Networks` (r:1 w:0)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::GatekeeperAmount` (r:1 w:1)
/// Proof: `GhostNetworks::GatekeeperAmount` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::BridgedImbalance` (r:1 w:1)
/// Proof: `GhostNetworks::BridgedImbalance` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::AccumulatedCommission` (r:1 w:1)
/// Proof: `GhostNetworks::AccumulatedCommission` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `System::Account` (r:1 w:1)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
fn slow_clap() -> Weight {
// Proof Size summary in bytes:
// Measured: `355`
// Estimated: `3820`
// Minimum execution time: 213_817_000 picoseconds.
Weight::from_parts(216_977_000, 0)
.saturating_add(Weight::from_parts(0, 3820))
.saturating_add(RocksDbWeight::get().reads(10))
.saturating_add(RocksDbWeight::get().writes(7))
}
/// Storage: `GhostSlowClaps::ReceivedClaps` (r:1 w:0)
/// Proof: `GhostSlowClaps::ReceivedClaps` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::Authorities` (r:1 w:0)
/// Proof: `GhostSlowClaps::Authorities` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ApplausesForTransaction` (r:1 w:1)
/// Proof: `GhostSlowClaps::ApplausesForTransaction` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::NullifyNeeded` (r:1 w:0)
/// Proof: `GhostNetworks::NullifyNeeded` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::Networks` (r:1 w:0)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::GatekeeperAmount` (r:1 w:1)
/// Proof: `GhostNetworks::GatekeeperAmount` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::BridgedImbalance` (r:1 w:1)
/// Proof: `GhostNetworks::BridgedImbalance` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::AccumulatedCommission` (r:1 w:1)
/// Proof: `GhostNetworks::AccumulatedCommission` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `System::Account` (r:1 w:1)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
fn self_applause() -> Weight {
// Proof Size summary in bytes:
// Measured: `655`
// Estimated: `4120`
// Minimum execution time: 210_676_000 picoseconds.
Weight::from_parts(212_905_000, 0)
.saturating_add(Weight::from_parts(0, 4120))
.saturating_add(RocksDbWeight::get().reads(9))
.saturating_add(RocksDbWeight::get().writes(5))
}
}

6
pallets/traits/Cargo.toml Executable file → Normal file
View File

@ -1,6 +1,6 @@
[package]
name = "ghost-traits"
version = "0.3.19"
version = "0.3.23"
license.workspace = true
authors.workspace = true
edition.workspace = true
@ -14,6 +14,6 @@ sp-runtime = { workspace = true }
[features]
default = ["std"]
std = [
"frame-support/std",
"sp-runtime/std",
"frame-support/std",
"sp-runtime/std",
]

0
pallets/traits/src/lib.rs Executable file → Normal file
View File

26
pallets/traits/src/networks.rs Executable file → Normal file
View File

@ -1,10 +1,7 @@
use frame_support::{
pallet_prelude::*,
storage::PrefixIterator,
};
use frame_support::{pallet_prelude::*, storage::PrefixIterator};
use sp_runtime::{
DispatchResult,
traits::{AtLeast32BitUnsigned, Member},
DispatchResult,
};
pub trait NetworkDataBasicHandler {
@ -21,9 +18,26 @@ pub trait NetworkDataBasicHandler {
pub trait NetworkDataInspectHandler<Network>: NetworkDataBasicHandler {
fn get(n: &Self::NetworkId) -> Option<Network>;
fn iter() -> PrefixIterator<(Self::NetworkId, Network)>;
fn is_nullification_period() -> bool;
}
pub trait NetworkDataMutateHandler<Network>: NetworkDataInspectHandler<Network> {
pub trait NetworkDataMutateHandler<Network, Balance>: NetworkDataInspectHandler<Network> {
fn register(chain_id: Self::NetworkId, network: Network) -> DispatchResult;
fn remove(chain_id: Self::NetworkId) -> DispatchResult;
fn increase_gatekeeper_amount(
chain_id: &Self::NetworkId,
amount: &Balance,
) -> Result<Balance, ()>;
fn decrease_gatekeeper_amount(
chain_id: &Self::NetworkId,
amount: &Balance,
) -> Result<Balance, ()>;
fn accumulate_outgoing_imbalance(amount: &Balance) -> Result<Balance, ()>;
fn accumulate_incoming_imbalance(amount: &Balance) -> Result<Balance, ()>;
fn accumulate_commission(commission: &Balance) -> Result<Balance, ()>;
fn nullify_commission();
fn trigger_nullification();
}

0
rpc/Cargo.toml Executable file → Normal file
View File

0
rpc/src/lib.rs Executable file → Normal file
View File

2
runtime/casper/Cargo.toml Executable file → Normal file
View File

@ -1,6 +1,6 @@
[package]
name = "casper-runtime"
version = "3.5.20"
version = "3.5.25"
build = "build.rs"
description = "Runtime of the Casper Network"
edition.workspace = true

0
runtime/casper/build.rs Executable file → Normal file
View File

0
runtime/casper/constants/Cargo.toml Executable file → Normal file
View File

0
runtime/casper/constants/src/lib.rs Executable file → Normal file
View File

2
runtime/casper/src/cult/mod.rs Executable file → Normal file
View File

@ -65,7 +65,7 @@ parameter_types! {
pub type CultReferendaInstance = pallet_referenda::Instance1;
impl pallet_referenda::Config<CultReferendaInstance> for Runtime {
type WeightInfo = ();
type WeightInfo = weights::pallet_referenda::WeightInfo<Runtime>;
type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type Scheduler = Scheduler;

0
runtime/casper/src/cult/origins.rs Executable file → Normal file
View File

0
runtime/casper/src/cult/tracks.rs Executable file → Normal file
View File

23
runtime/casper/src/lib.rs Executable file → Normal file
View File

@ -492,6 +492,8 @@ parameter_types! {
pub const OffendingValidatorsThreshold: Perbill = Perbill::from_percent(17);
pub const MaxNominations: u32 =
<NposCompactSolution16 as frame_election_provider_support::NposSolution>::LIMIT as u32;
pub const StakingHistoryDepth: u32 = 84;
pub const MaxUnlockingChunks: u32 = 32;
}
impl pallet_staking::Config for Runtime {
@ -520,8 +522,8 @@ impl pallet_staking::Config for Runtime {
type VoterList = VoterList;
type TargetList = UseValidatorsMap<Self>;
type NominationsQuota = pallet_staking::FixedNominationsQuota<{ MaxNominations::get() }>;
type MaxUnlockingChunks = frame_support::traits::ConstU32<32>;
type HistoryDepth = frame_support::traits::ConstU32<84>;
type MaxUnlockingChunks = MaxUnlockingChunks;
type HistoryDepth = StakingHistoryDepth;
type MaxControllersInDeprecationBatch = ConstU32<5314>;
type BenchmarkingConfig = runtime_common::StakingBenchmarkingConfig;
type EventListeners = NominationPools;
@ -1035,6 +1037,7 @@ impl pallet_alliance::Config for Runtime {
impl ghost_networks::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type NetworkId = u64;
type Currency = Balances;
type RegisterOrigin = EitherOf<
EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>,
@ -1073,14 +1076,13 @@ impl ghost_claims::Config<CultCollectiveInstance> for Runtime {
}
parameter_types! {
// maximum number of claps in one tx
pub MaxNumberOfClaps: u32 = 5;
// will be used in `Perbill::from_percent()`
pub ApplauseThreshold: u32 = 70;
pub const ApplauseThreshold: u32 = 70;
// will be used in `Perbill::from_percent()`
pub OffenceThreshold: u32 = 40;
pub const SlowClapUnsignedPriority: TransactionPriority =
TransactionPriority::max_value();
pub const OffenceThreshold: u32 = 40;
pub const SlowClapUnsignedPriority: TransactionPriority = TransactionPriority::MAX;
pub const SlowClapHistoryDepth: sp_staking::SessionIndex =
StakingHistoryDepth::get() * SessionsPerEra::get();
}
impl ghost_slow_clap::Config for Runtime {
@ -1095,13 +1097,10 @@ impl ghost_slow_clap::Config for Runtime {
type ReportUnresponsiveness = Offences;
type MaxAuthorities = MaxAuthorities;
type MaxNumberOfClaps = MaxNumberOfClaps;
type ApplauseThreshold = ApplauseThreshold;
type MaxAuthorityInfoInSession = MaxAuthorities;
type OffenceThreshold = OffenceThreshold;
type UnsignedPriority = SlowClapUnsignedPriority;
type TreasuryPalletId = TreasuryPalletId;
type HistoryDepth = SlowClapHistoryDepth;
type WeightInfo = weights::ghost_slow_clap::WeightInfo<Runtime>;
}

View File

@ -7,7 +7,7 @@
// Ghost Network 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
// 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
@ -16,7 +16,7 @@
//! Autogenerated weights for `ghost_networks`
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0
//! DATE: 2024-08-01, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! DATE: 2025-06-19, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! WORST CASE MAP SIZE: `1000000`
//! HOSTNAME: `ghostown`, CPU: `Intel(R) Core(TM) i3-2310M CPU @ 2.10GHz`
//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("casper-dev")`, DB CACHE: 1024
@ -50,30 +50,30 @@ impl<T: frame_system::Config> ghost_networks::WeightInfo for WeightInfo<T> {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// The range of component `i` is `[1, 20]`.
/// The range of component `j` is `[1, 150]`.
fn register_network(i: u32, j: u32, ) -> Weight {
fn register_network(_i: u32, j: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `109`
// Estimated: `3574`
// Minimum execution time: 44_464_000 picoseconds.
Weight::from_parts(44_802_179, 0)
// Minimum execution time: 43_753_000 picoseconds.
Weight::from_parts(45_805_520, 0)
.saturating_add(Weight::from_parts(0, 3574))
// Standard Error: 11_381
.saturating_add(Weight::from_parts(42_872, 0).saturating_mul(i.into()))
// Standard Error: 1_492
.saturating_add(Weight::from_parts(8_794, 0).saturating_mul(j.into()))
// Standard Error: 412
.saturating_add(Weight::from_parts(1_586, 0).saturating_mul(j.into()))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// The range of component `n` is `[1, 20]`.
fn update_network_name(_n: u32, ) -> Weight {
fn update_network_name(n: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `295`
// Estimated: `3760`
// Minimum execution time: 50_224_000 picoseconds.
Weight::from_parts(54_405_362, 0)
.saturating_add(Weight::from_parts(0, 3760))
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 49_412_000 picoseconds.
Weight::from_parts(50_617_210, 0)
.saturating_add(Weight::from_parts(0, 3766))
// Standard Error: 3_074
.saturating_add(Weight::from_parts(6_017, 0).saturating_mul(n.into()))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
@ -82,13 +82,13 @@ impl<T: frame_system::Config> ghost_networks::WeightInfo for WeightInfo<T> {
/// The range of component `n` is `[1, 150]`.
fn update_network_endpoint(n: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `295`
// Estimated: `3760`
// Minimum execution time: 50_598_000 picoseconds.
Weight::from_parts(54_951_352, 0)
.saturating_add(Weight::from_parts(0, 3760))
// Standard Error: 10_596
.saturating_add(Weight::from_parts(11_691, 0).saturating_mul(n.into()))
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 49_485_000 picoseconds.
Weight::from_parts(50_716_057, 0)
.saturating_add(Weight::from_parts(0, 3766))
// Standard Error: 453
.saturating_add(Weight::from_parts(4_916, 0).saturating_mul(n.into()))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
@ -96,23 +96,35 @@ impl<T: frame_system::Config> ghost_networks::WeightInfo for WeightInfo<T> {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_finality_delay() -> Weight {
// Proof Size summary in bytes:
// Measured: `295`
// Estimated: `3760`
// Minimum execution time: 49_089_000 picoseconds.
Weight::from_parts(50_797_000, 0)
.saturating_add(Weight::from_parts(0, 3760))
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 48_061_000 picoseconds.
Weight::from_parts(49_072_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_release_delay() -> Weight {
fn update_network_rate_limit_delay() -> Weight {
// Proof Size summary in bytes:
// Measured: `295`
// Estimated: `3760`
// Minimum execution time: 49_606_000 picoseconds.
Weight::from_parts(50_371_000, 0)
.saturating_add(Weight::from_parts(0, 3760))
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 49_066_000 picoseconds.
Weight::from_parts(52_137_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_block_distance() -> Weight {
// Proof Size summary in bytes:
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 48_085_000 picoseconds.
Weight::from_parts(48_838_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
@ -120,11 +132,11 @@ impl<T: frame_system::Config> ghost_networks::WeightInfo for WeightInfo<T> {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_type() -> Weight {
// Proof Size summary in bytes:
// Measured: `295`
// Estimated: `3760`
// Minimum execution time: 48_135_000 picoseconds.
Weight::from_parts(48_619_000, 0)
.saturating_add(Weight::from_parts(0, 3760))
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 47_872_000 picoseconds.
Weight::from_parts(48_972_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
@ -132,11 +144,11 @@ impl<T: frame_system::Config> ghost_networks::WeightInfo for WeightInfo<T> {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_gatekeeper() -> Weight {
// Proof Size summary in bytes:
// Measured: `295`
// Estimated: `3760`
// Minimum execution time: 50_027_000 picoseconds.
Weight::from_parts(51_212_000, 0)
.saturating_add(Weight::from_parts(0, 3760))
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 50_029_000 picoseconds.
Weight::from_parts(50_768_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
@ -144,11 +156,11 @@ impl<T: frame_system::Config> ghost_networks::WeightInfo for WeightInfo<T> {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_topic_name() -> Weight {
// Proof Size summary in bytes:
// Measured: `295`
// Estimated: `3760`
// Minimum execution time: 50_686_000 picoseconds.
Weight::from_parts(52_276_000, 0)
.saturating_add(Weight::from_parts(0, 3760))
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 50_151_000 picoseconds.
Weight::from_parts(51_573_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
@ -156,11 +168,11 @@ impl<T: frame_system::Config> ghost_networks::WeightInfo for WeightInfo<T> {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_incoming_network_fee() -> Weight {
// Proof Size summary in bytes:
// Measured: `295`
// Estimated: `3760`
// Minimum execution time: 48_485_000 picoseconds.
Weight::from_parts(49_672_000, 0)
.saturating_add(Weight::from_parts(0, 3760))
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 48_017_000 picoseconds.
Weight::from_parts(49_513_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
@ -168,11 +180,11 @@ impl<T: frame_system::Config> ghost_networks::WeightInfo for WeightInfo<T> {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_outgoing_network_fee() -> Weight {
// Proof Size summary in bytes:
// Measured: `295`
// Estimated: `3760`
// Minimum execution time: 48_926_000 picoseconds.
Weight::from_parts(49_482_000, 0)
.saturating_add(Weight::from_parts(0, 3760))
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 48_714_000 picoseconds.
Weight::from_parts(49_777_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
@ -180,11 +192,11 @@ impl<T: frame_system::Config> ghost_networks::WeightInfo for WeightInfo<T> {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn remove_network() -> Weight {
// Proof Size summary in bytes:
// Measured: `295`
// Estimated: `3760`
// Minimum execution time: 45_163_000 picoseconds.
Weight::from_parts(45_822_000, 0)
.saturating_add(Weight::from_parts(0, 3760))
// Measured: `301`
// Estimated: `3766`
// Minimum execution time: 44_583_000 picoseconds.
Weight::from_parts(45_681_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}

View File

@ -7,7 +7,7 @@
// Ghost Network 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
// 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
@ -16,7 +16,7 @@
//! Autogenerated weights for `ghost_slow_clap`
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0
//! DATE: 2024-08-02, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! DATE: 2025-06-19, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! WORST CASE MAP SIZE: `1000000`
//! HOSTNAME: `ghostown`, CPU: `Intel(R) Core(TM) i3-2310M CPU @ 2.10GHz`
//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("casper-dev")`, DB CACHE: 1024
@ -47,79 +47,61 @@ use core::marker::PhantomData;
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> ghost_slow_clap::WeightInfo for WeightInfo<T> {
/// Storage: `GhostSlowClaps::Authorities` (r:1 w:0)
/// Proof: `GhostSlowClaps::Authorities` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::AuthorityInfoInSession` (r:1 w:0)
/// Proof: `GhostSlowClaps::AuthorityInfoInSession` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ApplausesForTransaction` (r:1 w:0)
/// Proof: `GhostSlowClaps::Authorities` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ReceivedClaps` (r:1 w:1)
/// Proof: `GhostSlowClaps::ReceivedClaps` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ClapsInSession` (r:1 w:1)
/// Proof: `GhostSlowClaps::ClapsInSession` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ApplausesForTransaction` (r:1 w:1)
/// Proof: `GhostSlowClaps::ApplausesForTransaction` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::NullifyNeeded` (r:1 w:0)
/// Proof: `GhostNetworks::NullifyNeeded` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::Networks` (r:1 w:0)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::GatekeeperAmount` (r:1 w:1)
/// Proof: `GhostNetworks::GatekeeperAmount` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::BridgedImbalance` (r:1 w:1)
/// Proof: `GhostNetworks::BridgedImbalance` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::AccumulatedCommission` (r:1 w:1)
/// Proof: `GhostNetworks::AccumulatedCommission` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `System::Account` (r:1 w:1)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
fn slow_clap() -> Weight {
// Proof Size summary in bytes:
// Measured: `355`
// Estimated: `3820`
// Minimum execution time: 213_817_000 picoseconds.
Weight::from_parts(216_977_000, 0)
.saturating_add(Weight::from_parts(0, 3820))
.saturating_add(T::DbWeight::get().reads(10))
.saturating_add(T::DbWeight::get().writes(7))
}
/// Storage: `GhostSlowClaps::ReceivedClaps` (r:1 w:0)
/// Proof: `GhostSlowClaps::ReceivedClaps` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// The range of component `k` is `[1, 100]`.
/// The range of component `j` is `[1, 20]`.
fn slow_clap(k: u32, j: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `372 + j * (19 ±0)`
// Estimated: `3853 + j * (19 ±0)`
// Minimum execution time: 95_459_000 picoseconds.
Weight::from_parts(96_224_000, 0)
.saturating_add(Weight::from_parts(0, 3853))
// Standard Error: 152_014
.saturating_add(Weight::from_parts(32_092_278, 0).saturating_mul(k.into()))
// Standard Error: 761_228
.saturating_add(Weight::from_parts(22_412_712, 0).saturating_mul(j.into()))
.saturating_add(T::DbWeight::get().reads(4))
.saturating_add(Weight::from_parts(0, 19).saturating_mul(j.into()))
}
/// Storage: `GhostSlowClaps::CurrentCompanionId` (r:1 w:1)
/// Proof: `GhostSlowClaps::CurrentCompanionId` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::Authorities` (r:1 w:0)
/// Proof: `GhostSlowClaps::Authorities` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ApplausesForTransaction` (r:1 w:1)
/// Proof: `GhostSlowClaps::ApplausesForTransaction` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::NullifyNeeded` (r:1 w:0)
/// Proof: `GhostNetworks::NullifyNeeded` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::Networks` (r:1 w:0)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::Companions` (r:0 w:1)
/// Proof: `GhostSlowClaps::Companions` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::CompanionDetails` (r:0 w:1)
/// Proof: `GhostSlowClaps::CompanionDetails` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn propose_companion() -> Weight {
/// Storage: `GhostNetworks::GatekeeperAmount` (r:1 w:1)
/// Proof: `GhostNetworks::GatekeeperAmount` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::BridgedImbalance` (r:1 w:1)
/// Proof: `GhostNetworks::BridgedImbalance` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::AccumulatedCommission` (r:1 w:1)
/// Proof: `GhostNetworks::AccumulatedCommission` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `System::Account` (r:1 w:1)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
fn self_applause() -> Weight {
// Proof Size summary in bytes:
// Measured: `634`
// Estimated: `4099`
// Minimum execution time: 167_770_000 picoseconds.
Weight::from_parts(168_826_000, 0)
.saturating_add(Weight::from_parts(0, 4099))
.saturating_add(T::DbWeight::get().reads(2))
.saturating_add(T::DbWeight::get().writes(3))
}
/// Storage: `GhostSlowClaps::Companions` (r:1 w:0)
/// Proof: `GhostSlowClaps::Companions` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::Networks` (r:1 w:0)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::CompanionDetails` (r:1 w:0)
/// Proof: `GhostSlowClaps::CompanionDetails` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ReleaseBlocks` (r:0 w:1)
/// Proof: `GhostSlowClaps::ReleaseBlocks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn release_companion() -> Weight {
// Proof Size summary in bytes:
// Measured: `839`
// Estimated: `4304`
// Minimum execution time: 82_884_000 picoseconds.
Weight::from_parts(84_135_000, 0)
.saturating_add(Weight::from_parts(0, 4304))
.saturating_add(T::DbWeight::get().reads(3))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostSlowClaps::ReleaseBlocks` (r:1 w:0)
/// Proof: `GhostSlowClaps::ReleaseBlocks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::Companions` (r:1 w:1)
/// Proof: `GhostSlowClaps::Companions` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::CompanionDetails` (r:1 w:1)
/// Proof: `GhostSlowClaps::CompanionDetails` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn kill_companion() -> Weight {
// Proof Size summary in bytes:
// Measured: `514`
// Estimated: `3979`
// Minimum execution time: 152_418_000 picoseconds.
Weight::from_parts(153_436_000, 0)
.saturating_add(Weight::from_parts(0, 3979))
.saturating_add(T::DbWeight::get().reads(3))
.saturating_add(T::DbWeight::get().writes(2))
// Measured: `655`
// Estimated: `4120`
// Minimum execution time: 210_676_000 picoseconds.
Weight::from_parts(212_905_000, 0)
.saturating_add(Weight::from_parts(0, 4120))
.saturating_add(T::DbWeight::get().reads(9))
.saturating_add(T::DbWeight::get().writes(5))
}
}

View File

@ -17,7 +17,7 @@ pub mod pallet_nomination_pools;
pub mod pallet_preimage;
pub mod pallet_proxy;
pub mod pallet_ranked_collective;
// pub mod pallet_referenda;
pub mod pallet_referenda;
pub mod pallet_salary;
pub mod pallet_scheduler;
pub mod pallet_session;

48
runtime/common/Cargo.toml Executable file → Normal file
View File

@ -31,21 +31,21 @@ primitives = { workspace = true }
default = ["std"]
no_std = []
std = [
"sp-core/std",
"sp-std/std",
"sp-io/std",
"sp-core/std",
"sp-std/std",
"sp-io/std",
"sp-runtime/std",
"sp-staking/std",
"frame-support/std",
"frame-support/std",
"frame-system/std",
"pallet-authorship/std",
"pallet-balances/std",
"pallet-staking/std",
"pallet-staking-reward-fn/std",
"pallet-timestamp/std",
"pallet-transaction-payment/std",
"pallet-treasury/std",
"pallet-election-provider-multi-phase/std",
"pallet-authorship/std",
"pallet-balances/std",
"pallet-staking/std",
"pallet-staking-reward-fn/std",
"pallet-timestamp/std",
"pallet-transaction-payment/std",
"pallet-treasury/std",
"pallet-election-provider-multi-phase/std",
"primitives/std",
]
runtime-benchmarks = [
@ -53,21 +53,21 @@ runtime-benchmarks = [
"sp-staking/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"pallet-balances/runtime-benchmarks",
"pallet-staking/runtime-benchmarks",
"pallet-timestamp/runtime-benchmarks",
"pallet-treasury/runtime-benchmarks",
"pallet-election-provider-multi-phase/runtime-benchmarks",
"pallet-balances/runtime-benchmarks",
"pallet-staking/runtime-benchmarks",
"pallet-timestamp/runtime-benchmarks",
"pallet-treasury/runtime-benchmarks",
"pallet-election-provider-multi-phase/runtime-benchmarks",
]
try-runtime = [
"sp-runtime/try-runtime",
"frame-support/try-runtime",
"frame-system/try-runtime",
"pallet-authorship/try-runtime",
"pallet-balances/try-runtime",
"pallet-staking/try-runtime",
"pallet-timestamp/try-runtime",
"pallet-transaction-payment/try-runtime",
"pallet-treasury/try-runtime",
"pallet-election-provider-multi-phase/try-runtime",
"pallet-authorship/try-runtime",
"pallet-balances/try-runtime",
"pallet-staking/try-runtime",
"pallet-timestamp/try-runtime",
"pallet-transaction-payment/try-runtime",
"pallet-treasury/try-runtime",
"pallet-election-provider-multi-phase/try-runtime",
]

0
runtime/common/src/impls.rs Executable file → Normal file
View File

0
runtime/common/src/lib.rs Executable file → Normal file
View File

0
runtime/common/src/weights/block_weights.rs Executable file → Normal file
View File

0
runtime/common/src/weights/extrinsic.rs Executable file → Normal file
View File

0
runtime/common/src/weights/mod.rs Executable file → Normal file
View File

20
service/Cargo.toml Executable file → Normal file
View File

@ -107,16 +107,16 @@ default = ["db", "full-node"]
db = ["sc-service/rocksdb"]
full-node = ["kvdb-rocksdb", "parity-db"]
runtime-benchmarks = [
"frame-benchmarking-cli/runtime-benchmarks",
"frame-benchmarking/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"pallet-babe/runtime-benchmarks",
"pallet-staking/runtime-benchmarks",
"casper-runtime?/runtime-benchmarks",
"sc-client-db/runtime-benchmarks",
"sc-service/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
"frame-benchmarking-cli/runtime-benchmarks",
"frame-benchmarking/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"pallet-babe/runtime-benchmarks",
"pallet-staking/runtime-benchmarks",
"casper-runtime?/runtime-benchmarks",
"sc-client-db/runtime-benchmarks",
"sc-service/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
]
try-runtime = [
"frame-support/try-runtime",

10
service/src/chain_spec.rs Executable file → Normal file
View File

@ -177,8 +177,9 @@ fn casper_testnet_evm_networks() -> Vec<(u32, Vec<u8>)> {
(1, ghost_networks::NetworkData {
chain_name: "ethereum-mainnet".into(),
default_endpoint: "https://nd-422-757-666.p2pify.com/0a9d79d93fb2f4a4b1e04695da2b77a7/".into(),
finality_delay: Some(40u64),
release_delay: Some(80u64),
finality_delay: 40u64,
rate_limit_delay: 1_000u64,
block_distance: 50u64,
network_type: ghost_networks::NetworkType::Evm,
gatekeeper: "0x4d224452801aced8b2f0aebe155379bb5d594381".into(),
topic_name: "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef".into(),
@ -188,8 +189,9 @@ fn casper_testnet_evm_networks() -> Vec<(u32, Vec<u8>)> {
(56, ghost_networks::NetworkData {
chain_name: "bnb-mainnet".into(),
default_endpoint: "https://bsc-mainnet.core.chainstack.com/35848e183f3e3303c8cfeacbea831cab/".into(),
finality_delay: Some(20u64),
release_delay: Some(40u64),
finality_delay: 20u64,
rate_limit_delay: 1_000u64,
block_distance: 50u64,
network_type: ghost_networks::NetworkType::Evm,
gatekeeper: "0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82".into(),
topic_name: "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef".into(),

0
service/src/lib.rs Executable file → Normal file
View File

0
src/main.rs Executable file → Normal file
View File

0
tests/benchmark_block.rs Executable file → Normal file
View File

0
tests/benchmark_extrinsic.rs Executable file → Normal file
View File

0
tests/benchmark_overhead.rs Executable file → Normal file
View File

0
tests/benchmark_storage_works.rs Executable file → Normal file
View File

0
tests/common.rs Executable file → Normal file
View File

0
tests/invalid_order_arguments.rs Executable file → Normal file
View File

0
tests/purge_chain_works.rs Executable file → Normal file
View File

0
tests/running_the_node_and_interrupt.rs Executable file → Normal file
View File

0
utils/generate-bags/Cargo.toml Executable file → Normal file
View File

0
utils/generate-bags/src/main.rs Executable file → Normal file
View File

0
utils/ghostkey/Cargo.toml Executable file → Normal file
View File

0
utils/ghostkey/src/lib.rs Executable file → Normal file
View File

0
utils/ghostkey/src/main.rs Executable file → Normal file
View File

0
utils/staking-miner/Cargo.toml Executable file → Normal file
View File

View File

0
utils/staking-miner/src/main.rs Executable file → Normal file
View File

0
utils/staking-miner/tests/cli.rs Executable file → Normal file
View File