Skip to main content

df_hyperliquid_core/account/keys/
multi_sig.rs

1//! `convertToMultiSigUser`: turns an account into a multi-sig account, changes its signers, or
2//! turns it back into a normal account. User-signed: `signers` is a JSON text, signed as a string,
3//! `{"authorizedUsers":[..],"threshold":n}` or `null`, written compactly as `@nktkas/hyperliquid`
4//! 0.33.3 writes it, the addresses lowercase and sorted as the venue's Python SDK sorts them. Once
5//! converted, every action of the account must be sent through multi-sig, a change of signers or a
6//! conversion back included; [`MultiSig`](crate::utils::sign::MultiSig) wraps L1 actions only.
7
8use crate::account::{ActionKind, Signers};
9use crate::utils::sign::{Field, NonceKey, UserAction, UserSigned};
10use crate::utils::{Address, Json};
11
12/// The most signers a multi-sig account may have.
13pub const MOST_SIGNERS: usize = 10;
14
15/// A set of signers the venue would not take.
16#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
17pub enum BadSigners {
18    /// Fewer than one signer, or more than [`MOST_SIGNERS`], once repeats are counted once.
19    #[error("a multi-sig account has 1 to {MOST_SIGNERS} signers, not {0}")]
20    Count(usize),
21    /// A threshold of zero, or more than there are signers.
22    #[error("a threshold is 1 to the number of signers ({signers}), not {threshold}")]
23    Threshold {
24        /// The threshold asked for.
25        threshold: u8,
26        /// How many distinct signers there are.
27        signers: usize,
28    },
29}
30
31/// `convertToMultiSigUser`, signed by the account's own key while it is a normal account.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct ConvertToMultiSigUser {
34    signers: String,
35    nonce: u64,
36}
37
38impl ConvertToMultiSigUser {
39    /// User-signed: only the account's own key.
40    pub const KEY: Signers = ActionKind::ConvertToMultiSigUser.signers();
41
42    /// Any `threshold` of `authorized` may act for the account. Each signer must already be an
43    /// account on the venue; a repeated address counts once.
44    pub fn new(authorized: &[Address], threshold: u8, nonce: u64) -> Result<ConvertToMultiSigUser, BadSigners> {
45        let mut users: Vec<String> = authorized.iter().map(|user| user.to_hex()).collect();
46        users.sort();
47        users.dedup();
48        if users.is_empty() || users.len() > MOST_SIGNERS {
49            return Err(BadSigners::Count(users.len()));
50        }
51        if threshold == 0 || usize::from(threshold) > users.len() {
52            return Err(BadSigners::Threshold { threshold, signers: users.len() });
53        }
54        let signers = Json::Object(vec![
55            ("authorizedUsers".to_owned(), Json::Array(users.into_iter().map(Json::String).collect())),
56            ("threshold".to_owned(), Json::Number(threshold.to_string())),
57        ]);
58        Ok(ConvertToMultiSigUser { signers: signers.compact(), nonce })
59    }
60
61    /// Back to a normal account: `signers` is `null`, as `@nktkas/hyperliquid` 0.33.3 writes it.
62    #[must_use]
63    pub fn single(nonce: u64) -> ConvertToMultiSigUser {
64        ConvertToMultiSigUser { signers: "null".to_owned(), nonce }
65    }
66
67    /// `signers` as posted and signed.
68    #[must_use]
69    pub fn signers(&self) -> &str {
70        &self.signers
71    }
72}
73
74impl UserAction for ConvertToMultiSigUser {
75    fn user_signed(&self) -> UserSigned<'_> {
76        UserSigned::new(
77            "convertToMultiSigUser",
78            "HyperliquidTransaction:ConvertToMultiSigUser",
79            NonceKey::Nonce,
80            self.nonce,
81        )
82        .field("signers", Field::String(&self.signers))
83    }
84}
85
86#[cfg(test)]
87#[path = "tests/multi_sig.rs"]
88mod tests;