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)]
17#[non_exhaustive]
18pub enum BadSigners {
19    /// Fewer than one signer, or more than [`MOST_SIGNERS`], once repeats are counted once.
20    #[error("a multi-sig account has 1 to {MOST_SIGNERS} signers, not {0}")]
21    Count(usize),
22    /// A threshold of zero, or more than there are signers.
23    #[error("a threshold is 1 to the number of signers ({signers}), not {threshold}")]
24    Threshold {
25        /// The threshold asked for.
26        threshold: u8,
27        /// How many distinct signers there are.
28        signers: usize,
29    },
30}
31
32/// `convertToMultiSigUser`, signed by the account's own key while it is a normal account.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct ConvertToMultiSigUser {
35    signers: String,
36    nonce: u64,
37}
38
39impl ConvertToMultiSigUser {
40    /// User-signed: only the account's own key.
41    pub const KEY: Signers = ActionKind::ConvertToMultiSigUser.signers();
42
43    /// Any `threshold` of `authorized` may act for the account. Each signer must already be an
44    /// account on the venue; a repeated address counts once.
45    pub fn new(authorized: &[Address], threshold: u8, nonce: u64) -> Result<ConvertToMultiSigUser, BadSigners> {
46        let mut users: Vec<String> = authorized.iter().map(|user| user.to_hex()).collect();
47        users.sort();
48        users.dedup();
49        if users.is_empty() || users.len() > MOST_SIGNERS {
50            return Err(BadSigners::Count(users.len()));
51        }
52        if threshold == 0 || usize::from(threshold) > users.len() {
53            return Err(BadSigners::Threshold { threshold, signers: users.len() });
54        }
55        let signers = Json::Object(vec![
56            ("authorizedUsers".to_owned(), Json::Array(users.into_iter().map(Json::String).collect())),
57            ("threshold".to_owned(), Json::Number(threshold.to_string())),
58        ]);
59        Ok(ConvertToMultiSigUser { signers: signers.compact(), nonce })
60    }
61
62    /// Back to a normal account: `signers` is `null`, as `@nktkas/hyperliquid` 0.33.3 writes it.
63    #[must_use]
64    pub fn single(nonce: u64) -> ConvertToMultiSigUser {
65        ConvertToMultiSigUser { signers: "null".to_owned(), nonce }
66    }
67
68    /// `signers` as posted and signed.
69    #[must_use]
70    pub fn signers(&self) -> &str {
71        &self.signers
72    }
73}
74
75impl UserAction for ConvertToMultiSigUser {
76    fn user_signed(&self) -> UserSigned<'_> {
77        UserSigned::new(
78            "convertToMultiSigUser",
79            "HyperliquidTransaction:ConvertToMultiSigUser",
80            NonceKey::Nonce,
81            self.nonce,
82        )
83        .field("signers", Field::String(&self.signers))
84    }
85}
86
87#[cfg(test)]
88#[path = "tests/multi_sig.rs"]
89mod tests;