This repository was archived by the owner on Jun 1, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 53
Hyperliquid: fix partial unstake and show pending unstaking #1166
Merged
Merged
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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")] | ||
|
|
@@ -57,6 +58,53 @@ impl DelegationBalance { | |
| } | ||
| } | ||
|
|
||
| #[derive(Debug, Clone, Serialize, Deserialize)] | ||
| #[serde(rename_all = "camelCase")] | ||
| pub struct DelegatorHistoryEntry { | ||
| pub time: u64, | ||
| pub delta: DelegatorDelta, | ||
| } | ||
|
|
||
| #[derive(Debug, Clone, Serialize, Deserialize)] | ||
| #[serde(rename_all = "camelCase")] | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. same here, |
||
| 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")] | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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")] |
||
| 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() | ||
| } | ||
| } | ||
|
DRadmir marked this conversation as resolved.
Outdated
|
||
|
|
||
| #[derive(Debug, Clone, Serialize, Deserialize)] | ||
| #[serde(rename_all = "camelCase")] | ||
| pub struct Validator { | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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() | ||
| } | ||
|
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 { | ||
|
|
@@ -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] | ||
|
|
@@ -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); | ||
|
|
||
|
|
@@ -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)); | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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