Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(custom-rpc): add account roles and LP info to custom RPC #4089

Merged
merged 12 commits into from
Oct 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions state-chain/custom-rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,6 @@ sp-rpc = { git = "https://github.com/chainflip-io/substrate.git", tag = "chainfl
sc-rpc-api = { git = "https://github.com/chainflip-io/substrate.git", tag = "chainflip-monthly-2023-08+2" }
sp-runtime = { git = "https://github.com/chainflip-io/substrate.git", tag = "chainflip-monthly-2023-08+2" }
sc-client-api = { git = "https://github.com/chainflip-io/substrate.git", tag = "chainflip-monthly-2023-08+2" }

[dev-dependencies]
serde_json = "1.0.107"
233 changes: 202 additions & 31 deletions state-chain/custom-rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@ use cf_amm::{
common::{Amount, Price, Tick},
range_orders::Liquidity,
};
use cf_chains::{btc::BitcoinNetwork, dot::PolkadotHash, eth::Address as EthereumAddress};
use cf_primitives::{Asset, AssetAmount, SemVer, SwapOutput};
use cf_chains::{
address::AddressConverter, btc::BitcoinNetwork, dot::PolkadotHash,
eth::Address as EthereumAddress,
};
use cf_primitives::{AccountRole, Asset, AssetAmount, ForeignChain, SemVer, SwapOutput};
use core::ops::Range;
use jsonrpsee::{
core::RpcResult,
Expand All @@ -19,22 +22,89 @@ use sp_api::BlockT;
use sp_rpc::number::NumberOrHex;
use sp_runtime::DispatchError;
use state_chain_runtime::{
chainflip::Offence,
chainflip::{ChainAddressConverter, Offence},
constants::common::TX_FEE_MULTIPLIER,
runtime_apis::{ChainflipAccountStateWithPassive, CustomRuntimeApi, Environment},
runtime_apis::{CustomRuntimeApi, Environment, LiquidityProviderInfo, RuntimeApiAccountInfoV2},
};
use std::{marker::PhantomData, sync::Arc};
use std::{collections::HashMap, marker::PhantomData, sync::Arc};

#[derive(Serialize, Deserialize)]
pub struct RpcAccountInfo {
pub balance: NumberOrHex,
pub bond: NumberOrHex,
pub last_heartbeat: u32,
pub is_live: bool,
pub is_activated: bool,
pub online_credits: u32,
pub reputation_points: i32,
pub state: ChainflipAccountStateWithPassive,
#[serde(tag = "role", rename_all = "snake_case")]
pub enum RpcAccountInfo {
None,
Broker,
LiquidityProvider {
balances: HashMap<ForeignChain, HashMap<Asset, NumberOrHex>>,
refund_addresses: HashMap<ForeignChain, Option<String>>,
},
Validator {
balance: NumberOrHex,
bond: NumberOrHex,
last_heartbeat: u32,
online_credits: u32,
reputation_points: i32,
keyholder_epochs: Vec<u32>,
is_current_authority: bool,
is_current_backup: bool,
is_qualified: bool,
is_online: bool,
is_bidding: bool,
bound_redeem_address: Option<EthereumAddress>,
},
}

impl RpcAccountInfo {
fn none() -> Self {
Self::None
}

fn broker() -> Self {
Self::Broker
}

fn lp(info: LiquidityProviderInfo) -> Self {
let mut balances = HashMap::new();

for (asset, balance) in info.balances {
balances
.entry(asset.into())
.or_insert_with(HashMap::new)
.insert(asset, balance.into());
}

Self::LiquidityProvider {
balances,
refund_addresses: info
.refund_addresses
.into_iter()
.map(|(chain, address)| {
(
chain,
address
.map(ChainAddressConverter::to_encoded_address)
.map(|a| format!("{}", a)),
)
})
.collect(),
}
}

fn validator(info: RuntimeApiAccountInfoV2) -> Self {
Self::Validator {
balance: info.balance.into(),
bond: info.bond.into(),
last_heartbeat: info.last_heartbeat,
online_credits: info.online_credits,
reputation_points: info.reputation_points,
keyholder_epochs: info.keyholder_epochs,
is_current_authority: info.is_current_authority,
is_current_backup: info.is_current_backup,
is_qualified: info.is_qualified,
is_online: info.is_online,
is_bidding: info.is_bidding,
bound_redeem_address: info.bound_redeem_address,
}
}
}

#[derive(Serialize, Deserialize)]
Expand Down Expand Up @@ -440,28 +510,41 @@ where
})
.collect())
}

fn cf_account_info(
&self,
account_id: state_chain_runtime::AccountId,
at: Option<<B as BlockT>::Hash>,
at: Option<state_chain_runtime::Hash>,
) -> RpcResult<RpcAccountInfo> {
let account_info = self
.client
.runtime_api()
.cf_account_info(self.unwrap_or_best(at), account_id)
.map_err(to_rpc_error)?;

Ok(RpcAccountInfo {
balance: account_info.balance.into(),
bond: account_info.bond.into(),
last_heartbeat: account_info.last_heartbeat,
is_live: account_info.is_live,
is_activated: account_info.is_activated,
online_credits: account_info.online_credits,
reputation_points: account_info.reputation_points,
state: account_info.state,
})
let api = self.client.runtime_api();

Ok(
match api
.cf_account_role(self.unwrap_or_best(at), account_id.clone())
.map_err(to_rpc_error)?
.unwrap_or(AccountRole::None)
{
AccountRole::None => RpcAccountInfo::none(),
AccountRole::Broker => RpcAccountInfo::broker(),
AccountRole::LiquidityProvider => {
let info = api
.cf_liquidity_provider_info(self.unwrap_or_best(at), account_id)
.map_err(to_rpc_error)?
.expect("role already validated");

RpcAccountInfo::lp(info)
},
AccountRole::Validator => {
let info = api
.cf_account_info_v2(self.unwrap_or_best(at), account_id)
.map_err(to_rpc_error)?;

RpcAccountInfo::validator(info)
},
},
)
}

fn cf_account_info_v2(
&self,
account_id: state_chain_runtime::AccountId,
Expand All @@ -488,6 +571,7 @@ where
bound_redeem_address: account_info.bound_redeem_address,
})
}

fn cf_penalties(
&self,
at: Option<<B as BlockT>::Hash>,
Expand Down Expand Up @@ -832,3 +916,90 @@ where
Ok(())
}
}

#[cfg(test)]

mod test {
use super::*;
use serde_json::json;
use sp_core::H160;

#[test]
fn test_account_info_serialization() {
assert_eq!(
serde_json::to_value(RpcAccountInfo::none()).unwrap(),
json!({ "role": "none" })
);
assert_eq!(
serde_json::to_value(RpcAccountInfo::broker()).unwrap(),
json!({ "role":"broker" })
);

let lp = RpcAccountInfo::lp(LiquidityProviderInfo {
refund_addresses: vec![
(
ForeignChain::Ethereum,
Some(cf_chains::ForeignChainAddress::Eth(H160::from([1; 20]))),
),
(
ForeignChain::Polkadot,
Some(cf_chains::ForeignChainAddress::Dot(Default::default())),
),
(ForeignChain::Bitcoin, None),
],
balances: vec![(Asset::Eth, u128::MAX), (Asset::Btc, 0), (Asset::Flip, u128::MAX / 2)],
});

assert_eq!(
serde_json::to_value(lp).unwrap(),
json!({
"role": "liquidity_provider",
"balances": {
"Ethereum": {
"Flip": "0x7fffffffffffffffffffffffffffffff",
"Eth": "0xffffffffffffffffffffffffffffffff"
},
"Bitcoin": { "Btc": "0x0" },
},
"refund_addresses": {
"Ethereum": "0x0101010101010101010101010101010101010101",
"Bitcoin": null,
"Polkadot": "0x0000000000000000000000000000000000000000000000000000000000000000"
}
})
);

let validator = RpcAccountInfo::validator(RuntimeApiAccountInfoV2 {
balance: 10u128.pow(18),
bond: 10u128.pow(18),
last_heartbeat: 0,
online_credits: 0,
reputation_points: 0,
keyholder_epochs: vec![123],
is_current_authority: true,
is_bidding: false,
is_current_backup: false,
is_online: true,
is_qualified: true,
bound_redeem_address: Some(H160::from([1; 20])),
});
assert_eq!(
serde_json::to_value(validator).unwrap(),
json!({
"balance": "0xde0b6b3a7640000",
"bond": "0xde0b6b3a7640000",
"bound_redeem_address": "0x0101010101010101010101010101010101010101",
"is_bidding": false,
"is_current_authority": true,
"is_current_backup": false,
"is_online": true,
"is_qualified": true,
"keyholder_epochs": [123],
"last_heartbeat": 0,
"online_credits": 0,
"reputation_points": 0,
"role": "validator"
})
);
}
}
10 changes: 9 additions & 1 deletion state-chain/primitives/src/chains.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ macro_rules! chains {
}
)+

#[derive(Clone, Debug, PartialEq, Eq, Encode, Decode, TypeInfo, MaxEncodedLen, Copy)]
#[derive(Clone, Debug, PartialEq, Eq, Encode, Decode, TypeInfo, MaxEncodedLen, Copy, Hash)]
#[derive(Serialize, Deserialize)]
#[repr(u32)]
pub enum ForeignChain {
Expand All @@ -38,6 +38,14 @@ macro_rules! chains {
)+
}

impl ForeignChain {
pub fn iter() -> impl Iterator<Item = Self> {
[
$( ForeignChain::$chain, )+
].into_iter()
}
}

impl TryFrom<u32> for ForeignChain {
type Error = &'static str;

Expand Down
Loading