inital commit, which is clearly not initial

Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
This commit is contained in:
Uncle Stretch
2024-10-03 15:38:52 +03:00
commit 66719626bb
178 changed files with 41709 additions and 0 deletions

74
pallets/claims/Cargo.toml Normal file
View File

@@ -0,0 +1,74 @@
[package]
name = "ghost-claims"
version = "0.2.2"
description = "Ghost balance and rank claims based on EVM actions"
license.workspace = true
authors.workspace = true
edition.workspace = true
homepage.workspace = true
repository.workspace = true
[dependencies]
codec = { workspace = true, features = ["derive"] }
scale-info = { workspace = true, features = ["derive"] }
serde = { workspace = true }
serde_derive = { workspace = true }
rustc-hex = { workspace = true }
libsecp256k1 = { workspace = true, default-features = false }
frame-benchmarking = { workspace = true, optional = true }
frame-support = { workspace = true }
frame-system = { workspace = true }
pallet-ranked-collective = { workspace = true }
pallet-vesting = { workspace = true }
pallet-balances = { workspace = true }
sp-core = { features = ["serde"], workspace = true }
sp-runtime = { features = ["serde"], workspace = true }
sp-io = { workspace = true }
sp-std = { workspace = true }
[dev-dependencies]
hex-literal = { workspace = true, default-features = true }
libsecp256k1 = { workspace = true, default-features = true }
serde_json = { workspace = true, default-features = true }
[features]
default = ["std"]
std = [
"frame-benchmarking?/std",
"serde/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",
"pallet-ranked-collective/std",
"pallet-vesting/std",
"pallet-balances/std",
"rustc-hex/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",
]
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

@@ -0,0 +1,56 @@
#![cfg(feature = "runtime-benchmarks")]
use super::*;
use frame_benchmarking::v2::*;
#[instance_benchmarks]
mod benchmarks {
use super::*;
use pallet_ranked_collective::Pallet as Club;
use frame_support::dispatch::RawOrigin;
#[benchmark]
fn claim() {
let i = 1337u32;
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();
let pseudo_account: T::AccountId = Pallet::<T, I>::into_account_id(eth_address).unwrap();
let _ = CurrencyOf::<T, I>::deposit_creating(&pseudo_account, balance);
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 user_account: T::AccountId = account("user", i, 0);
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);
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),
_ => Some(pseudo_rank),
};
assert_eq!(Club::<T, I>::rank_of(&user_account), rank);
assert_eq!(Club::<T, I>::rank_of(&pseudo_account), None);
}
impl_benchmark_test_suite!(
Pallet,
crate::mock::new_test_ext(),
crate::mock::Test,
);
}

313
pallets/claims/src/lib.rs Normal file
View File

@@ -0,0 +1,313 @@
#![cfg_attr(not(feature = "std"), no_std)]
use frame_support::{
ensure, pallet_prelude::*,
traits::{
Currency, ExistenceRequirement, Get, RankedMembers,
RankedMembersSwapHandler, VestingSchedule,
},
DefaultNoBound,
};
use frame_system::pallet_prelude::*;
use serde::{self, Deserialize, Deserializer, Serialize, Serializer};
pub use pallet::*;
use sp_io::{crypto::secp256k1_ecdsa_recover, hashing::keccak_256};
use sp_runtime::traits::{CheckedSub, CheckedDiv, BlockNumberProvider};
use sp_std::prelude::*;
extern crate alloc;
#[cfg(not(feature = "std"))]
use alloc::{format, string::String};
pub mod weights;
pub use crate::weights::WeightInfo;
mod tests;
mod mock;
mod benchmarking;
mod secp_utils;
/// An ethereum address (i.e. 20 bytes, used to represent an Ethereum account).
///
/// This gets serialized to the 0x-prefixed hex representation.
#[derive(Clone, Copy, PartialEq, Eq, Encode, Decode, Default, RuntimeDebug, TypeInfo)]
pub struct EthereumAddress(pub [u8; 20]);
impl Serialize for EthereumAddress {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let hex: String = rustc_hex::ToHex::to_hex(&self.0[..]);
serializer.serialize_str(&format!("0x{}", hex))
}
}
impl<'de> Deserialize<'de> for EthereumAddress {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let base_string = String::deserialize(deserializer)?;
let offset = if base_string.starts_with("0x") { 2 } else { 0 };
let s = &base_string[offset..];
if s.len() != 40 {
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();
r.0.copy_from_slice(&raw);
Ok(r)
}
}
#[derive(Encode, Decode, Clone, TypeInfo)]
pub struct EcdsaSignature(pub [u8; 65]);
impl PartialEq for EcdsaSignature {
fn eq(&self, other: &Self) -> bool {
&self.0[..] == &other.0[..]
}
}
impl sp_std::fmt::Debug for EcdsaSignature {
fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result {
write!(f, "EcdsaSignature({:?})", &self.0[..])
}
}
type CurrencyOf<T, I> = <<T as Config<I>>::VestingSchedule as VestingSchedule<
<T as frame_system::Config>::AccountId
>>::Currency;
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;
#[frame_support::pallet]
pub mod pallet {
use super::*;
#[pallet::pallet]
#[pallet::without_storage_info]
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>;
type VestingSchedule: VestingSchedule<Self::AccountId, Moment = BlockNumberFor<Self>>;
type BlockNumberProvider: BlockNumberProvider<BlockNumber = BlockNumberFor<Self>>;
type MemberSwappedHandler: RankedMembersSwapHandler<AccountIdOf<Self, I>, RankOf<Self, I>>;
#[pallet::constant]
type Prefix: Get<&'static [u8]>;
#[pallet::constant]
type MaximumWithdrawAmount: Get<BalanceOf<Self, I>>;
#[pallet::constant]
type VestingBlocks: Get<u32>;
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,
amount: BalanceOf<T, I>,
rank: Option<RankOf<T, I>>,
},
}
#[pallet::error]
pub enum Error<T, I = ()> {
InvalidEthereumSignature,
InvalidEthereumAddress,
NoBalanceToClaim,
AddressDecodingFailed,
ArithmeticError,
PotUnderflow,
}
#[pallet::storage]
pub type Total<T: Config<I>, I: 'static = ()> = StorageValue<_, BalanceOf<T, I>, ValueQuery>;
#[pallet::genesis_config]
#[derive(DefaultNoBound)]
pub struct GenesisConfig<T: Config<I>, I: 'static = ()> {
pub total: BalanceOf<T, I>,
pub members_and_ranks: Vec<(T::AccountId, u16)>,
}
#[pallet::genesis_build]
impl<T: Config<I>, I: 'static> BuildGenesisConfig for GenesisConfig<T, I> {
fn build(&self) {
let cult_accounts: Vec<_> = self
.members_and_ranks
.iter()
.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
})
.collect();
assert!(
self.members_and_ranks.len() == cult_accounts.len(),
"duplicates in `members_and_ranks`"
);
Total::<T, I>::put(self.total);
}
}
#[pallet::call]
impl<T: Config<I>, I: 'static> Pallet<T, I> {
#[pallet::call_index(0)]
#[pallet::weight(<T as Config<I>>::WeightInfo::claim())]
pub fn claim(
origin: OriginFor<T>,
ethereum_address: EthereumAddress,
ethereum_signature: EcdsaSignature,
) -> 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)?;
ensure!(recovered_address == ethereum_address,
Error::<T, I>::InvalidEthereumAddress);
Self::do_claim(who, ethereum_address)
}
}
}
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
}
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
}
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)
}
fn into_account_id(address: EthereumAddress) -> Result<T::AccountId, codec::Error> {
let mut data = [0u8; 32];
data[0..4].copy_from_slice(b"evm:");
data[4..24].copy_from_slice(&address.0[..]);
let hash = sp_core::keccak_256(&data);
T::AccountId::decode(&mut &hash[..])
}
fn do_claim(receiver: T::AccountId, ethereum_address: EthereumAddress) -> DispatchResult {
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);
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,
ExistenceRequirement::AllowDeath,
)?;
let max_amount = T::MaximumWithdrawAmount::get();
if balance_due > max_amount {
let vesting_balance = balance_due
.checked_sub(&max_amount)
.ok_or(Error::<T, I>::ArithmeticError)?;
let vesting_blocks = T::VestingBlocks::get();
let per_block_balance = vesting_balance
.checked_div(&vesting_blocks.into())
.ok_or(Error::<T, I>::ArithmeticError)?;
T::VestingSchedule::add_vesting_schedule(
&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) {
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)?;
}
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 {
None
};
Total::<T, I>::put(new_total);
Self::deposit_event(Event::<T, I>::Claimed {
receiver,
donor,
amount: balance_due,
rank,
});
Ok(())
}
}

221
pallets/claims/src/mock.rs Normal file
View File

@@ -0,0 +1,221 @@
#![cfg(test)]
use super::*;
pub use crate as ghost_claims;
use frame_support::{
parameter_types, derive_impl,
traits::{PollStatus, Polling, WithdrawReasons, ConstU16, ConstU64},
};
use frame_system::EnsureRootWithSuccess;
use sp_runtime::{BuildStorage, traits::Convert};
pub use pallet_ranked_collective::{TallyOf, Rank};
pub mod eth_keys {
use crate::{
mock::Test,
EcdsaSignature, EthereumAddress,
};
use hex_literal::hex;
use codec::Encode;
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")) }
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_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()) }
}
#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
impl frame_system::Config for Test {
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
type Block = Block;
type RuntimeEvent = RuntimeEvent;
type AccountData = pallet_balances::AccountData<u64>;
type MaxConsumers = frame_support::traits::ConstU32<16>;
}
#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)]
impl pallet_balances::Config for Test {
type AccountStore = System;
}
parameter_types! {
pub const MinVestedTransfer: u64 = 1;
pub UnvestedFundsAllowedWithdrawReasons: WithdrawReasons =
WithdrawReasons::except(WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE);
}
impl pallet_vesting::Config for Test {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type BlockNumberToBalance = sp_runtime::traits::ConvertInto;
type MinVestedTransfer = MinVestedTransfer;
type WeightInfo = ();
type UnvestedFundsAllowedWithdrawReasons =
UnvestedFundsAllowedWithdrawReasons;
type BlockNumberProvider = System;
const MAX_VESTING_SCHEDULES: u32 = 28;
}
parameter_types! {
pub MinRankOfClassDelta: Rank = 1;
}
pub struct MinRankOfClass<Delta>(sp_std::marker::PhantomData<Delta>);
impl<Delta: Get<Rank>> Convert<Class, Rank> for MinRankOfClass<Delta> {
fn convert(a: Class) -> Rank {
a.saturating_sub(Delta::get())
}
}
pub struct TestPolls;
impl Polling<TallyOf<Test>> for TestPolls {
type Index = u8;
type Votes = u32;
type Moment = u64;
type Class = Class;
fn classes() -> Vec<Self::Class> {
unimplemented!()
}
fn as_ongoing(_index: u8) -> Option<(TallyOf<Test>, Self::Class)> {
unimplemented!()
}
fn access_poll<R>(
_index: Self::Index,
_f: impl FnOnce(PollStatus<&mut TallyOf<Test>, Self::Moment, Self::Class>) -> R,
) -> R {
unimplemented!()
}
fn try_access_poll<R>(
_index: Self::Index,
_f: impl FnOnce(
PollStatus<&mut TallyOf<Test>, Self::Moment, Self::Class>,
) -> Result<R, DispatchError>,
) -> Result<R, DispatchError> {
unimplemented!()
}
#[cfg(feature = "runtime-benchmarks")]
fn create_ongoing(_class: Self::Class) -> Result<Self::Index, ()> {
unimplemented!()
}
#[cfg(feature = "runtime-benchmarks")]
fn end_ongoing(_index: Self::Index, _approved: bool) -> Result<(), ()> {
unimplemented!()
}
}
impl pallet_ranked_collective::Config for Test {
type WeightInfo = ();
type RuntimeEvent = RuntimeEvent;
type AddOrigin = EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>;
type RemoveOrigin = EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>;
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>;
type VoteWeight = pallet_ranked_collective::Geometric;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkSetup = ();
}
parameter_types! {
pub Prefix: &'static [u8] = b"AccountId:";
}
impl Config for Test {
type RuntimeEvent = RuntimeEvent;
type VestingSchedule = Vesting;
type BlockNumberProvider = System;
type MemberSwappedHandler = ();
type Prefix = Prefix;
type MaximumWithdrawAmount = ConstU64<200>;
type VestingBlocks = ConstU32<80>;
type WeightInfo = ();
}
type Block = frame_system::mocking::MockBlock<Test>;
type Class = Rank;
frame_support::construct_runtime!(
pub enum Test
{
System: frame_system,
Balances: pallet_balances,
Vesting: pallet_vesting,
Club: pallet_ranked_collective,
Claims: ghost_claims,
}
);
pub fn new_test_ext() -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::<Test>::default()
.build_storage()
.unwrap();
pallet_balances::GenesisConfig::<Test> {
balances: vec![
(crate::mock::eth_keys::first_account_id(), 10),
(crate::mock::eth_keys::second_account_id(), 100),
(crate::mock::eth_keys::third_account_id(), 1000),
],
}
.assimilate_storage(&mut t)
.unwrap();
ghost_claims::GenesisConfig::<Test> {
total: crate::mock::eth_keys::total_claims(),
members_and_ranks: vec![
(crate::mock::eth_keys::second_account_id(), 1),
(crate::mock::eth_keys::third_account_id(), 3),
],
}
.assimilate_storage(&mut t)
.unwrap();
let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(|| {
System::set_block_number(1);
});
ext
}

View File

@@ -0,0 +1,37 @@
#![cfg(any(test, feature = "runtime-benchmarks"))]
use crate::{keccak_256, Config, EcdsaSignature, EthereumAddress};
pub fn public(secret: &libsecp256k1::SecretKey) -> libsecp256k1::PublicKey {
libsecp256k1::PublicKey::from_secret_key(secret)
}
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
}
#[cfg(test)]
pub fn into_account_id<T: Config<I>, I: 'static>(address: EthereumAddress) -> T::AccountId {
super::Pallet::<T, I>::into_account_id(address).unwrap()
}
pub fn sig<T: Config<I>, I: 'static>(
secret: &libsecp256k1::SecretKey,
what: &[u8],
) -> EcdsaSignature {
let msg = keccak_256(&super::Pallet::<T, I>::ethereum_signable_message(
&crate::to_ascii_hex(what)[..],
));
let (sig, recovery_id) = libsecp256k1::sign(
&libsecp256k1::Message::parse(&msg),
secret,
);
let mut r = [0u8; 65];
r[0..64].copy_from_slice(&sig.serialize()[..]);
r[64] = recovery_id.serialize();
EcdsaSignature(r)
}

274
pallets/claims/src/tests.rs Normal file
View File

@@ -0,0 +1,274 @@
#![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::*;
#[test]
fn serde_works() {
let x = EthereumAddress(hex!["0123456789abcdef0123456789abcdef01234567"]);
let y = serde_json::to_string(&x).unwrap();
assert_eq!(y, "\"0x0123456789abcdef0123456789abcdef01234567\"");
let z: EthereumAddress = serde_json::from_str(&y).unwrap();
assert_eq!(x, z);
}
#[test]
fn known_eth_public_accounts_are_correct() {
assert_eq!(first_eth_public_key(), first_eth_public_known());
assert_eq!(second_eth_public_key(), second_eth_public_known());
assert_eq!(third_eth_public_key(), third_eth_public_known());
assert_eq!(fourth_eth_public_key(), fourth_eth_public_known());
}
#[test]
fn basic_setup_works() {
new_test_ext().execute_with(|| {
assert_eq!(Balances::usable_balance(&alice_account_id()), 0);
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());
});
}
#[test]
fn small_claiming_works() {
new_test_ext().execute_with(|| {
assert_ok!(Claims::claim(
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);
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!(Vesting::vesting_balance(&alice_account_id()), None);
assert_eq!(ghost_claims::Total::<Test, ()>::get(), total_claims() - 10);
})
}
#[test]
fn medium_claiming_works() {
new_test_ext().execute_with(|| {
assert_ok!(Claims::claim(
RuntimeOrigin::signed(alice_account_id()),
second_eth_public_key(),
second_signature(),
));
assert_eq!(Balances::usable_balance(&alice_account_id()), 100);
assert_eq!(Balances::usable_balance(&first_account_id()), 10);
assert_eq!(Balances::usable_balance(&second_account_id()), 0);
assert_eq!(Balances::usable_balance(&third_account_id()), 1000);
assert_eq!(Club::rank_of(&alice_account_id()), Some(1));
assert_eq!(Club::rank_of(&second_account_id()), None);
assert_eq!(Vesting::vesting_balance(&alice_account_id()), None);
assert_eq!(ghost_claims::Total::<Test, ()>::get(), total_claims() - 100);
})
}
#[test]
fn big_claiming_works() {
new_test_ext().execute_with(|| {
assert_ok!(Claims::claim(
RuntimeOrigin::signed(alice_account_id()),
third_eth_public_key(),
third_signature(),
));
assert_eq!(Balances::usable_balance(&alice_account_id()), 200);
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()), 0);
assert_eq!(Club::rank_of(&alice_account_id()), Some(3));
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_ok!(Balances::transfer_allow_death(
RuntimeOrigin::signed(alice_account_id()),
bob_account_id(),
200));
})
}
#[test]
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(),
));
assert_ok!(Claims::claim(
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(),
));
assert_eq!(Balances::usable_balance(&alice_account_id()), 310);
assert_eq!(Balances::usable_balance(&first_account_id()), 0);
assert_eq!(Balances::usable_balance(&second_account_id()), 0);
assert_eq!(Balances::usable_balance(&third_account_id()), 0);
assert_eq!(Club::rank_of(&alice_account_id()), Some(3));
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(), 0);
})
}
#[test]
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(),
));
assert_ok!(Claims::claim(
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(),
));
assert_eq!(Balances::usable_balance(&alice_account_id()), 310);
assert_eq!(Balances::usable_balance(&first_account_id()), 0);
assert_eq!(Balances::usable_balance(&second_account_id()), 0);
assert_eq!(Balances::usable_balance(&third_account_id()), 0);
assert_eq!(Club::rank_of(&alice_account_id()), Some(3));
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(), 0);
})
}
#[test]
fn cannot_claim_with_bad_signature() {
new_test_ext().execute_with(|| {
assert_err!(Claims::claim(
RuntimeOrigin::signed(alice_account_id()),
first_eth_public_key(),
wrong_signature()),
crate::Error::<Test>::InvalidEthereumAddress);
assert_eq!(Balances::usable_balance(&alice_account_id()), 0);
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());
})
}
#[test]
fn cannot_claim_with_wrong_address() {
new_test_ext().execute_with(|| {
assert_err!(Claims::claim(
RuntimeOrigin::signed(bob_account_id()),
first_eth_public_key(),
first_signature()),
crate::Error::<Test>::InvalidEthereumAddress);
assert_eq!(Balances::usable_balance(&bob_account_id()), 0);
assert_eq!(Balances::usable_balance(&alice_account_id()), 0);
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());
})
}
#[test]
fn cannot_claim_nothing() {
new_test_ext().execute_with(|| {
assert_err!(Claims::claim(
RuntimeOrigin::signed(bob_account_id()),
fourth_eth_public_key(),
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);
assert_eq!(ghost_claims::Total::<Test, ()>::get(), total_claims());
})
}
#[test]
fn event_emitted_during_claim() {
new_test_ext().execute_with(|| {
let account = third_account_id();
let amount = Balances::usable_balance(&account);
let rank = Club::rank_of(&account);
System::reset_events();
assert_eq!(System::event_count(), 0);
assert_ok!(Claims::claim(
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,
}));
})
}

View File

@@ -0,0 +1,9 @@
use frame_support::weights::Weight;
pub trait WeightInfo {
fn claim() -> Weight;
}
impl WeightInfo for () {
fn claim() -> Weight { Weight::zero() }
}

49
pallets/networks/Cargo.toml Executable file
View File

@@ -0,0 +1,49 @@
[package]
name = "ghost-networks"
license.workspace = true
authors.workspace = true
version.workspace = true
edition.workspace = true
homepage.workspace = true
repository.workspace = true
[dependencies]
scale-info = { workspace = true, features = ["derive"] }
codec = { workspace = true, features = ["max-encoded-len"] }
frame-benchmarking = { workspace = true, optional = true }
frame-support = { workspace = true }
frame-system = { 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 }
[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",
]
runtime-benchmarks = [
"frame-benchmarking/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
]
try-runtime = [
"frame-support/try-runtime",
"frame-system/try-runtime",
]

View File

@@ -0,0 +1,222 @@
#![cfg(feature = "runtime-benchmarks")]
use super::*;
use crate::Pallet as GhostNetworks;
use frame_benchmarking::v1::{benchmarks, BenchmarkError};
use sp_runtime::Saturating;
const MAX_NAME_LEN: u32 = 20;
const MAX_ENDPOINT_LEN: u32 = 150;
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) {
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); }
let mut topic_name = b"0x".to_vec();
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,
incoming_fee: 0,
outgoing_fee: 0,
};
(chain_id, network)
}
fn create_network<T: Config>(
chain_id: <T as module::Config>::NetworkId,
network: NetworkData,
) -> Result<Option<NetworkData>, BenchmarkError> {
let prev_network = match GhostNetworks::<T>::get(&chain_id) {
Some(net) => net,
None => {
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)?;
network
}
};
Ok(Some(prev_network))
}
benchmarks! {
register_network {
let i in 1 .. MAX_NAME_LEN;
let j in 1 .. MAX_ENDPOINT_LEN;
let (chain_id, network) = prepare_network::<T>(i, j);
let authority = T::RegisterOrigin::try_successful_origin()
.map_err(|_| BenchmarkError::Weightless)?;
let prev_network = GhostNetworks::<T>::networks(chain_id.clone());
}: _<T::RuntimeOrigin>(authority, chain_id.clone(), network.clone())
verify {
assert_last_event::<T>(Event::NetworkRegistered {
chain_id: chain_id.clone(), network,
}.into());
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
update_network_name {
let n in 1 .. MAX_NAME_LEN;
let name = sp_std::vec![0x42; n as usize];
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(), name.clone())
verify {
assert_last_event::<T>(Event::NetworkNameUpdated {
chain_id: chain_id.clone(), chain_name: name,
}.into());
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
update_network_endpoint {
let n in 1 .. MAX_ENDPOINT_LEN;
let endpoint = sp_std::vec![0x42; n as usize];
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(), endpoint.clone())
verify {
assert_last_event::<T>(Event::NetworkEndpointUpdated {
chain_id: chain_id.clone(), default_endpoint: endpoint,
}.into());
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
update_network_finality_delay {
let delay = Some(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)
verify {
assert_last_event::<T>(Event::NetworkFinalityDelayUpdated {
chain_id: chain_id.clone(), finality_delay: delay,
}.into());
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
update_network_release_delay {
let delay = Some(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)
verify {
assert_last_event::<T>(Event::NetworkReleaseDelayUpdated {
chain_id: chain_id.clone(), release_delay: delay,
}.into());
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
update_network_type {
let network_type = NetworkType::Utxo;
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(), network_type.clone())
verify {
assert_last_event::<T>(Event::NetworkTypeUpdated {
chain_id: chain_id.clone(), network_type: network_type.clone(),
}.into());
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
update_network_gatekeeper {
let mut gatekeeper = b"0x".to_vec();
for i in 0..40 { gatekeeper.push(i + 1); }
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(), gatekeeper.clone())
verify {
assert_last_event::<T>(Event::NetworkGatekeeperUpdated {
chain_id: chain_id.clone(), gatekeeper,
}.into());
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
update_network_topic_name {
let topic_name = b"0x9876543219876543219876543219876543219876543219876543219876543219".to_vec();
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(), topic_name.clone())
verify {
assert_last_event::<T>(Event::NetworkTopicNameUpdated {
chain_id: chain_id.clone(), topic_name,
}.into());
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
update_incoming_network_fee {
let incoming_fee = 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(), incoming_fee)
verify {
assert_last_event::<T>(Event::NetworkIncomingFeeUpdated {
chain_id: chain_id.clone(), incoming_fee,
}.into());
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
update_outgoing_network_fee {
let outgoing_fee = 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(), outgoing_fee)
verify {
assert_last_event::<T>(Event::NetworkOutgoingFeeUpdated {
chain_id: chain_id.clone(), outgoing_fee,
}.into());
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
remove_network {
let (chain_id, network) = prepare_network::<T>(1, 1);
let authority = T::RemoveOrigin::try_successful_origin()
.map_err(|_| BenchmarkError::Weightless)?;
let prev_network = create_network::<T>(chain_id.clone(), network.clone())?;
}: _<T::RuntimeOrigin>(authority, chain_id.clone())
verify {
assert_last_event::<T>(Event::NetworkRemoved {
chain_id: chain_id.clone(),
}.into());
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
impl_benchmark_test_suite!(GhostNetworks, crate::mock::ExtBuilder::build(), crate::mock::Test);
}

538
pallets/networks/src/lib.rs Executable file
View File

@@ -0,0 +1,538 @@
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::large_enum_variant)]
#![allow(clippy::too_many_arguments)]
use frame_support::{
pallet_prelude::*,
storage::PrefixIterator, traits::EnsureOrigin,
};
use frame_system::pallet_prelude::*;
use scale_info::TypeInfo;
use sp_runtime::{
traits::{AtLeast32BitUnsigned, Member},
DispatchResult,
};
use sp_std::prelude::*;
pub use ghost_traits::networks::{
NetworkDataBasicHandler, NetworkDataInspectHandler,
NetworkDataMutateHandler,
};
mod weights;
pub use module::*;
pub use crate::weights::WeightInfo;
#[cfg(any(feature = "runtime-benchmarks", test))]
mod benchmarking;
#[cfg(all(feature = "std", test))]
mod mock;
#[cfg(all(feature = "std", test))]
mod tests;
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub enum NetworkType {
Evm = 0,
Utxo = 1,
Undefined = 2,
}
impl Default for NetworkType {
fn default() -> Self { NetworkType::Evm }
}
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub struct NetworkData {
pub chain_name: Vec<u8>,
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 incoming_fee: u32,
pub outgoing_fee: u32,
}
#[frame_support::pallet]
pub mod module {
use super::*;
#[pallet::config]
pub trait Config: frame_system::Config {
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// The type used as a unique network id.
type NetworkId: Parameter
+ Member
+ Parameter
+ AtLeast32BitUnsigned
+ Default
+ Copy
+ Ord
+ TypeInfo
+ MaybeSerializeDeserialize
+ MaxEncodedLen;
/// The origin required to register new network.
type RegisterOrigin: EnsureOrigin<Self::RuntimeOrigin>;
/// The origin required to update network information.
type UpdateOrigin: EnsureOrigin<Self::RuntimeOrigin>;
/// The origin required to remove network.
type RemoveOrigin: EnsureOrigin<Self::RuntimeOrigin>;
/// Weight information for extrinsics in this module.
type WeightInfo: WeightInfo;
}
#[pallet::error]
pub enum Error<T> {
/// Network already registered.
NetworkAlreadyRegistered,
/// Network does not exist.
NetworkDoesNotExist,
/// Gatekeeper address length not 42 or prefix `0x` missed.
WrongGatekeeperAddress,
/// Topic name length not 66 or prefix `0x` missed.
WrongTopicName,
}
#[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 },
}
#[pallet::storage]
#[pallet::getter(fn networks)]
pub type Networks<T: Config> =
StorageMap<_, Twox64Concat, T::NetworkId, NetworkData, OptionQuery>;
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
pub networks: Vec<(T::NetworkId, Vec<u8>)>,
}
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
Self { networks: vec![] }
}
}
#[pallet::genesis_build]
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");
});
}
}
}
#[pallet::pallet]
#[pallet::without_storage_info]
pub struct Pallet<T>(PhantomData<T>);
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::call_index(0)]
#[pallet::weight(T::WeightInfo::register_network(
network.chain_name.len() as u32,
network.default_endpoint.len() as u32,
))]
pub fn register_network(
origin: OriginFor<T>,
chain_id: T::NetworkId,
network: NetworkData,
) -> DispatchResult {
T::RegisterOrigin::ensure_origin_or_root(origin)?;
Self::do_register_network(chain_id, network)
}
#[pallet::call_index(1)]
#[pallet::weight(T::WeightInfo::update_network_name(
chain_name.len() as u32,
))]
pub fn update_network_name(
origin: OriginFor<T>,
chain_id: T::NetworkId,
chain_name: Vec<u8>,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_name(
chain_id,
chain_name,
)
}
#[pallet::call_index(2)]
#[pallet::weight(T::WeightInfo::update_network_endpoint(
default_endpoint.len() as u32
))]
pub fn update_network_endpoint(
origin: OriginFor<T>,
chain_id: T::NetworkId,
default_endpoint: Vec<u8>,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_endpoint(
chain_id,
default_endpoint,
)
}
#[pallet::call_index(3)]
#[pallet::weight(T::WeightInfo::update_network_finality_delay())]
pub fn update_network_finality_delay(
origin: OriginFor<T>,
chain_id: T::NetworkId,
finality_delay: Option<u64>,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
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(
origin: OriginFor<T>,
chain_id: T::NetworkId,
release_delay: Option<u64>,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_release_delay(
chain_id,
release_delay,
)
}
#[pallet::call_index(5)]
#[pallet::weight(T::WeightInfo::update_network_type())]
pub fn update_network_type(
origin: OriginFor<T>,
chain_id: T::NetworkId,
network_type: NetworkType,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_type(
chain_id,
network_type,
)
}
#[pallet::call_index(6)]
#[pallet::weight(T::WeightInfo::update_network_gatekeeper())]
pub fn update_network_gatekeeper(
origin: OriginFor<T>,
chain_id: T::NetworkId,
gatekeeper: Vec<u8>,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_gatekeeper(
chain_id,
gatekeeper,
)
}
#[pallet::call_index(7)]
#[pallet::weight(T::WeightInfo::update_network_topic_name())]
pub fn update_network_topic_name(
origin: OriginFor<T>,
chain_id: T::NetworkId,
topic_name: Vec<u8>,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_topic_name(
chain_id,
topic_name,
)
}
#[pallet::call_index(8)]
#[pallet::weight(T::WeightInfo::update_incoming_network_fee())]
pub fn update_incoming_network_fee(
origin: OriginFor<T>,
chain_id: T::NetworkId,
incoming_fee: u32,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_incoming_network_fee(
chain_id,
incoming_fee,
)
}
#[pallet::call_index(9)]
#[pallet::weight(T::WeightInfo::update_outgoing_network_fee())]
pub fn update_outgoing_network_fee(
origin: OriginFor<T>,
chain_id: T::NetworkId,
outgoing_fee: u32,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_outgoing_network_fee(
chain_id,
outgoing_fee,
)
}
#[pallet::call_index(10)]
#[pallet::weight(T::WeightInfo::remove_network())]
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)
}
}
}
impl<T: Config> Pallet<T> {
/// Register a new network.
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);
*maybe_network = Some(network.clone());
Ok(())
})?;
Self::deposit_event(Event::<T>::NetworkRegistered { chain_id, network });
Ok(())
}
/// Remove existent network.
pub fn do_remove_network(chain_id: T::NetworkId) -> DispatchResult {
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist);
*maybe_network = None;
Ok(())
})?;
Self::deposit_event(Event::<T>::NetworkRemoved { chain_id });
Ok(())
}
/// Update existent network name.
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();
net.chain_name = chain_name.clone();
*maybe_network = Some(net.clone());
Ok(())
})?;
Self::deposit_event(Event::<T>::NetworkNameUpdated {
chain_id,
chain_name,
});
Ok(())
}
/// Update existent network default endpoint.
pub fn do_update_network_endpoint(
chain_id: T::NetworkId,
default_endpoint: 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();
net.default_endpoint = default_endpoint.clone();
*maybe_network = Some(net.clone());
Ok(())
})?;
Self::deposit_event(Event::<T>::NetworkEndpointUpdated {
chain_id,
default_endpoint,
});
Ok(())
}
/// Update existent network default endpoint.
pub fn do_update_network_finality_delay(
chain_id: T::NetworkId,
finality_delay: Option<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.finality_delay = finality_delay;
*maybe_network = Some(net.clone());
Ok(())
})?;
Self::deposit_event(Event::<T>::NetworkFinalityDelayUpdated {
chain_id,
finality_delay,
});
Ok(())
}
/// Update existent network default endpoint.
pub fn do_update_network_release_delay(
chain_id: T::NetworkId,
release_delay: Option<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;
*maybe_network = Some(net.clone());
Ok(())
})?;
Self::deposit_event(Event::<T>::NetworkReleaseDelayUpdated {
chain_id,
release_delay,
});
Ok(())
}
/// Update existent network type.
pub fn do_update_network_type(
chain_id: T::NetworkId,
network_type: NetworkType,
) -> 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.network_type = network_type.clone();
*maybe_network = Some(net.clone());
Ok(())
})?;
Self::deposit_event(Event::<T>::NetworkTypeUpdated {
chain_id,
network_type,
});
Ok(())
}
/// Update existent network gatekeeper.
pub fn do_update_network_gatekeeper(
chain_id: T::NetworkId,
gatekeeper: Vec<u8>,
) -> DispatchResult {
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();
net.gatekeeper = gatekeeper.clone();
*maybe_network = Some(net.clone());
Ok(())
})?;
Self::deposit_event(Event::<T>::NetworkGatekeeperUpdated {
chain_id,
gatekeeper,
});
Ok(())
}
/// Update existent network gatekeeper's topic name.
pub fn do_update_network_topic_name(
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);
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.topic_name = topic_name.clone();
*maybe_network = Some(net.clone());
Ok(())
})?;
Self::deposit_event(Event::<T>::NetworkTopicNameUpdated {
chain_id,
topic_name,
});
Ok(())
}
pub fn do_update_incoming_network_fee(
chain_id: T::NetworkId,
incoming_fee: u32,
) -> 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.incoming_fee = incoming_fee.clone();
*maybe_network = Some(net.clone());
Ok(())
})?;
Self::deposit_event(Event::<T>::NetworkIncomingFeeUpdated {
chain_id,
incoming_fee,
});
Ok(())
}
pub fn do_update_outgoing_network_fee(
chain_id: T::NetworkId,
outgoing_fee: u32,
) -> 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.outgoing_fee = outgoing_fee.clone();
*maybe_network = Some(net.clone());
Ok(())
})?;
Self::deposit_event(Event::<T>::NetworkOutgoingFeeUpdated {
chain_id,
outgoing_fee,
});
Ok(())
}
}
impl<T: Config> NetworkDataBasicHandler for Pallet<T> {
type NetworkId = T::NetworkId;
}
impl<T: Config> NetworkDataInspectHandler<NetworkData> for Pallet<T> {
fn get(n: &Self::NetworkId) -> Option<NetworkData> {
Networks::<T>::get(n)
}
fn iter() -> PrefixIterator<(Self::NetworkId, NetworkData)> {
Networks::<T>::iter()
}
}
impl<T: Config> NetworkDataMutateHandler<NetworkData> for Pallet<T> {
fn register(chain_id: Self::NetworkId, network: NetworkData) -> DispatchResult {
Self::do_register_network(chain_id, network)
}
fn remove(chain_id: Self::NetworkId) -> DispatchResult {
Self::do_remove_network(chain_id)
}
}

104
pallets/networks/src/mock.rs Executable file
View File

@@ -0,0 +1,104 @@
use crate as ghost_networks;
use frame_system::EnsureSignedBy;
use frame_support::{
construct_runtime, ord_parameter_types, parameter_types, traits::{ConstU128, ConstU32, Everything}
};
pub use primitives::{
AccountId, Balance, Nonce, BlockNumber, Hash,
ReserveIdentifier, FreezeIdentifier,
};
use sp_runtime::{
traits::{BlakeTwo256, AccountIdLookup},
BuildStorage,
};
parameter_types! {
pub const BlockHashCount: BlockNumber = 250;
}
impl frame_system::Config for Test {
type RuntimeEvent = RuntimeEvent;
type BaseCallFilter = Everything;
type BlockWeights = ();
type BlockLength = ();
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
type RuntimeTask = ();
type Nonce = Nonce;
type Hash = Hash;
type Hashing = BlakeTwo256;
type AccountId = AccountId;
type Lookup = AccountIdLookup<Self::AccountId, ()>;
type Block = Block;
type BlockHashCount = BlockHashCount;
type DbWeight = ();
type Version = ();
type PalletInfo = PalletInfo;
type AccountData = pallet_balances::AccountData<Balance>;
type OnNewAccount = ();
type OnKilledAccount = ();
type SystemWeightInfo = ();
type SS58Prefix = ();
type OnSetCode = ();
type MaxConsumers = ConstU32<16>;
type SingleBlockMigrations = ();
type MultiBlockMigrator = ();
type PreInherents = ();
type PostInherents = ();
type PostTransactions = ();
}
impl pallet_balances::Config for Test {
type RuntimeEvent = RuntimeEvent;
type RuntimeHoldReason = ();
type RuntimeFreezeReason = ();
type WeightInfo = ();
type Balance = Balance;
type DustRemoval = ();
type ExistentialDeposit = ConstU128<1>;
type AccountStore = System;
type ReserveIdentifier = ReserveIdentifier;
type FreezeIdentifier = FreezeIdentifier;
type MaxLocks = ();
type MaxReserves = ConstU32<50>;
type MaxFreezes = ConstU32<50>;
}
ord_parameter_types! {
pub const RegistererAccount: AccountId = AccountId::from([1u8; 32]);
pub const UpdaterAccount: AccountId = AccountId::from([2u8; 32]);
pub const RemoverAccount: AccountId = AccountId::from([3u8; 32]);
pub const RandomAccount: AccountId = AccountId::from([4u8; 32]);
}
impl ghost_networks::Config for Test {
type RuntimeEvent = RuntimeEvent;
type NetworkId = u32;
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>;
construct_runtime!(
pub enum Test {
System: frame_system,
Balances: pallet_balances,
GhostNetworks: ghost_networks,
}
);
pub(crate) struct ExtBuilder();
impl ExtBuilder {
pub(crate) fn build() -> sp_io::TestExternalities {
let t = frame_system::GenesisConfig::<Test>::default()
.build_storage()
.expect("Frame system builds valid default genesis config; qed");
let mut ext: sp_io::TestExternalities = t.into();
ext.execute_with(|| System::set_block_number(1));
ext
}
}

637
pallets/networks/src/tests.rs Executable file
View File

@@ -0,0 +1,637 @@
use mock::{
ExtBuilder, System, RegistererAccount, UpdaterAccount, RemoverAccount,
RandomAccount, GhostNetworks, Test, RuntimeEvent, RuntimeOrigin,
};
use frame_support::{assert_err, assert_ok};
use sp_runtime::DispatchError;
use super::*;
fn prepare_network_data() -> (u32, NetworkData) {
(1u32, NetworkData {
chain_name: "Ethereum".into(),
default_endpoint:
"https:://some-endpoint.my-server.com/v1/my-super-secret-key".into(),
finality_delay: Some(69),
release_delay: Some(69),
network_type: NetworkType::Evm,
gatekeeper: b"0x1234567891234567891234567891234567891234".to_vec(),
topic_name: b"0x12345678912345678912345678912345678912345678912345678912345678".to_vec(),
incoming_fee: 0,
outgoing_fee: 0,
})
}
fn register_and_check_network(chain_id: u32, network: NetworkData) {
assert_ok!(GhostNetworks::register_network(
RuntimeOrigin::signed(RegistererAccount::get()),
chain_id,
network.clone()));
assert_eq!(Networks::<Test>::get(chain_id), Some(network.clone()));
}
#[test]
fn could_add_network_from_authority() {
ExtBuilder::build()
.execute_with(|| {
let (chain_id, network) = prepare_network_data();
assert_eq!(Networks::<Test>::get(chain_id), None);
assert_ok!(GhostNetworks::register_network(
RuntimeOrigin::signed(RegistererAccount::get()),
chain_id,
network.clone(),
));
System::assert_last_event(RuntimeEvent::GhostNetworks(
crate::Event::NetworkRegistered {
chain_id, network: network.clone()
}));
assert_eq!(Networks::<Test>::get(chain_id), Some(network));
});
}
#[test]
fn could_not_add_network_from_random_account() {
ExtBuilder::build()
.execute_with(|| {
let (chain_id, network) = prepare_network_data();
assert_eq!(Networks::<Test>::get(chain_id), None);
assert_err!(GhostNetworks::register_network(
RuntimeOrigin::signed(RandomAccount::get()),
chain_id,
network.clone(),
), DispatchError::BadOrigin);
assert_err!(GhostNetworks::register_network(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id,
network.clone(),
), DispatchError::BadOrigin);
assert_err!(GhostNetworks::register_network(
RuntimeOrigin::signed(RemoverAccount::get()),
chain_id,
network,
), DispatchError::BadOrigin);
assert_eq!(Networks::<Test>::get(chain_id), None);
});
}
#[test]
fn could_update_network_name_from_authority_account() {
ExtBuilder::build()
.execute_with(|| {
let new_name = b"Polygon".to_vec();
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_ok!(GhostNetworks::update_network_name(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, new_name.clone()));
System::assert_last_event(RuntimeEvent::GhostNetworks(
crate::Event::NetworkNameUpdated {
chain_id,
chain_name: new_name.clone() }));
let mut final_network = network.clone();
final_network.chain_name = new_name;
assert_eq!(Networks::<Test>::get(chain_id), Some(final_network.clone()));
assert_ne!(network, final_network);
});
}
#[test]
fn could_update_network_endpoint_from_authority_account() {
ExtBuilder::build()
.execute_with(|| {
let new_endpoint = b"https:://google.com".to_vec();
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_ok!(GhostNetworks::update_network_endpoint(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, new_endpoint.clone()));
System::assert_last_event(RuntimeEvent::GhostNetworks(
crate::Event::NetworkEndpointUpdated {
chain_id,
default_endpoint: new_endpoint.clone() }));
let mut final_network = network.clone();
final_network.default_endpoint = new_endpoint;
assert_eq!(Networks::<Test>::get(chain_id), Some(final_network.clone()));
assert_ne!(network, final_network);
});
}
#[test]
fn could_update_network_finality_delay_from_authority_account() {
ExtBuilder::build()
.execute_with(|| {
let new_finality_delay = Some(1337);
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_ok!(GhostNetworks::update_network_finality_delay(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, new_finality_delay));
System::assert_last_event(RuntimeEvent::GhostNetworks(
crate::Event::NetworkFinalityDelayUpdated {
chain_id,
finality_delay: new_finality_delay }));
let mut final_network = network.clone();
final_network.finality_delay = new_finality_delay;
assert_eq!(Networks::<Test>::get(chain_id), Some(final_network.clone()));
assert_ne!(network, final_network);
});
}
#[test]
fn could_update_network_release_delay_from_authority_account() {
ExtBuilder::build()
.execute_with(|| {
let new_release_delay = Some(1337);
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_ok!(GhostNetworks::update_network_release_delay(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, new_release_delay));
System::assert_last_event(RuntimeEvent::GhostNetworks(
crate::Event::NetworkReleaseDelayUpdated {
chain_id,
release_delay: new_release_delay }));
let mut final_network = network.clone();
final_network.release_delay = new_release_delay;
assert_eq!(Networks::<Test>::get(chain_id), Some(final_network.clone()));
assert_ne!(network, final_network);
});
}
#[test]
fn could_update_network_type_from_authority_account() {
ExtBuilder::build()
.execute_with(|| {
let new_type = NetworkType::Utxo;
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_ok!(GhostNetworks::update_network_type(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, new_type.clone()));
System::assert_last_event(RuntimeEvent::GhostNetworks(
crate::Event::NetworkTypeUpdated {
chain_id,
network_type: new_type.clone() }));
let mut final_network = network.clone();
final_network.network_type = new_type;
assert_eq!(Networks::<Test>::get(chain_id), Some(final_network.clone()));
assert_ne!(network, final_network);
});
}
#[test]
fn could_update_network_gatekeeper_from_authority_account() {
ExtBuilder::build()
.execute_with(|| {
let new_gatekeeper = b"0x9876543219876543219876543219876543219876".to_vec();
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_ok!(GhostNetworks::update_network_gatekeeper(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, new_gatekeeper.clone()));
System::assert_last_event(RuntimeEvent::GhostNetworks(
crate::Event::NetworkGatekeeperUpdated {
chain_id,
gatekeeper: new_gatekeeper.clone() }));
let mut final_network = network.clone();
final_network.gatekeeper = new_gatekeeper;
assert_eq!(Networks::<Test>::get(chain_id), Some(final_network.clone()));
assert_ne!(network, final_network);
});
}
#[test]
fn could_update_network_topic_name_from_authority_account() {
ExtBuilder::build()
.execute_with(|| {
let new_topic_name = b"0x9876543219876543219876543219876543219876543219876543219876543219".to_vec();
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_ok!(GhostNetworks::update_network_topic_name(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, new_topic_name.clone()));
System::assert_last_event(RuntimeEvent::GhostNetworks(
crate::Event::NetworkTopicNameUpdated {
chain_id,
topic_name: new_topic_name.clone() }));
let mut final_network = network.clone();
final_network.topic_name = new_topic_name;
assert_eq!(Networks::<Test>::get(chain_id), Some(final_network.clone()));
assert_ne!(network, final_network);
});
}
#[test]
fn could_update_incoming_network_fee_from_authority_account() {
ExtBuilder::build()
.execute_with(|| {
let new_incoming_fee = 69;
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_ok!(GhostNetworks::update_incoming_network_fee(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, new_incoming_fee));
System::assert_last_event(RuntimeEvent::GhostNetworks(
crate::Event::NetworkIncomingFeeUpdated {
chain_id,
incoming_fee: new_incoming_fee }));
let mut final_network = network.clone();
final_network.incoming_fee = new_incoming_fee;
assert_eq!(Networks::<Test>::get(chain_id), Some(final_network.clone()));
assert_ne!(network, final_network);
});
}
#[test]
fn could_update_outgoing_network_fee_from_authority_account() {
ExtBuilder::build()
.execute_with(|| {
let new_outgoing_fee = 69;
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_ok!(GhostNetworks::update_outgoing_network_fee(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, new_outgoing_fee));
System::assert_last_event(RuntimeEvent::GhostNetworks(
crate::Event::NetworkOutgoingFeeUpdated {
chain_id,
outgoing_fee: new_outgoing_fee }));
let mut final_network = network.clone();
final_network.outgoing_fee = new_outgoing_fee;
assert_eq!(Networks::<Test>::get(chain_id), Some(final_network.clone()));
assert_ne!(network, final_network);
});
}
#[test]
fn could_not_update_network_name_from_random_account() {
ExtBuilder::build()
.execute_with(|| {
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_err!(GhostNetworks::update_network_name(
RuntimeOrigin::signed(RegistererAccount::get()),
chain_id, "Binance".into()),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_name(
RuntimeOrigin::signed(RemoverAccount::get()),
chain_id, "Binance".into()),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_name(
RuntimeOrigin::signed(RandomAccount::get()),
chain_id, "Binance".into()),
DispatchError::BadOrigin);
assert_eq!(Networks::<Test>::get(chain_id), Some(network));
});
}
#[test]
fn could_not_update_network_endpoint_from_random_account() {
ExtBuilder::build()
.execute_with(|| {
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_err!(GhostNetworks::update_network_endpoint(
RuntimeOrigin::signed(RegistererAccount::get()),
chain_id, "https:://google.com".into()),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_endpoint(
RuntimeOrigin::signed(RemoverAccount::get()),
chain_id, "https:://google.com".into()),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_endpoint(
RuntimeOrigin::signed(RandomAccount::get()),
chain_id, "https:://google.com".into()),
DispatchError::BadOrigin);
assert_eq!(Networks::<Test>::get(chain_id), Some(network));
});
}
#[test]
fn could_not_update_network_finality_delay_from_random_account() {
ExtBuilder::build()
.execute_with(|| {
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_err!(GhostNetworks::update_network_finality_delay(
RuntimeOrigin::signed(RegistererAccount::get()),
chain_id, Some(1337)),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_finality_delay(
RuntimeOrigin::signed(RemoverAccount::get()),
chain_id, Some(1337)),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_finality_delay(
RuntimeOrigin::signed(RandomAccount::get()),
chain_id, Some(1337)),
DispatchError::BadOrigin);
assert_eq!(Networks::<Test>::get(chain_id), Some(network));
});
}
#[test]
fn could_not_update_network_release_delay_from_random_account() {
ExtBuilder::build()
.execute_with(|| {
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_err!(GhostNetworks::update_network_release_delay(
RuntimeOrigin::signed(RegistererAccount::get()),
chain_id, Some(1337)),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_release_delay(
RuntimeOrigin::signed(RemoverAccount::get()),
chain_id, Some(1337)),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_release_delay(
RuntimeOrigin::signed(RandomAccount::get()),
chain_id, Some(1337)),
DispatchError::BadOrigin);
assert_eq!(Networks::<Test>::get(chain_id), Some(network));
});
}
#[test]
fn could_not_update_network_type_from_random_account() {
ExtBuilder::build()
.execute_with(|| {
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_err!(GhostNetworks::update_network_type(
RuntimeOrigin::signed(RegistererAccount::get()),
chain_id, NetworkType::Utxo),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_type(
RuntimeOrigin::signed(RemoverAccount::get()),
chain_id, NetworkType::Utxo),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_type(
RuntimeOrigin::signed(RandomAccount::get()),
chain_id, NetworkType::Utxo),
DispatchError::BadOrigin);
assert_eq!(Networks::<Test>::get(chain_id), Some(network));
});
}
#[test]
fn could_not_update_network_gatekeeper_from_random_account() {
ExtBuilder::build()
.execute_with(|| {
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_err!(GhostNetworks::update_network_gatekeeper(
RuntimeOrigin::signed(RegistererAccount::get()),
chain_id, b"0x9876543219876543219876543219876543219876".to_vec()),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_gatekeeper(
RuntimeOrigin::signed(RemoverAccount::get()),
chain_id, b"0x9876543219876543219876543219876543219876".to_vec()),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_gatekeeper(
RuntimeOrigin::signed(RandomAccount::get()),
chain_id, b"0x9876543219876543219876543219876543219876".to_vec()),
DispatchError::BadOrigin);
assert_eq!(Networks::<Test>::get(chain_id), Some(network));
});
}
#[test]
fn could_not_update_network_topic_name_from_random_account() {
ExtBuilder::build()
.execute_with(|| {
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_err!(GhostNetworks::update_network_topic_name(
RuntimeOrigin::signed(RegistererAccount::get()),
chain_id, b"0x9876543219876543219876543219876543219876543219876543219876543219".to_vec()),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_topic_name(
RuntimeOrigin::signed(RemoverAccount::get()),
chain_id, b"0x9876543219876543219876543219876543219876543219876543219876543219".to_vec()),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_network_topic_name(
RuntimeOrigin::signed(RandomAccount::get()),
chain_id, b"0x9876543219876543219876543219876543219876543219876543219876543219".to_vec()),
DispatchError::BadOrigin);
assert_eq!(Networks::<Test>::get(chain_id), Some(network));
});
}
#[test]
fn could_not_update_network_incoming_fee_from_random_account() {
ExtBuilder::build()
.execute_with(|| {
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_err!(GhostNetworks::update_incoming_network_fee(
RuntimeOrigin::signed(RegistererAccount::get()),
chain_id, 69),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_incoming_network_fee(
RuntimeOrigin::signed(RemoverAccount::get()),
chain_id, 69),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_incoming_network_fee(
RuntimeOrigin::signed(RandomAccount::get()),
chain_id, 69),
DispatchError::BadOrigin);
assert_eq!(Networks::<Test>::get(chain_id), Some(network));
});
}
#[test]
fn could_not_update_network_outgoing_fee_from_random_account() {
ExtBuilder::build()
.execute_with(|| {
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_err!(GhostNetworks::update_outgoing_network_fee(
RuntimeOrigin::signed(RegistererAccount::get()),
chain_id, 69),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_outgoing_network_fee(
RuntimeOrigin::signed(RemoverAccount::get()),
chain_id, 69),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::update_outgoing_network_fee(
RuntimeOrigin::signed(RandomAccount::get()),
chain_id, 69),
DispatchError::BadOrigin);
assert_eq!(Networks::<Test>::get(chain_id), Some(network));
});
}
#[test]
fn could_not_update_name_for_non_existent_network() {
ExtBuilder::build()
.execute_with(|| {
let chain_id: u32 = 1;
assert_eq!(Networks::<Test>::get(chain_id), None);
assert_err!(GhostNetworks::update_network_name(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, "Binance".into()),
crate::Error::<Test>::NetworkDoesNotExist);
assert_eq!(Networks::<Test>::get(chain_id), None);
});
}
#[test]
fn could_not_update_endpoint_for_non_existent_network() {
ExtBuilder::build()
.execute_with(|| {
let chain_id: u32 = 1;
assert_eq!(Networks::<Test>::get(chain_id), None);
assert_err!(GhostNetworks::update_network_endpoint(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, "https:://google.com".into()),
crate::Error::<Test>::NetworkDoesNotExist);
assert_eq!(Networks::<Test>::get(chain_id), None);
});
}
#[test]
fn could_not_update_finality_delay_for_non_existent_network() {
ExtBuilder::build()
.execute_with(|| {
let chain_id: u32 = 1;
assert_eq!(Networks::<Test>::get(chain_id), None);
assert_err!(GhostNetworks::update_network_finality_delay(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, Some(1337)),
crate::Error::<Test>::NetworkDoesNotExist);
assert_eq!(Networks::<Test>::get(chain_id), None);
});
}
#[test]
fn could_not_update_release_delay_for_non_existent_network() {
ExtBuilder::build()
.execute_with(|| {
let chain_id: u32 = 1;
assert_eq!(Networks::<Test>::get(chain_id), None);
assert_err!(GhostNetworks::update_network_release_delay(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, Some(1337)),
crate::Error::<Test>::NetworkDoesNotExist);
assert_eq!(Networks::<Test>::get(chain_id), None);
});
}
#[test]
fn could_not_update_type_for_non_existent_network() {
ExtBuilder::build()
.execute_with(|| {
let chain_id: u32 = 1;
assert_eq!(Networks::<Test>::get(chain_id), None);
assert_err!(GhostNetworks::update_network_type(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, NetworkType::Utxo),
crate::Error::<Test>::NetworkDoesNotExist);
assert_eq!(Networks::<Test>::get(chain_id), None);
});
}
#[test]
fn could_not_update_gatekeeper_for_non_existent_network() {
ExtBuilder::build()
.execute_with(|| {
let chain_id: u32 = 1;
assert_eq!(Networks::<Test>::get(chain_id), None);
assert_err!(GhostNetworks::update_network_gatekeeper(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, b"0x9876543219876543219876543219876543219876".to_vec()),
crate::Error::<Test>::NetworkDoesNotExist);
assert_eq!(Networks::<Test>::get(chain_id), None);
});
}
#[test]
fn could_not_update_topic_name_for_non_existent_network() {
ExtBuilder::build()
.execute_with(|| {
let chain_id: u32 = 1;
assert_eq!(Networks::<Test>::get(chain_id), None);
assert_err!(GhostNetworks::update_network_topic_name(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, b"0x9876543219876543219876543219876543219876543219876543219876543219".to_vec()),
crate::Error::<Test>::NetworkDoesNotExist);
assert_eq!(Networks::<Test>::get(chain_id), None);
});
}
#[test]
fn could_not_update_incoming_fee_for_non_existent_network() {
ExtBuilder::build()
.execute_with(|| {
let chain_id: u32 = 1;
assert_eq!(Networks::<Test>::get(chain_id), None);
assert_err!(GhostNetworks::update_incoming_network_fee(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, 1337),
crate::Error::<Test>::NetworkDoesNotExist);
assert_eq!(Networks::<Test>::get(chain_id), None);
});
}
#[test]
fn could_not_update_outgoing_fee_for_non_existent_network() {
ExtBuilder::build()
.execute_with(|| {
let chain_id: u32 = 1;
assert_eq!(Networks::<Test>::get(chain_id), None);
assert_err!(GhostNetworks::update_outgoing_network_fee(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id, 1337),
crate::Error::<Test>::NetworkDoesNotExist);
assert_eq!(Networks::<Test>::get(chain_id), None);
});
}
#[test]
fn could_remove_network_from_authority_account() {
ExtBuilder::build()
.execute_with(|| {
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_ok!(GhostNetworks::remove_network(
RuntimeOrigin::signed(RemoverAccount::get()),
chain_id,
));
assert_eq!(Networks::<Test>::get(chain_id), None);
});
}
#[test]
fn could_not_remove_network_from_random_account() {
ExtBuilder::build()
.execute_with(|| {
let (chain_id, network) = prepare_network_data();
register_and_check_network(chain_id, network.clone());
assert_err!(GhostNetworks::remove_network(
RuntimeOrigin::signed(RegistererAccount::get()),
chain_id),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::remove_network(
RuntimeOrigin::signed(UpdaterAccount::get()),
chain_id),
DispatchError::BadOrigin);
assert_err!(GhostNetworks::remove_network(
RuntimeOrigin::signed(RandomAccount::get()),
chain_id),
DispatchError::BadOrigin);
assert_eq!(Networks::<Test>::get(chain_id), Some(network));
});
}
#[test]
fn could_not_remove_non_existent_network() {
ExtBuilder::build()
.execute_with(|| {
let chain_id: u32 = 1;
assert_eq!(Networks::<Test>::get(chain_id), None);
assert_err!(GhostNetworks::remove_network(
RuntimeOrigin::signed(RemoverAccount::get()),
chain_id),
crate::Error::<Test>::NetworkDoesNotExist);
assert_eq!(Networks::<Test>::get(chain_id), None);
});
}

325
pallets/networks/src/weights.rs Executable file
View File

@@ -0,0 +1,325 @@
// 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_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: `[]`
//! 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
// Executed Command:
// ./target/production/ghost
// benchmark
// pallet
// --chain=casper-dev
// --steps=50
// --repeat=20
// --pallet=ghost_networks
// --extrinsic=*
// --execution=wasm
// --wasm-execution=compiled
// --header=./file_header.txt
// --output=./runtime/casper/src/weights/ghost_networks.rs
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(unused_parens)]
#![allow(unused_imports)]
use frame_support::{
traits::Get,
weights::{
Weight, constants::RocksDbWeight
}
};
use sp_std::marker::PhantomData;
/// Weight functions needed for ghost_networks
pub trait WeightInfo {
fn register_network(n: u32, m: u32, ) -> Weight;
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_type() -> Weight;
fn update_network_gatekeeper() -> Weight;
fn update_network_topic_name() -> Weight;
fn update_incoming_network_fee() -> Weight;
fn update_outgoing_network_fee() -> Weight;
fn remove_network() -> Weight;
}
/// 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 {
// Proof Size summary in bytes:
// Measured: `76`
// Estimated: `2551`
// Minimum execution time: 32_086 nanoseconds.
Weight::from_parts(33_092_855, 2551)
.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)
/// The range of component `n` is `[1, 20]`.
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
.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)
/// The range of component `n` is `[1, 150]`.
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
.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_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)
.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 {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 33_860 nanoseconds.
Weight::from_parts(34_995_000, 2616)
.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_type() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_976 nanoseconds.
Weight::from_parts(36_182_000, 2616)
.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_gatekeeper() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_768 nanoseconds.
Weight::from_parts(35_580_000, 2616)
.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_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)
.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_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)
.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_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)
.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 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)
.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 {
// Proof Size summary in bytes:
// Measured: `76`
// Estimated: `2551`
// Minimum execution time: 32_086 nanoseconds.
Weight::from_parts(33_092_855, 2551)
.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)
/// The range of component `n` is `[1, 20]`.
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
.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)
/// The range of component `n` is `[1, 150]`.
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
.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_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)
.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 {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 33_860 nanoseconds.
Weight::from_parts(34_995_000, 2616)
.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_type() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_976 nanoseconds.
Weight::from_parts(36_182_000, 2616)
.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_gatekeeper() -> Weight {
// Proof Size summary in bytes:
// Measured: `141`
// Estimated: `2616`
// Minimum execution time: 34_768 nanoseconds.
Weight::from_parts(35_580_000, 2616)
.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_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)
.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_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)
.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_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)
.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 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)
.saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1))
}
}

71
pallets/slow-clap/Cargo.toml Executable file
View File

@@ -0,0 +1,71 @@
[package]
name = "ghost-slow-clap"
version = "0.3.14"
description = "Applause protocol for the EVM bridge"
license.workspace = true
authors.workspace = true
edition.workspace = true
homepage.workspace = true
repository.workspace = true
[dependencies]
codec = { workspace = true, features = ["max-encoded-len"] }
scale-info = { workspace = true, features = ["derive"] }
log = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true, features = ["alloc"] }
frame-benchmarking = { workspace = true, optional = true }
frame-support = { workspace = true }
frame-system = { workspace = true }
sp-application-crypto = { workspace = true }
sp-core = { workspace = true }
sp-runtime = { workspace = true }
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 }
[features]
default = ["std"]
std = [
"frame-benchmarking?/std",
"log/std",
"codec/std",
"scale-info/std",
"frame-support/std",
"frame-system/std",
"sp-application-crypto/std",
"sp-core/std",
"sp-runtime/std",
"sp-staking/std",
"sp-io/std",
"sp-std/std",
"pallet-session/std",
"pallet-balances/std",
"ghost-networks/std",
]
runtime-benchmarks = [
"frame-benchmarking/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
"sp-staking/runtime-benchmarks",
"pallet-balances/runtime-benchmarks",
"ghost-networks/runtime-benchmarks",
]
try-runtime = [
"frame-support/try-runtime",
"frame-system/try-runtime",
"sp-runtime/try-runtime",
"pallet-session/try-runtime",
"pallet-balances/try-runtime",
"ghost-networks/try-runtime",
]

View File

@@ -0,0 +1,205 @@
#![cfg(feature = "runtime-benchmarks")]
use super::*;
use frame_benchmarking::v1::*;
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]);
T::AccountId::decode(&mut &account_bytes[0..32])
.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());
}
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 _ = <<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)
verify {
assert_eq!(SlowClap::<T>::current_companion_id(), companion_id + 1);
}
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());
}
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)
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);
}
impl_benchmark_test_suite!(
Pallet,
crate::mock::new_test_ext(),
crate::mock::Runtime,
);
}

1334
pallets/slow-clap/src/lib.rs Executable file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,253 @@
#![cfg(test)]
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::{
testing::{TestXt, UintAuthorityId},
traits::ConvertInto,
BuildStorage, Permill,
};
use sp_staking::{
offence::{OffenceError, ReportOffence},
SessionIndex,
};
use crate as slow_clap;
use crate::Config;
type Block = frame_system::mocking::MockBlock<Runtime>;
frame_support::construct_runtime!(
pub enum Runtime {
System: frame_system,
Session: pallet_session,
Historical: pallet_session_historical,
Balances: pallet_balances,
Networks: ghost_networks,
SlowClap: slow_clap,
}
);
parameter_types! {
pub static Validators: Option<Vec<u64>> = Some(vec![
1,
2,
3,
]);
}
pub struct TestSessionManager;
impl pallet_session::SessionManager<u64> for TestSessionManager {
fn new_session(_new_index: SessionIndex) -> Option<Vec<u64>> {
Validators::mutate(|l| l.take())
}
fn end_session(_: SessionIndex) {}
fn start_session(_: SessionIndex) {}
}
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())
)
}
fn end_session(_: SessionIndex) {}
fn start_session(_: SessionIndex) {}
}
type IdentificationTuple = (u64, u64);
type Offence = crate::ThrottlingOffence<IdentificationTuple>;
parameter_types! {
pub static Offences: Vec<(Vec<u64>, Offence)> = vec![];
}
pub struct OffenceHandler;
impl ReportOffence<u64, IdentificationTuple, Offence> for OffenceHandler {
fn report_offence(reporters: Vec<u64>, offence: Offence) -> Result<(), OffenceError> {
Offences::mutate(|l| l.push((reporters, offence)));
Ok(())
}
fn is_known_offence(_offenders: &[IdentificationTuple], _time_slot: &SessionIndex) -> bool {
false
}
}
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()
.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);
});
result
}
#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
impl frame_system::Config for Runtime {
type Block = Block;
type AccountData = pallet_balances::AccountData<u64>;
}
parameter_types! {
pub const Period: u64 = 1;
pub const Offset: u64 = 0;
}
impl pallet_session::Config for Runtime {
type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
type SessionManager =
pallet_session::historical::NoteHistoricalRoot<Runtime, TestSessionManager>;
type SessionHandler = (SlowClap,);
type ValidatorId = u64;
type ValidatorIdOf = ConvertInto;
type Keys = UintAuthorityId;
type RuntimeEvent = RuntimeEvent;
type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;
type WeightInfo = ();
}
impl pallet_session::historical::Config for Runtime {
type FullIdentification = u64;
type FullIdentificationOf = ConvertInto;
}
parameter_types! {
pub static MockCurrentSessionProgress: Option<Option<Permill>> = None;
}
parameter_types! {
pub static MockAverageSessionLength: Option<u64> = None;
}
pub struct TestNextSessionRotation;
impl frame_support::traits::EstimateNextSessionRotation<u64> for TestNextSessionRotation {
fn average_session_length() -> u64 {
let mock = MockAverageSessionLength::mutate(|p| p.take());
mock.unwrap_or(pallet_session::PeriodicSessions::<Period, Offset>::average_session_length())
}
fn estimate_current_session_progress(now: u64) -> (Option<Permill>, Weight) {
let (estimate, weight) =
pallet_session::PeriodicSessions::<Period, Offset>::estimate_current_session_progress(
now,
);
let mock = MockCurrentSessionProgress::mutate(|p| p.take());
(mock.unwrap_or(estimate), weight)
}
fn estimate_next_session_rotation(now: u64) -> (Option<u64>, Weight) {
pallet_session::PeriodicSessions::<Period, Offset>::estimate_next_session_rotation(now)
}
}
impl ghost_networks::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type NetworkId = u32;
type RegisterOrigin = EnsureRoot<Self::AccountId>;
type UpdateOrigin = EnsureRoot<Self::AccountId>;
type RemoveOrigin = EnsureRoot<Self::AccountId>;
type WeightInfo = ();
}
parameter_types! {
pub static ExistentialDeposit: u64 = 2;
pub const TreasuryPalletId: PalletId = PalletId(*b"mck/test");
}
#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)]
impl pallet_balances::Config for Runtime {
type ExistentialDeposit = ExistentialDeposit;
type MaxReserves = ConstU32<2>;
type AccountStore = System;
type WeightInfo = ();
}
impl Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type AuthorityId = UintAuthorityId;
type NextSessionRotation = TestNextSessionRotation;
type ValidatorSet = Historical;
type Currency = Balances;
type NetworkDataHandler = Networks;
type BlockNumberProvider = System;
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 UnsignedPriority = ConstU64<{ 1 << 20 }>;
type TreasuryPalletId = TreasuryPalletId;
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>,
{
type OverarchingCall = RuntimeCall;
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 authorities = Session::validators()
// .into_iter()
// .map(UintAuthorityId)
// .collect();
//
// SlowClap::set_authorities(authorities);
// assert_eq!(Session::current_index(), (now / Period::get()) as u32);
// }

View File

@@ -0,0 +1,696 @@
#![cfg(test)]
use super::*;
use crate::mock::*;
use frame_support::{assert_err, assert_ok};
use sp_core::offchain::{
testing,
testing::TestOffchainExt, OffchainWorkerExt,
// OffchainDbExt, TransactionPoolExt,
};
// use sp_runtime::testing::UintAuthorityId;
fn prepare_networks() -> (u32, u32) {
let network = NetworkData {
chain_name: "Ethereum".into(),
default_endpoint: get_rpc_endpoint(),
finality_delay: Some(69),
release_delay: Some(69),
network_type: ghost_networks::NetworkType::Evm,
gatekeeper: get_gatekeeper(),
topic_name: get_topic_name(),
incoming_fee: 0,
outgoing_fee: 0,
};
assert_ok!(Networks::register_network(
RuntimeOrigin::root(),
get_network_id(),
network));
(1, 69)
}
fn prepare_companion(amount: u64) -> Companion<NetworkIdOf<Runtime>, BalanceOf<Runtime>> {
Companion {
network_id: 1,
receiver: H160::from_low_u64_ne(1337),
fee: H256::from_low_u64_ne(40_000),
amount: amount,
}
}
#[test]
fn test_throttling_slash_function() {
let dummy_offence = ThrottlingOffence {
session_index: 0,
validator_set_count: 50,
offenders: vec![()],
};
assert_eq!(dummy_offence.slash_fraction(1), Perbill::zero());
assert_eq!(dummy_offence.slash_fraction(5), Perbill::zero());
assert_eq!(dummy_offence.slash_fraction(7), Perbill::from_parts(4200000));
assert_eq!(dummy_offence.slash_fraction(17), Perbill::from_parts(46200000));
}
#[test]
fn propose_companion_works_as_expected() {
new_test_ext().execute_with(|| {
let actor = alice_account_id();
let companion_id = SlowClap::current_companion_id();
let (valid_network_id, _) = prepare_networks();
let companion = prepare_companion(100);
assert_eq!(Balances::balance(&actor), 100);
assert_eq!(Balances::total_issuance(), 100);
assert_eq!(SlowClap::companions(valid_network_id, companion_id), None);
assert_eq!(SlowClap::companion_details(companion_id), None);
assert_eq!(SlowClap::current_companion_id(), companion_id);
assert_ok!(SlowClap::propose_companion(RuntimeOrigin::signed(actor), valid_network_id, companion.clone()));
assert_eq!(Balances::balance(&actor), 0);
assert_eq!(Balances::total_issuance(), 0);
assert_eq!(SlowClap::companions(valid_network_id, companion_id), Some(actor));
assert_eq!(SlowClap::companion_details(companion_id), Some(companion));
assert_eq!(SlowClap::current_companion_id(), companion_id + 1);
});
}
#[test]
fn propose_companion_emits_event() {
new_test_ext().execute_with(|| {
let actor = alice_account_id();
let companion_id = SlowClap::current_companion_id();
let (valid_network_id, _) = prepare_networks();
let companion = prepare_companion(100);
System::reset_events();
assert_ok!(SlowClap::propose_companion(
RuntimeOrigin::signed(actor),
valid_network_id, companion.clone()));
System::assert_has_event(RuntimeEvent::SlowClap(
crate::Event::CompanionCreated {
companion_id,
owner: actor,
companion,
}));
});
}
#[test]
fn could_not_propose_if_not_enough_funds() {
new_test_ext().execute_with(|| {
let actor = alice_account_id();
let (valid_network_id, _) = prepare_networks();
let companion = prepare_companion(1_000);
assert_err!(SlowClap::propose_companion(
RuntimeOrigin::signed(actor),
valid_network_id, companion.clone()),
sp_runtime::TokenError::FundsUnavailable);
let companion = prepare_companion(100 / 2);
let prev_balance = Balances::balance(&actor);
assert_ok!(SlowClap::propose_companion(
RuntimeOrigin::signed(actor),
valid_network_id, companion.clone()));
assert_eq!(Balances::balance(&actor), prev_balance / 2);
});
}
#[test]
fn companion_amount_should_be_existent() {
new_test_ext().execute_with(|| {
let actor = alice_account_id();
let (valid_network_id, _) = prepare_networks();
let companion = prepare_companion(1);
assert_err!(SlowClap::propose_companion(
RuntimeOrigin::signed(actor),
valid_network_id, companion.clone()),
crate::Error::<Runtime>::CompanionAmountNotExistent);
});
}
#[test]
fn could_not_register_companion_if_network_not_registered() {
new_test_ext().execute_with(|| {
let actor = alice_account_id();
let (_, invalid_network_id) = prepare_networks();
let companion = prepare_companion(100);
assert_err!(SlowClap::propose_companion(
RuntimeOrigin::signed(actor),
invalid_network_id,
companion.clone()),
crate::Error::<Runtime>::NonRegisteredNetwork);
});
}
#[test]
fn release_companion_works() {
new_test_ext().execute_with(|| {
let actor = alice_account_id();
let companion_id = SlowClap::current_companion_id();
let (valid_network_id, _) = prepare_networks();
let companion = prepare_companion(50);
assert_ok!(SlowClap::propose_companion(
RuntimeOrigin::signed(actor),
valid_network_id,
companion.clone()));
assert_eq!(SlowClap::release_blocks(companion_id), 0);
assert_ok!(SlowClap::release_companion(
RuntimeOrigin::signed(actor),
valid_network_id, companion_id));
assert_eq!(SlowClap::release_blocks(companion_id), 69 + 1);
});
}
#[test]
fn release_companion_emits_event() {
new_test_ext().execute_with(|| {
let actor = alice_account_id();
let companion_id = SlowClap::current_companion_id();
let (valid_network_id, _) = prepare_networks();
let companion = prepare_companion(50);
assert_ok!(SlowClap::propose_companion(
RuntimeOrigin::signed(actor),
valid_network_id, companion.clone()));
System::reset_events();
assert_ok!(SlowClap::release_companion(
RuntimeOrigin::signed(actor),
valid_network_id, companion_id));
System::assert_has_event(RuntimeEvent::SlowClap(
crate::Event::CompanionReleased {
companion_id,
network_id: valid_network_id,
who: actor,
release_block: 69 + 1 }));
});
}
#[test]
fn could_not_release_from_random_account() {
new_test_ext().execute_with(|| {
let actor = alice_account_id();
let companion_id = SlowClap::current_companion_id();
let (valid_network_id, _) = prepare_networks();
let companion = prepare_companion(50);
assert_ok!(SlowClap::propose_companion(
RuntimeOrigin::signed(actor),
valid_network_id, companion.clone()));
assert_err!(SlowClap::release_companion(
RuntimeOrigin::signed(eve_account_id()),
valid_network_id, companion_id),
crate::Error::<Runtime>::NotValidCompanion);
});
}
#[test]
fn kill_companion_works() {
new_test_ext().execute_with(|| {
let actor = alice_account_id();
let companion_id = SlowClap::current_companion_id();
let (valid_network_id, _) = prepare_networks();
let companion = prepare_companion(50);
assert_ok!(SlowClap::propose_companion(
RuntimeOrigin::signed(actor),
valid_network_id, companion.clone()));
assert_ok!(SlowClap::release_companion(
RuntimeOrigin::signed(actor),
valid_network_id, companion_id));
let release_block = ReleaseBlocks::<Runtime>::get(companion_id);
assert_eq!(SlowClap::companions(valid_network_id, companion_id), Some(actor));
assert_eq!(SlowClap::companion_details(companion_id), Some(companion));
assert_eq!(Balances::balance(&actor), 50);
assert_eq!(Balances::total_issuance(), 50);
System::set_block_number(release_block + 1);
assert_ok!(SlowClap::kill_companion(
RuntimeOrigin::signed(actor),
valid_network_id, companion_id));
assert_eq!(SlowClap::companions(valid_network_id, companion_id), None);
assert_eq!(SlowClap::companion_details(companion_id), None);
assert_eq!(Balances::balance(&actor), 100);
assert_eq!(Balances::total_issuance(), 100);
});
}
#[test]
fn kill_companion_emits_event() {
new_test_ext().execute_with(|| {
let actor = alice_account_id();
let companion_id = SlowClap::current_companion_id();
let (valid_network_id, _) = prepare_networks();
let companion = prepare_companion(50);
assert_ok!(SlowClap::propose_companion(
RuntimeOrigin::signed(actor),
valid_network_id, companion.clone()));
assert_ok!(SlowClap::release_companion(
RuntimeOrigin::signed(actor),
valid_network_id, companion_id));
System::set_block_number(
ReleaseBlocks::<Runtime>::get(companion_id) + 1);
System::reset_events();
assert_ok!(SlowClap::kill_companion(
RuntimeOrigin::signed(actor),
valid_network_id, companion_id));
System::assert_has_event(RuntimeEvent::SlowClap(
crate::Event::CompanionKilled {
network_id: valid_network_id,
who: actor,
companion_id,
freed_balance: 50,
}));
});
}
#[test]
fn could_not_kill_companion_that_was_not_released() {
new_test_ext().execute_with(|| {
let actor = alice_account_id();
let companion_id = SlowClap::current_companion_id();
let (valid_network_id, _) = prepare_networks();
let companion = prepare_companion(50);
assert_ok!(SlowClap::propose_companion(
RuntimeOrigin::signed(actor),
valid_network_id, companion.clone()));
assert_ok!(SlowClap::release_companion(
RuntimeOrigin::signed(actor),
valid_network_id, companion_id));
let release_block = ReleaseBlocks::<Runtime>::get(companion_id);
assert_eq!(SlowClap::companions(valid_network_id, companion_id), Some(actor));
assert_eq!(SlowClap::companion_details(companion_id), Some(companion.clone()));
assert_eq!(Balances::balance(&actor), 50);
assert_eq!(Balances::total_issuance(), 50);
System::set_block_number(release_block / 2);
assert_err!(SlowClap::kill_companion(
RuntimeOrigin::signed(actor),
valid_network_id, companion_id),
crate::Error::<Runtime>::ReleaseTimeHasNotCome);
assert_eq!(SlowClap::companions(valid_network_id, companion_id), Some(actor));
assert_eq!(SlowClap::companion_details(companion_id), Some(companion));
assert_eq!(Balances::balance(&actor), 50);
assert_eq!(Balances::total_issuance(), 50);
});
}
#[test]
fn could_not_kill_companion_from_random_account() {
new_test_ext().execute_with(|| {
let actor = alice_account_id();
let companion_id = SlowClap::current_companion_id();
let (valid_network_id, _) = prepare_networks();
let companion = prepare_companion(50);
assert_ok!(SlowClap::propose_companion(
RuntimeOrigin::signed(actor),
valid_network_id, companion.clone()));
assert_ok!(SlowClap::release_companion(
RuntimeOrigin::signed(actor),
valid_network_id, companion_id));
let release_block = ReleaseBlocks::<Runtime>::get(companion_id);
assert_eq!(SlowClap::companions(valid_network_id, companion_id), Some(actor));
assert_eq!(SlowClap::companion_details(companion_id), Some(companion.clone()));
assert_eq!(Balances::balance(&actor), 50);
assert_eq!(Balances::total_issuance(), 50);
System::set_block_number(release_block + 1);
assert_err!(SlowClap::kill_companion(
RuntimeOrigin::signed(eve_account_id()),
valid_network_id, companion_id),
crate::Error::<Runtime>::NotValidCompanion);
assert_eq!(SlowClap::companions(valid_network_id, companion_id), Some(actor));
assert_eq!(SlowClap::companion_details(companion_id), Some(companion));
assert_eq!(Balances::balance(&actor), 50);
assert_eq!(Balances::total_issuance(), 50);
});
}
#[test]
fn request_body_is_correct_for_get_block_number() {
let (offchain, _) = TestOffchainExt::new();
let mut t = sp_io::TestExternalities::default();
t.register_extension(OffchainWorkerExt::new(offchain));
t.execute_with(|| {
let request_body = SlowClap::prepare_request_body(
None, 0, Vec::new(), Vec::new());
assert_eq!(core::str::from_utf8(&request_body).unwrap(),
r#"{"id":0,"jsonrpc":"2.0","method":"eth_blockNumber"}"#);
});
}
#[test]
fn request_body_is_correct_for_get_logs() {
let (offchain, _) = TestOffchainExt::new();
let mut t = sp_io::TestExternalities::default();
t.register_extension(OffchainWorkerExt::new(offchain));
t.execute_with(|| {
let request_body = SlowClap::prepare_request_body(
Some(1337), 69, get_gatekeeper(), get_topic_name());
assert_eq!(
core::str::from_utf8(&request_body).unwrap(),
r#"{"id":0,"jsonrpc":"2.0","method":"eth_getLogs","params":[{"fromBlock":1268,"toBlock":1337,"address":"0x4d224452801ACEd8B2F0aebE155379bb5D594381","topics":["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]}]}"#,
);
});
}
#[test]
fn should_make_http_call_for_block_number() {
let (offchain, state) = TestOffchainExt::new();
let mut t = sp_io::TestExternalities::default();
t.register_extension(OffchainWorkerExt::new(offchain));
evm_block_response(&mut state.write());
t.execute_with(|| {
let request_body = SlowClap::prepare_request_body(
None, 0, Vec::new(), Vec::new());
let raw_response = SlowClap::fetch_from_remote(
get_rpc_endpoint(), request_body).unwrap();
assert_eq!(raw_response.len(), 45usize); // precalculated
});
}
#[test]
fn should_make_http_call_for_logs() {
let (offchain, state) = TestOffchainExt::new();
let mut t = sp_io::TestExternalities::default();
t.register_extension(OffchainWorkerExt::new(offchain));
evm_logs_response(&mut state.write());
t.execute_with(|| {
let request_body = SlowClap::prepare_request_body(
Some(20335857), 84, get_gatekeeper(), get_topic_name());
let raw_response = SlowClap::fetch_from_remote(
get_rpc_endpoint(), request_body).unwrap();
assert_eq!(raw_response.len(), 1805); // precalculated
});
}
#[test]
fn should_make_http_call_and_parse_block_number() {
let (offchain, state) = TestOffchainExt::new();
let mut t = sp_io::TestExternalities::default();
t.register_extension(OffchainWorkerExt::new(offchain));
evm_block_response(&mut state.write());
t.execute_with(|| {
let evm_response = SlowClap::fetch_and_parse(
None, 0, Vec::<u8>::new(),
Vec::<u8>::new(), get_rpc_endpoint()).unwrap();
let evm_block_number = match evm_response {
EvmResponseType::BlockNumber(evm_block) => Some(evm_block),
_ => None,
};
assert_eq!(evm_block_number.unwrap_or_default(), 20335745);
});
}
#[test]
fn should_make_http_call_and_parse_logs() {
let (offchain, state) = TestOffchainExt::new();
let mut t = sp_io::TestExternalities::default();
t.register_extension(OffchainWorkerExt::new(offchain));
evm_logs_response(&mut state.write());
let expected_logs = get_expected_logs();
t.execute_with(|| {
let evm_response = SlowClap::fetch_and_parse(
Some(20335857), 84, get_gatekeeper(),
get_topic_name(), get_rpc_endpoint()
).unwrap();
let evm_logs = match evm_response {
EvmResponseType::TransactionLogs(logs) => Some(logs),
_ => None,
};
assert!(evm_logs.is_some());
let evm_logs = evm_logs.unwrap();
assert_eq!(evm_logs, expected_logs);
});
}
#[test]
fn should_catch_error_in_json_response() {
let (offchain, state) = TestOffchainExt::new();
let mut t = sp_io::TestExternalities::default();
t.register_extension(OffchainWorkerExt::new(offchain));
evm_error_response(&mut state.write());
t.execute_with(|| {
assert_err!(SlowClap::fetch_and_parse(
None, 0, Vec::<u8>::new(),
Vec::<u8>::new(), get_rpc_endpoint()),
OffchainErr::ErrorInEvmResponse);
});
}
// #[test]
// fn conversion_to_claps_is_correct() {
// todo!();
// }
//
// #[test]
// fn evm_block_storage_is_empty_by_default() {
// todo!();
// }
//
// #[test]
// fn evm_block_is_stored_locally_after_first_response() {
// todo!();
// }
//
// #[test]
// fn evm_block_storage_is_none_after_logs() {
// todo!();
// }
//
// #[test]
// fn send_evm_usigned_transaction_from_authority() {
// todo!();
// }
// #[test]
// fn should_report_offline_validators() {
// new_test_ext().execute_with(|| {
// let block = 1;
// System::set_block_number(block);
// advance_session();
// let validators = vec![1, 2, 3, 4, 5, 6];
// Validators::mutate(|l| *l = Some(validators.clone()));
// advance_session();
//
// advance_session();
//
// let offences = Offences::take();
// assert_eq!(
// offences,
// vec![(
// vec![],
// ThrottlingOffence {
// session_index: 2,
// validator_set_count: 3,
// offenders: vec![(1, 1), (2, 2), (3, 3)],
// }
// )]
// );
//
// for (idx, v) in validators.into_iter().take(4).enumerate() {
// let _ = clap();
// }
//
// advance_session();
//
// let offences = Offences::take();
// assert_eq!(
// offences,
// vec![(
// vec![],
// ThrottlingOffence {
// session_index: 3,
// validator_set_count: 6,
// offenders: vec![(5, 5), (6, 6)],
// }
// )]
// );
// });
// }
//
// #[test]
// fn should_increase_actions_of_validators_when_clap_is_received() {
// }
//
// #[test]
// fn same_claps_should_not_increase_actions() {
// }
//
// #[test]
// fn should_cleanup_received_claps_on_session_end() {
// }
//
// #[test]
// fn should_mark_validator_if_disabled() {
// }
fn get_rpc_endpoint() -> Vec<u8> {
b"https://nd-422-757-666.p2pify.com/0a9d79d93fb2f4a4b1e04695da2b77a7/".to_vec()
}
fn get_gatekeeper() -> Vec<u8> {
b"0x4d224452801ACEd8B2F0aebE155379bb5D594381".to_vec()
}
fn get_topic_name() -> Vec<u8> {
b"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef".to_vec()
}
fn get_network_id() -> u32 {
// let mut network_id: NetworkIdOf<Runtime> = Default::default();
// network_id.saturating_inc();
// network_id
1u32
}
fn evm_block_response(state: &mut testing::OffchainState) {
let expected_body = br#"{"id":0,"jsonrpc":"2.0","method":"eth_blockNumber"}"#.to_vec();
state.expect_request(testing::PendingRequest {
method: "POST".into(),
uri: "https://nd-422-757-666.p2pify.com/0a9d79d93fb2f4a4b1e04695da2b77a7/".into(),
headers: vec![
("ACCEPT".to_string(), "APPLICATION/JSON".to_string()),
("CONTENT-TYPE".to_string(), "APPLICATION/JSON".to_string()),
],
response: Some(b"{\"id\":0,\"jsonrpc\":\"2.0\",\"result\":\"0x1364c81\"}".to_vec()),
body: expected_body,
sent: true,
..Default::default()
});
}
fn evm_error_response(state: &mut testing::OffchainState) {
let expected_body = br#"{"id":0,"jsonrpc":"2.0","method":"eth_blockNumber"}"#.to_vec();
state.expect_request(testing::PendingRequest {
method: "POST".into(),
uri: "https://nd-422-757-666.p2pify.com/0a9d79d93fb2f4a4b1e04695da2b77a7/".into(),
headers: vec![
("ACCEPT".to_string(), "APPLICATION/JSON".to_string()),
("CONTENT-TYPE".to_string(), "APPLICATION/JSON".to_string()),
],
response: Some(b"{\"id\":0,\"jsonrpc\":\"2.0\",\"error\":\"some bad error occures :-(\"}".to_vec()),
body: expected_body,
sent: true,
..Default::default()
});
}
fn evm_logs_response(state: &mut testing::OffchainState) {
let expected_body = br#"{"id":0,"jsonrpc":"2.0","method":"eth_getLogs","params":[{"fromBlock":20335773,"toBlock":20335857,"address":"0x4d224452801ACEd8B2F0aebE155379bb5D594381","topics":["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]}]}"#.to_vec();
let expected_response = br#"{
"jsonrpc":"2.0",
"id":0,
"result":[
{
"address":"0x4d224452801aced8b2f0aebe155379bb5d594381",
"topics":[
"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",
"0x000000000000000000000000d91efec7e42f80156d1d9f660a69847188950747",
"0x0000000000000000000000005e611dfbe71b988cf2a3e5fe4191b5e3d4c4212a"
],
"data":"0x000000000000000000000000000000000000000000000046f0d522a71fdac000",
"blockNumber":"0x1364c9d",
"transactionHash":"0xa82f2fe87f4ba01ab3bd2cd4d0fe75a26f0e9a37e2badc004a0e38f9d088a758",
"transactionIndex":"0x11",
"blockHash":"0x4b08f82d5a948c0bc5c23c8ddce55e5b4536d7454be53668bbd985ef13dca04a",
"logIndex":"0x92",
"removed":false
},
{
"address":"0x4d224452801aced8b2f0aebe155379bb5d594381",
"topics":[
"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",
"0x0000000000000000000000005954ab967bc958940b7eb73ee84797dc8a2afbb9",
"0x000000000000000000000000465165be7cacdbd2cbc8334f549fab9783ad6e7a"
],
"data":"0x0000000000000000000000000000000000000000000000027c790defec959e75",
"blockNumber":"0x1364cf1",
"transactionHash":"0xd9f02b79a90db7536b0afb5e24bbc1f4319dc3d8c57af7c39941acd249ec053a",
"transactionIndex":"0x2c",
"blockHash":"0x6876b18f5081b5d24d5a73107a667a7713256f6e51edbbe52bf8df24e340b0f7",
"logIndex":"0x14b",
"removed":false
}
]
}"#.to_vec();
state.expect_request(testing::PendingRequest {
method: "POST".into(),
uri: "https://nd-422-757-666.p2pify.com/0a9d79d93fb2f4a4b1e04695da2b77a7/".into(),
headers: vec![
("ACCEPT".to_string(), "APPLICATION/JSON".to_string()),
("CONTENT-TYPE".to_string(), "APPLICATION/JSON".to_string()),
],
body: expected_body,
response: Some(expected_response),
sent: true,
..Default::default()
});
}
fn get_expected_logs() -> Vec<Log> {
let byte_converter = |s: &str| -> Vec<u8> {
(2..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i+2], 16).expect("valid u8 symbol; qed"))
.collect()
};
vec![
Log {
transaction_hash: Some(H256::from_slice(&byte_converter("0xa82f2fe87f4ba01ab3bd2cd4d0fe75a26f0e9a37e2badc004a0e38f9d088a758"))),
block_number: Some(20335773),
topics: vec![
byte_converter("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"),
byte_converter("0x000000000000000000000000d91efec7e42f80156d1d9f660a69847188950747"),
byte_converter("0x0000000000000000000000005e611dfbe71b988cf2a3e5fe4191b5e3d4c4212a"),
],
address: Some(b"0x4d224452801aced8b2f0aebe155379bb5d594381".to_vec()),
data: sp_std::collections::btree_map::BTreeMap::from([(0, 1308625900000000000000)]),
removed: false,
},
Log {
transaction_hash: Some(H256::from_slice(&byte_converter("0xd9f02b79a90db7536b0afb5e24bbc1f4319dc3d8c57af7c39941acd249ec053a"))),
block_number: Some(20335857),
topics: vec![
byte_converter("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"),
byte_converter("0x0000000000000000000000005954ab967bc958940b7eb73ee84797dc8a2afbb9"),
byte_converter("0x000000000000000000000000465165be7cacdbd2cbc8334f549fab9783ad6e7a"),
],
address: Some(b"0x4d224452801aced8b2f0aebe155379bb5d594381".to_vec()),
data: sp_std::collections::btree_map::BTreeMap::from([(0, 45862703604421729909)]),
removed: false,
},
]
}

View File

@@ -0,0 +1,18 @@
use frame_support::weights::Weight;
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;
}
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() }
}

19
pallets/traits/Cargo.toml Executable file
View File

@@ -0,0 +1,19 @@
[package]
name = "ghost-traits"
version = "0.3.19"
license.workspace = true
authors.workspace = true
edition.workspace = true
homepage.workspace = true
repository.workspace = true
[dependencies]
frame-support = { workspace = true }
sp-runtime = { workspace = true }
[features]
default = ["std"]
std = [
"frame-support/std",
"sp-runtime/std",
]

3
pallets/traits/src/lib.rs Executable file
View File

@@ -0,0 +1,3 @@
#![cfg_attr(not(feature = "std"), no_std)]
pub mod networks;

29
pallets/traits/src/networks.rs Executable file
View File

@@ -0,0 +1,29 @@
use frame_support::{
pallet_prelude::*,
storage::PrefixIterator,
};
use sp_runtime::{
DispatchResult,
traits::{AtLeast32BitUnsigned, Member},
};
pub trait NetworkDataBasicHandler {
type NetworkId: Parameter
+ Member
+ AtLeast32BitUnsigned
+ Default
+ Copy
+ TypeInfo
+ MaybeSerializeDeserialize
+ MaxEncodedLen;
}
pub trait NetworkDataInspectHandler<Network>: NetworkDataBasicHandler {
fn get(n: &Self::NetworkId) -> Option<Network>;
fn iter() -> PrefixIterator<(Self::NetworkId, Network)>;
}
pub trait NetworkDataMutateHandler<Network>: NetworkDataInspectHandler<Network> {
fn register(chain_id: Self::NetworkId, network: Network) -> DispatchResult;
fn remove(chain_id: Self::NetworkId) -> DispatchResult;
}