Skip to content
This repository was archived by the owner on Jun 1, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
48 changes: 48 additions & 0 deletions crates/gem_hypercore/src/models/balance.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use gem_evm::ethereum_address_checksum;
use serde::{Deserialize, Serialize};
use serde_serializers::deserialize_f64_from_str;
use strum::{Display, EnumString};

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
Expand Down Expand Up @@ -57,6 +58,53 @@ impl DelegationBalance {
}
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no camelCase for those field names

pub struct DelegatorHistoryEntry {
pub time: u64,
pub delta: DelegatorDelta,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here, withdrawal

pub struct DelegatorDelta {
pub withdrawal: Option<DelegatorWithdrawal>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DelegatorWithdrawal {
#[serde(deserialize_with = "deserialize_f64_from_str")]
pub amount: f64,
pub phase: WithdrawalPhase,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Display, EnumString)]
#[serde(from = "String", into = "String")]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this enum looks so weird, from sting and to string? and #[strum(serialize = "initiated")]
Initiated??

pub enum WithdrawalPhase {
#[strum(serialize = "initiated")]
Initiated,
#[strum(serialize = "finalized")]
Finalized,
#[strum(default)]
Other(String),
}

impl From<String> for WithdrawalPhase {
fn from(value: String) -> Self {
match value.parse() {
Ok(phase) => phase,
Err(_) => WithdrawalPhase::Other(value),
}
}
}

impl From<WithdrawalPhase> for String {
fn from(value: WithdrawalPhase) -> Self {
value.to_string()
}
}
Comment thread
DRadmir marked this conversation as resolved.
Outdated

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Validator {
Expand Down
6 changes: 4 additions & 2 deletions crates/gem_hypercore/src/provider/staking.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use async_trait::async_trait;
use chain_traits::ChainStaking;
use chrono::Utc;
use futures::try_join;
use std::error::Error;

use gem_client::Client;
Expand All @@ -21,7 +23,7 @@ impl<C: Client> ChainStaking for HyperCoreClient<C> {
}

async fn get_staking_delegations(&self, address: String) -> Result<Vec<DelegationBase>, Box<dyn Error + Sync + Send>> {
let delegations = self.get_staking_delegations(&address).await?;
Ok(staking_mapper::map_staking_delegations(delegations, self.chain))
let (delegations, history) = try_join!(self.get_staking_delegations(&address), self.get_staking_history(&address))?;
Ok(staking_mapper::map_staking_delegations(delegations, history, Utc::now(), self.chain))
}
}
120 changes: 99 additions & 21 deletions crates/gem_hypercore/src/provider/staking_mapper.rs
Original file line number Diff line number Diff line change
@@ -1,46 +1,93 @@
use crate::models::balance::{DelegationBalance, Validator};
use crate::models::balance::{DelegationBalance, DelegatorHistoryEntry, Validator, WithdrawalPhase};
use chrono::{DateTime, Duration, Utc};
use num_bigint::BigUint;
use number_formatter::BigNumberFormatter;
use primitives::{Asset, Chain, DelegationBase, DelegationState, DelegationValidator};
use std::str::FromStr;

pub fn map_staking_validators(validators: Vec<Validator>, chain: Chain, apy: Option<f64>) -> Vec<DelegationValidator> {
let calculated_apy = apy.unwrap_or_else(|| Validator::max_apr(validators.clone()));
validators
let mut result: Vec<DelegationValidator> = validators
.into_iter()
.map(|x| DelegationValidator::stake(chain, x.validator_address(), x.name, x.is_active, x.commission, calculated_apy))
.collect()
.collect();

result.push(DelegationValidator::system(chain));

result
}

pub fn map_staking_delegations(delegations: Vec<DelegationBalance>, chain: Chain) -> Vec<DelegationBase> {
pub fn map_staking_delegations(delegations: Vec<DelegationBalance>, history: Vec<DelegatorHistoryEntry>, now: DateTime<Utc>, chain: Chain) -> Vec<DelegationBase> {
let native_decimals = Asset::from_chain(chain).decimals as u32;
delegations
let mut result: Vec<DelegationBase> = delegations
.into_iter()
.map(|x| DelegationBase {
asset_id: chain.as_asset_id(),
state: DelegationState::Active,
balance: parse_balance(&x.amount.to_string(), native_decimals),
shares: BigUint::from(0u32),
rewards: BigUint::from(0u32),
completion_date: None,
delegation_id: x.validator_address(),
validator_id: x.validator_address(),
})
.collect();

result.extend(map_pending_withdrawals(history, now, chain, native_decimals));
result
}

fn map_pending_withdrawals(history: Vec<DelegatorHistoryEntry>, now: DateTime<Utc>, chain: Chain, native_decimals: u32) -> Vec<DelegationBase> {
let lock_time = chain.config().stake.as_ref().map(|stake| stake.lock_time).unwrap_or_default();
let lock = Duration::seconds(lock_time as i64);

history
.into_iter()
.map(|x| {
let balance = BigNumberFormatter::value_from_amount(&x.amount.to_string(), native_decimals)
.ok()
.and_then(|s| BigUint::from_str(&s).ok())
.unwrap_or_default();
DelegationBase {
.filter_map(|entry| {
let withdrawal = entry.delta.withdrawal?;
if withdrawal.phase != WithdrawalPhase::Initiated {
return None;
}
let completion_date = DateTime::from_timestamp_millis(entry.time as i64)? + lock;
if completion_date <= now {
return None;
}
Some(DelegationBase {
asset_id: chain.as_asset_id(),
state: DelegationState::Active,
balance,
state: DelegationState::Pending,
balance: parse_balance(&withdrawal.amount.to_string(), native_decimals),
shares: BigUint::from(0u32),
rewards: BigUint::from(0u32),
completion_date: None,
delegation_id: x.validator_address(),
validator_id: x.validator_address(),
}
completion_date: Some(completion_date),
delegation_id: format!("unstaking_{}", entry.time),
validator_id: DelegationValidator::SYSTEM_ID.to_string(),
})
})
.collect()
}

fn parse_balance(amount: &str, native_decimals: u32) -> BigUint {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

inline useless helpers

BigNumberFormatter::value_from_amount(amount, native_decimals)
.ok()
.and_then(|s| BigUint::from_str(&s).ok())
.unwrap_or_default()
}
Comment thread
DRadmir marked this conversation as resolved.
Outdated

#[cfg(test)]
mod tests {
use super::*;
use crate::models::balance::ValidatorStats;
use crate::models::balance::{DelegatorDelta, DelegatorWithdrawal, ValidatorStats};
use primitives::{Chain, DelegationState};

fn withdrawal_entry(time: u64, amount: f64, phase: WithdrawalPhase) -> DelegatorHistoryEntry {
DelegatorHistoryEntry {
time,
delta: DelegatorDelta {
withdrawal: Some(DelegatorWithdrawal { amount, phase }),
},
}
}

#[test]
fn test_map_staking_validators() {
let validators = vec![Validator {
Expand All @@ -52,13 +99,18 @@ mod tests {
}];

let result = map_staking_validators(validators, Chain::HyperCore, None);
assert_eq!(result.len(), 1);
assert_eq!(result.len(), 2);
assert_eq!(result[0].name, "Test Validator");
assert_eq!(result[0].id, "0x5aC99df645F3414876C816Caa18b2d234024b487");
assert_eq!(result[0].chain, Chain::HyperCore);
assert!(result[0].is_active);
assert_eq!(result[0].commission, 5.0);
assert_eq!(result[0].apr, 15.0); // max_apr * 100

let system = &result[1];
assert_eq!(system.id, DelegationValidator::SYSTEM_ID);
assert_eq!(system.name, DelegationValidator::SYSTEM_NAME);
assert!(system.is_active);
}

#[test]
Expand All @@ -72,15 +124,16 @@ mod tests {
}];

let result = map_staking_validators(validators, Chain::HyperCore, Some(10.0));
assert_eq!(result.len(), 1);
assert_eq!(result.len(), 2);
assert_eq!(result[0].apr, 10.0); // Uses provided APY
assert_eq!(result[1].id, DelegationValidator::SYSTEM_ID);
}

#[test]
fn test_map_staking_delegations() {
let delegations: Vec<DelegationBalance> = serde_json::from_str(include_str!("../../testdata/staking_delegations.json")).unwrap();

let result = map_staking_delegations(delegations, Chain::HyperCore);
let result = map_staking_delegations(delegations, vec![], Utc::now(), Chain::HyperCore);

assert_eq!(result.len(), 2);

Expand All @@ -98,4 +151,29 @@ mod tests {
assert_eq!(delegation2.validator_id, "0xaBCDefF4b3727B83A23697500EEf089020DF2cD2");
assert_eq!(delegation2.balance.to_string(), "1814578086");
}

#[test]
fn test_map_staking_delegations_pending_withdrawals() {
let now = DateTime::from_timestamp(1_780_000_000, 0).unwrap();
let history = vec![
withdrawal_entry(1_779_913_600_000, 1.5, WithdrawalPhase::Initiated),
withdrawal_entry(1_779_308_800_000, 2.0, WithdrawalPhase::Initiated),
withdrawal_entry(1_779_950_000_000, 3.0, WithdrawalPhase::Finalized),
DelegatorHistoryEntry {
time: 1_779_950_000_001,
delta: DelegatorDelta { withdrawal: None },
},
];

let result = map_staking_delegations(vec![], history, now, Chain::HyperCore);

assert_eq!(result.len(), 1);
let pending = &result[0];
assert!(matches!(pending.state, DelegationState::Pending));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just use assert_eq here

assert_eq!(pending.validator_id, DelegationValidator::SYSTEM_ID);
assert_eq!(pending.balance.to_string(), "150000000");
assert_eq!(pending.delegation_id, "unstaking_1779913600000");
assert_eq!(pending.completion_date, Some(now + Duration::seconds(518_400)));
assert!(pending.completion_date.unwrap() > now);
}
}
6 changes: 5 additions & 1 deletion crates/gem_hypercore/src/rpc/client.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::models::{
balance::{Balances, DelegationBalance, StakeBalance, Validator},
balance::{Balances, DelegationBalance, DelegatorHistoryEntry, StakeBalance, Validator},
candlestick::Candlestick,
metadata::HypercoreMetadataResponse,
order::{OpenOrder, UserFill},
Expand Down Expand Up @@ -115,6 +115,10 @@ impl<C: Client> HyperCoreClient<C> {
self.info(json!({"type": "delegations", "user": user})).await
}

pub async fn get_staking_history(&self, user: &str) -> Result<Vec<DelegatorHistoryEntry>, Box<dyn Error + Send + Sync>> {
self.info(json!({"type": "delegatorHistory", "user": user})).await
}

pub async fn get_staking_apy(&self) -> Result<f64, Box<dyn Error + Send + Sync>> {
let validators = self.get_validators().await?;
Ok(Validator::max_apr(validators))
Expand Down
28 changes: 15 additions & 13 deletions crates/gem_hypercore/src/signer/core_signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,7 @@ impl HyperCoreSigner {
Ok(vec![deposit_action, delegate_action])
}
StakeType::Unstake(delegation) => {
let balance = delegation.base.balance.to_string();
let wei = BigNumberFormatter::value_as_u64(&balance, 0).map_err(|err| SignerError::InvalidInput(err.to_string()))?;
let wei = BigNumberFormatter::value_as_u64(&input.value, 0).map_err(|err| SignerError::InvalidInput(err.to_string()))?;

let undelegate_request = TokenDelegate::new(delegation.validator.id.clone(), wei, true, nonce_incrementer.next_val());
let undelegate_action = self.sign_token_delegate(undelegate_request, private_key)?;
Expand Down Expand Up @@ -438,7 +437,7 @@ mod tests {
}

#[test]
fn unstake_actions_have_unique_nonces() {
fn unstake_uses_entered_amount_and_unique_nonces() {
let signer = HyperCoreSigner;
let asset = Asset::from_chain(Chain::HyperCore);
let delegation = Delegation {
Expand All @@ -456,7 +455,7 @@ mod tests {
price: None,
};
let input = TransactionLoadInput {
value: "0".into(),
value: "60000000".into(),
sender_address: "0xsender".into(),
destination_address: "".into(),
..TransactionLoadInput::mock_with_input_type(TransactionInputType::Stake(asset, StakeType::Unstake(delegation)))
Expand All @@ -467,16 +466,19 @@ mod tests {
let responses = signer.sign_stake_action(&input, &private_key).expect("should sign");
assert_eq!(responses.len(), 2);

let nonces: Vec<u64> = responses
.iter()
.map(|payload| {
let value: serde_json::Value = serde_json::from_str(payload).expect("valid json");
value["action"]["nonce"].as_u64().expect("action nonce")
})
.collect();
let undelegate: serde_json::Value = serde_json::from_str(&responses[0]).expect("json");
let withdraw: serde_json::Value = serde_json::from_str(&responses[1]).expect("json");

assert_eq!(undelegate["action"]["type"], "tokenDelegate");
assert_eq!(undelegate["action"]["isUndelegate"], true);
assert_eq!(withdraw["action"]["type"], "cWithdraw");

assert_eq!(undelegate["action"]["wei"].as_u64().expect("undelegate wei"), 60000000);
assert_eq!(withdraw["action"]["wei"].as_u64().expect("withdraw wei"), 60000000);

assert_eq!(nonces.len(), 2);
assert!(nonces[0] < nonces[1], "unstake actions should advance nonce");
let undelegate_nonce = undelegate["action"]["nonce"].as_u64().expect("nonce");
let withdraw_nonce = withdraw["action"]["nonce"].as_u64().expect("nonce");
assert!(undelegate_nonce < withdraw_nonce, "unstake actions should advance nonce");
}

#[test]
Expand Down
4 changes: 1 addition & 3 deletions crates/gem_tron/src/provider/staking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ use super::staking_mapper::map_staking_validators;
use crate::rpc::client::TronClient;
use crate::rpc::constants::{GET_WITNESS_127_PAY_PER_BLOCK, GET_WITNESS_PAY_PER_BLOCK};

const SYSTEM_VALIDATOR_ID: &str = "system";

#[async_trait]
impl<C: Client + Clone> ChainStaking for TronClient<C> {
async fn get_staking_apy(&self) -> Result<Option<f64>, Box<dyn Error + Sync + Send>> {
Expand Down Expand Up @@ -70,7 +68,7 @@ impl<C: Client + Clone> ChainStaking for TronClient<C> {
rewards: BigUint::from(0u32),
completion_date: Some(completion_date),
delegation_id: completion_date.timestamp().to_string(),
validator_id: SYSTEM_VALIDATOR_ID.to_string(),
validator_id: DelegationValidator::SYSTEM_ID.to_string(),
});
}
}
Expand Down
16 changes: 3 additions & 13 deletions crates/gem_tron/src/provider/staking_mapper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@ use crate::address::TronAddress;
use crate::models::WitnessesList;
use primitives::{Address as _, Chain, DelegationValidator, StakeValidator};

const SYSTEM_UNSTAKING_VALIDATOR_ID: &str = "system";
const SYSTEM_UNSTAKING_VALIDATOR_NAME: &str = "Unstaking";

pub fn map_validators(witnesses: WitnessesList) -> Vec<StakeValidator> {
witnesses.witnesses.into_iter().map(|x| StakeValidator::new(x.address, x.url)).collect()
}
Expand All @@ -26,14 +23,7 @@ pub fn map_staking_validators(witnesses: WitnessesList, apy: Option<f64>) -> Vec
})
.collect();

validators.push(DelegationValidator::stake(
Chain::Tron,
SYSTEM_UNSTAKING_VALIDATOR_ID.to_string(),
SYSTEM_UNSTAKING_VALIDATOR_NAME.to_string(),
true,
0.0,
default_apy,
));
validators.push(DelegationValidator::system(Chain::Tron));

validators
}
Expand Down Expand Up @@ -79,8 +69,8 @@ mod tests {
assert_eq!(validators[1].id, "TEqyWRKCzREYC2bK2fc3j7pp8XjAa6tJK1");
assert!(!validators[1].is_active);

assert_eq!(validators[2].id, SYSTEM_UNSTAKING_VALIDATOR_ID);
assert_eq!(validators[2].name, SYSTEM_UNSTAKING_VALIDATOR_NAME);
assert_eq!(validators[2].id, DelegationValidator::SYSTEM_ID);
assert_eq!(validators[2].name, DelegationValidator::SYSTEM_NAME);
assert!(validators[2].is_active);
}
}
Loading
Loading