Skip to content

Commit 65a8b9f

Browse files
authored
Relayer reward metric (paritytech#1742)
* use StorageDoubleMapKeyProvider in RelayerRewards * add metrics * clippy * fixed alerts that have caused missing dashboards * fix metric name * fix metric name again * add new metrics to the RialtoParachain <> Millau maintenance dashboard * remove obsolete dashboard
1 parent 491f900 commit 65a8b9f

File tree

13 files changed

+127
-21
lines changed

13 files changed

+127
-21
lines changed

bridges/modules/relayers/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ scale-info = { version = "2.1.1", default-features = false, features = ["derive"
1515

1616
bp-messages = { path = "../../primitives/messages", default-features = false }
1717
bp-relayers = { path = "../../primitives/relayers", default-features = false }
18+
bp-runtime = { path = "../../primitives/runtime", default-features = false }
1819

1920
# Substrate Dependencies
2021

@@ -37,6 +38,7 @@ default = ["std"]
3738
std = [
3839
"bp-messages/std",
3940
"bp-relayers/std",
41+
"bp-runtime/std",
4042
"codec/std",
4143
"frame-support/std",
4244
"frame-system/std",

bridges/modules/relayers/src/lib.rs

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@
2121
#![warn(missing_docs)]
2222

2323
use bp_messages::LaneId;
24-
use bp_relayers::PaymentProcedure;
24+
use bp_relayers::{PaymentProcedure, RelayerRewardsKeyProvider};
25+
use bp_runtime::StorageDoubleMapKeyProvider;
2526
use frame_support::sp_runtime::Saturating;
2627
use sp_arithmetic::traits::{AtLeast32BitUnsigned, Zero};
2728
use sp_std::marker::PhantomData;
@@ -46,6 +47,10 @@ pub mod pallet {
4647
use frame_support::pallet_prelude::*;
4748
use frame_system::pallet_prelude::*;
4849

50+
/// `RelayerRewardsKeyProvider` for given configuration.
51+
type RelayerRewardsKeyProviderOf<T> =
52+
RelayerRewardsKeyProvider<<T as frame_system::Config>::AccountId, <T as Config>::Reward>;
53+
4954
#[pallet::config]
5055
pub trait Config: frame_system::Config {
5156
/// The overarching event type.
@@ -146,11 +151,11 @@ pub mod pallet {
146151
#[pallet::getter(fn relayer_reward)]
147152
pub type RelayerRewards<T: Config> = StorageDoubleMap<
148153
_,
149-
Blake2_128Concat,
150-
T::AccountId,
151-
Identity,
152-
LaneId,
153-
T::Reward,
154+
<RelayerRewardsKeyProviderOf<T> as StorageDoubleMapKeyProvider>::Hasher1,
155+
<RelayerRewardsKeyProviderOf<T> as StorageDoubleMapKeyProvider>::Key1,
156+
<RelayerRewardsKeyProviderOf<T> as StorageDoubleMapKeyProvider>::Hasher2,
157+
<RelayerRewardsKeyProviderOf<T> as StorageDoubleMapKeyProvider>::Key2,
158+
<RelayerRewardsKeyProviderOf<T> as StorageDoubleMapKeyProvider>::Value,
154159
OptionQuery,
155160
>;
156161
}

bridges/primitives/relayers/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
1111
# Bridge Dependencies
1212

1313
bp-messages = { path = "../messages", default-features = false }
14+
bp-runtime = { path = "../runtime", default-features = false }
1415

1516
# Substrate Dependencies
1617

@@ -27,6 +28,7 @@ hex-literal = "0.3"
2728
default = ["std"]
2829
std = [
2930
"bp-messages/std",
31+
"bp-runtime/std",
3032
"frame-support/std",
3133
"sp-runtime/std",
3234
"sp-std/std",

bridges/primitives/relayers/src/lib.rs

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,10 @@
2020
#![cfg_attr(not(feature = "std"), no_std)]
2121

2222
use bp_messages::LaneId;
23+
use bp_runtime::StorageDoubleMapKeyProvider;
24+
use frame_support::{Blake2_128Concat, Identity};
2325
use sp_runtime::{
24-
codec::{Decode, Encode},
26+
codec::{Codec, Decode, Encode, EncodeLike},
2527
traits::AccountIdConversion,
2628
};
2729
use sp_std::{fmt::Debug, marker::PhantomData};
@@ -65,6 +67,24 @@ where
6567
}
6668
}
6769

70+
/// Can be use to access the runtime storage key within the `RelayerRewards` map of the relayers
71+
/// pallet.
72+
pub struct RelayerRewardsKeyProvider<AccountId, Reward>(PhantomData<(AccountId, Reward)>);
73+
74+
impl<AccountId, Reward> StorageDoubleMapKeyProvider for RelayerRewardsKeyProvider<AccountId, Reward>
75+
where
76+
AccountId: Codec + EncodeLike,
77+
Reward: Codec + EncodeLike,
78+
{
79+
const MAP_NAME: &'static str = "RelayerRewards";
80+
81+
type Hasher1 = Blake2_128Concat;
82+
type Key1 = AccountId;
83+
type Hasher2 = Identity;
84+
type Key2 = LaneId;
85+
type Value = Reward;
86+
}
87+
6888
#[cfg(test)]
6989
mod tests {
7090
use super::*;

bridges/relays/bin-substrate/src/cli/relay_headers_and_messages/mod.rs

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,8 @@ use crate::{
6161
use bp_messages::LaneId;
6262
use bp_runtime::BalanceOf;
6363
use relay_substrate_client::{
64-
AccountIdOf, AccountKeyPairOf, Chain, ChainWithBalances, ChainWithTransactions, Client,
65-
Parachain,
64+
AccountIdOf, AccountKeyPairOf, Chain, ChainWithBalances, ChainWithMessages,
65+
ChainWithTransactions, Client, Parachain,
6666
};
6767
use relay_utils::metrics::MetricsParams;
6868
use sp_core::Pair;
@@ -259,9 +259,9 @@ where
259259
type Base: Full2WayBridgeBase<Left = Self::Left, Right = Self::Right>;
260260

261261
/// The left relay chain.
262-
type Left: ChainWithTransactions + ChainWithBalances + CliChain;
262+
type Left: ChainWithTransactions + ChainWithBalances + ChainWithMessages + CliChain;
263263
/// The right relay chain.
264-
type Right: ChainWithTransactions + ChainWithBalances + CliChain;
264+
type Right: ChainWithTransactions + ChainWithBalances + ChainWithMessages + CliChain;
265265

266266
/// Left to Right bridge.
267267
type L2R: MessagesCliBridge<Source = Self::Left, Target = Self::Right>;
@@ -317,28 +317,36 @@ where
317317
self.mut_base().start_on_demand_headers_relayers().await?;
318318

319319
// add balance-related metrics
320+
let lanes = self
321+
.base()
322+
.common()
323+
.shared
324+
.lane
325+
.iter()
326+
.cloned()
327+
.map(Into::into)
328+
.collect::<Vec<_>>();
320329
{
321330
let common = self.mut_base().mut_common();
322-
substrate_relay_helper::messages_metrics::add_relay_balances_metrics(
331+
substrate_relay_helper::messages_metrics::add_relay_balances_metrics::<_, Self::Right>(
323332
common.left.client.clone(),
324333
&mut common.metrics_params,
325334
&common.left.accounts,
335+
&lanes,
326336
)
327337
.await?;
328-
substrate_relay_helper::messages_metrics::add_relay_balances_metrics(
338+
substrate_relay_helper::messages_metrics::add_relay_balances_metrics::<_, Self::Left>(
329339
common.right.client.clone(),
330340
&mut common.metrics_params,
331341
&common.right.accounts,
342+
&lanes,
332343
)
333344
.await?;
334345
}
335346

336-
let lanes = self.base().common().shared.lane.clone();
337347
// Need 2x capacity since we consider both directions for each lane
338348
let mut message_relays = Vec::with_capacity(lanes.len() * 2);
339349
for lane in lanes {
340-
let lane = lane.into();
341-
342350
let left_to_right_messages = substrate_relay_helper::messages_lane::run::<
343351
<Self::L2R as MessagesCliBridge>::MessagesLane,
344352
>(self.left_to_right().messages_relay_params(

bridges/relays/client-bridge-hub-rococo/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ impl ChainWithTransactions for BridgeHubRococo {
110110
impl ChainWithMessages for BridgeHubRococo {
111111
const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str =
112112
bp_bridge_hub_rococo::WITH_BRIDGE_HUB_ROCOCO_MESSAGES_PALLET_NAME;
113+
const WITH_CHAIN_RELAYERS_PALLET_NAME: Option<&'static str> = None;
113114

114115
const TO_CHAIN_MESSAGE_DETAILS_METHOD: &'static str =
115116
bp_bridge_hub_rococo::TO_BRIDGE_HUB_ROCOCO_MESSAGE_DETAILS_METHOD;

bridges/relays/client-bridge-hub-wococo/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ impl ChainWithTransactions for BridgeHubWococo {
110110
impl ChainWithMessages for BridgeHubWococo {
111111
const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str =
112112
bp_bridge_hub_wococo::WITH_BRIDGE_HUB_WOCOCO_MESSAGES_PALLET_NAME;
113+
const WITH_CHAIN_RELAYERS_PALLET_NAME: Option<&'static str> = None;
113114

114115
const TO_CHAIN_MESSAGE_DETAILS_METHOD: &'static str =
115116
bp_bridge_hub_wococo::TO_BRIDGE_HUB_WOCOCO_MESSAGE_DETAILS_METHOD;

bridges/relays/client-millau/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@ impl ChainWithGrandpa for Millau {
4545
impl ChainWithMessages for Millau {
4646
const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str =
4747
bp_millau::WITH_MILLAU_MESSAGES_PALLET_NAME;
48+
// TODO (https://github.com/paritytech/parity-bridges-common/issues/1692): change the name
49+
const WITH_CHAIN_RELAYERS_PALLET_NAME: Option<&'static str> = Some("BridgeRelayers");
4850
const TO_CHAIN_MESSAGE_DETAILS_METHOD: &'static str =
4951
bp_millau::TO_MILLAU_MESSAGE_DETAILS_METHOD;
5052
const FROM_CHAIN_MESSAGE_DETAILS_METHOD: &'static str =

bridges/relays/client-rialto-parachain/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,8 @@ impl ChainWithBalances for RialtoParachain {
6363
impl ChainWithMessages for RialtoParachain {
6464
const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str =
6565
bp_rialto_parachain::WITH_RIALTO_PARACHAIN_MESSAGES_PALLET_NAME;
66+
// TODO (https://github.com/paritytech/parity-bridges-common/issues/1692): change the name
67+
const WITH_CHAIN_RELAYERS_PALLET_NAME: Option<&'static str> = Some("BridgeRelayers");
6668
const TO_CHAIN_MESSAGE_DETAILS_METHOD: &'static str =
6769
bp_rialto_parachain::TO_RIALTO_PARACHAIN_MESSAGE_DETAILS_METHOD;
6870
const FROM_CHAIN_MESSAGE_DETAILS_METHOD: &'static str =

bridges/relays/client-rialto/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,8 @@ impl ChainWithGrandpa for Rialto {
6363
impl ChainWithMessages for Rialto {
6464
const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str =
6565
bp_rialto::WITH_RIALTO_MESSAGES_PALLET_NAME;
66+
// TODO (https://github.com/paritytech/parity-bridges-common/issues/1692): change the name
67+
const WITH_CHAIN_RELAYERS_PALLET_NAME: Option<&'static str> = Some("BridgeRelayers");
6668
const TO_CHAIN_MESSAGE_DETAILS_METHOD: &'static str =
6769
bp_rialto::TO_RIALTO_MESSAGE_DETAILS_METHOD;
6870
const FROM_CHAIN_MESSAGE_DETAILS_METHOD: &'static str =

bridges/relays/client-substrate/src/chain.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,16 @@ pub trait ChainWithMessages: Chain {
101101
/// the same name.
102102
const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str;
103103

104+
// TODO (https://github.com/paritytech/parity-bridges-common/issues/1692): check all the names
105+
// after the issue is fixed - all names must be changed
106+
107+
/// Name of the bridge relayers pallet (used in `construct_runtime` macro call) that is deployed
108+
/// at some other chain to bridge with this `ChainWithMessages`.
109+
///
110+
/// We assume that all chains that are bridging with this `ChainWithMessages` are using
111+
/// the same name.
112+
const WITH_CHAIN_RELAYERS_PALLET_NAME: Option<&'static str>;
113+
104114
/// Name of the `To<ChainWithMessages>OutboundLaneApi::message_details` runtime API method.
105115
/// The method is provided by the runtime that is bridged with this `ChainWithMessages`.
106116
const TO_CHAIN_MESSAGE_DETAILS_METHOD: &'static str;

bridges/relays/lib-substrate-relay/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ async-std = "1.9.0"
1212
async-trait = "0.1"
1313
codec = { package = "parity-scale-codec", version = "3.1.5" }
1414
futures = "0.3.12"
15+
hex = "0.4"
1516
num-traits = "0.2"
1617
log = "0.4.17"
1718

@@ -20,6 +21,7 @@ log = "0.4.17"
2021
bp-header-chain = { path = "../../primitives/header-chain" }
2122
bp-parachains = { path = "../../primitives/parachains" }
2223
bp-polkadot-core = { path = "../../primitives/polkadot-core" }
24+
bp-relayers = { path = "../../primitives/relayers" }
2325
bridge-runtime-common = { path = "../../bin/runtime-common" }
2426

2527
finality-grandpa = { version = "0.16.0" }

bridges/relays/lib-substrate-relay/src/messages_metrics.rs

Lines changed: 54 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,23 +18,27 @@
1818
1919
use crate::TaggedAccount;
2020

21+
use bp_messages::LaneId;
22+
use bp_runtime::StorageDoubleMapKeyProvider;
2123
use codec::Decode;
2224
use frame_system::AccountInfo;
2325
use pallet_balances::AccountData;
2426
use relay_substrate_client::{
2527
metrics::{FloatStorageValue, FloatStorageValueMetric},
26-
AccountIdOf, BalanceOf, Chain, ChainWithBalances, Client, Error as SubstrateError, IndexOf,
28+
AccountIdOf, BalanceOf, Chain, ChainWithBalances, ChainWithMessages, Client,
29+
Error as SubstrateError, IndexOf,
2730
};
2831
use relay_utils::metrics::{MetricsParams, StandaloneMetric};
2932
use sp_core::storage::StorageData;
3033
use sp_runtime::{FixedPointNumber, FixedU128};
3134
use std::{convert::TryFrom, fmt::Debug, marker::PhantomData};
3235

3336
/// Add relay accounts balance metrics.
34-
pub async fn add_relay_balances_metrics<C: ChainWithBalances>(
37+
pub async fn add_relay_balances_metrics<C: ChainWithBalances, BC: ChainWithMessages>(
3538
client: Client<C>,
3639
metrics: &mut MetricsParams,
3740
relay_accounts: &Vec<TaggedAccount<AccountIdOf<C>>>,
41+
lanes: &[LaneId],
3842
) -> anyhow::Result<()>
3943
where
4044
BalanceOf<C>: Into<u128> + std::fmt::Debug,
@@ -68,26 +72,43 @@ where
6872

6973
for account in relay_accounts {
7074
let relay_account_balance_metric = FloatStorageValueMetric::new(
71-
FreeAccountBalance::<C> { token_decimals, _phantom: Default::default() },
75+
AccountBalanceFromAccountInfo::<C> { token_decimals, _phantom: Default::default() },
7276
client.clone(),
7377
C::account_info_storage_key(account.id()),
7478
format!("at_{}_relay_{}_balance", C::NAME, account.tag()),
7579
format!("Balance of the {} relay account at the {}", account.tag(), C::NAME),
7680
)?;
7781
relay_account_balance_metric.register_and_spawn(&metrics.registry)?;
82+
83+
if let Some(relayers_pallet_name) = BC::WITH_CHAIN_RELAYERS_PALLET_NAME {
84+
for lane in lanes {
85+
let relay_account_reward_metric = FloatStorageValueMetric::new(
86+
AccountBalance::<C> { token_decimals, _phantom: Default::default() },
87+
client.clone(),
88+
bp_relayers::RelayerRewardsKeyProvider::<AccountIdOf<C>, BalanceOf<C>>::final_key(
89+
relayers_pallet_name,
90+
account.id(),
91+
lane,
92+
),
93+
format!("at_{}_relay_{}_reward_for_lane_{}_with_{}", C::NAME, account.tag(), hex::encode(lane.as_ref()), BC::NAME),
94+
format!("Reward of the {} relay account for serving lane {:?} with {} at the {}", account.tag(), lane, BC::NAME, C::NAME),
95+
)?;
96+
relay_account_reward_metric.register_and_spawn(&metrics.registry)?;
97+
}
98+
}
7899
}
79100

80101
Ok(())
81102
}
82103

83104
/// Adapter for `FloatStorageValueMetric` to decode account free balance.
84105
#[derive(Clone, Debug)]
85-
struct FreeAccountBalance<C> {
106+
struct AccountBalanceFromAccountInfo<C> {
86107
token_decimals: u32,
87108
_phantom: PhantomData<C>,
88109
}
89110

90-
impl<C> FloatStorageValue for FreeAccountBalance<C>
111+
impl<C> FloatStorageValue for AccountBalanceFromAccountInfo<C>
91112
where
92113
C: Chain,
93114
BalanceOf<C>: Into<u128>,
@@ -110,6 +131,34 @@ where
110131
}
111132
}
112133

134+
/// Adapter for `FloatStorageValueMetric` to decode account free balance.
135+
#[derive(Clone, Debug)]
136+
struct AccountBalance<C> {
137+
token_decimals: u32,
138+
_phantom: PhantomData<C>,
139+
}
140+
141+
impl<C> FloatStorageValue for AccountBalance<C>
142+
where
143+
C: Chain,
144+
BalanceOf<C>: Into<u128>,
145+
{
146+
type Value = FixedU128;
147+
148+
fn decode(
149+
&self,
150+
maybe_raw_value: Option<StorageData>,
151+
) -> Result<Option<Self::Value>, SubstrateError> {
152+
maybe_raw_value
153+
.map(|raw_value| {
154+
BalanceOf::<C>::decode(&mut &raw_value.0[..])
155+
.map_err(SubstrateError::ResponseParseFailed)
156+
.map(|balance| convert_to_token_balance(balance.into(), self.token_decimals))
157+
})
158+
.transpose()
159+
}
160+
}
161+
113162
/// Convert from raw `u128` balance (nominated in smallest chain token units) to the float regular
114163
/// tokens value.
115164
fn convert_to_token_balance(balance: u128, token_decimals: u32) -> FixedU128 {

0 commit comments

Comments
 (0)