Skip to main content

df_hyperliquid_core/transfer/
evm.rs

1//! HyperCore and HyperEVM, linked. A linked spot token crosses between Core and EVM spot through
2//! its system address: `0x2222...2222` for HYPE, `0x20`, zeros and the token index for any other.
3//! Core to EVM is a `spotSend` or `sendAsset` to [`Linked::system`]; EVM to Core is a HyperEVM
4//! transaction to the same address ([`Linked::to_core`]). A send to a system address leaves Core
5//! rather than reaching a person, so a transfer checks for them. `sendToEvmWithData` sends a linked
6//! token to its contract with a payload, for contracts that take `coreReceiveWithData`.
7
8use crate::account::{ActionKind, Signers};
9use crate::client::evm::tx::Call;
10use crate::client::evm::u256::{BadAmount, NATIVE_DECIMALS, U256};
11use crate::transfer::erc20;
12use crate::transfer::send::Amount;
13use crate::utils::sign::{Field, NonceKey, UserAction, UserSigned};
14use crate::utils::{Address, Dec};
15
16/// HYPE's system address, `0x2222...2222`: HYPE is the native coin on HyperEVM.
17pub const HYPE_SYSTEM: Address = Address::from_bytes([0x22; 20]);
18
19/// The address a linked spot token crosses through: `0x20`, then the token
20/// index big-endian in the low bytes. Token 200 is `0x2000...00c8`.
21#[must_use]
22pub fn system_address(index: u64) -> Address {
23    let mut bytes = [0u8; 20];
24    bytes[0] = 0x20;
25    bytes[12..].copy_from_slice(&index.to_be_bytes());
26    Address::from_bytes(bytes)
27}
28
29/// Whether a send to `address` crosses between Core and HyperEVM rather than
30/// reaching a person: `0x2222...2222`, or `0x20`, zeros and a token index.
31#[must_use]
32pub fn is_system_address(address: Address) -> bool {
33    address == HYPE_SYSTEM || system_token(address).is_some()
34}
35
36/// The token index a `0x20` system address stands for; `None` for HYPE's,
37/// which crosses natively.
38#[must_use]
39pub fn system_token(address: Address) -> Option<u64> {
40    let bytes = address.bytes();
41    if bytes[0] != 0x20 || bytes[1..12].iter().any(|byte| *byte != 0) {
42        return None;
43    }
44    let mut index = [0u8; 8];
45    index.copy_from_slice(&bytes[12..]);
46    Some(u64::from_be_bytes(index))
47}
48
49/// A spot token as it is linked to HyperEVM. Its contract can hold arbitrary code; nothing here
50/// checks its supply or what its `transfer` does.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52#[non_exhaustive]
53pub struct Linked {
54    /// The token's index in `spotMeta`.
55    pub index: u64,
56    /// The ERC-20; `None` for HYPE, which is the chain's native coin.
57    pub contract: Option<Address>,
58    /// The decimals Core counts the token in (`spotMeta`'s `weiDecimals`).
59    pub wei_decimals: u32,
60    /// How many more the ERC-20 counts in, -2 to 18.
61    pub evm_extra_wei_decimals: i32,
62}
63
64impl Linked {
65    /// HYPE: native on HyperEVM, eighteen decimals there.
66    #[must_use]
67    pub const fn hype(wei_decimals: u32) -> Linked {
68        Linked { index: 0, contract: None, wei_decimals, evm_extra_wei_decimals: 0 }
69    }
70
71    /// A token linked to an ERC-20 (`spotMeta`'s `evmContract`).
72    #[must_use]
73    pub const fn erc20(index: u64, contract: Address, wei_decimals: u32, evm_extra_wei_decimals: i32) -> Linked {
74        Linked { index, contract: Some(contract), wei_decimals, evm_extra_wei_decimals }
75    }
76
77    /// Where the token crosses, both ways. Sent there on Core, it arrives at the sender's address
78    /// on HyperEVM.
79    #[must_use]
80    pub fn system(&self) -> Address {
81        match self.contract {
82            None => HYPE_SYSTEM,
83            Some(_) => system_address(self.index),
84        }
85    }
86
87    /// The decimals the token counts in on HyperEVM.
88    #[must_use]
89    pub fn evm_decimals(&self) -> Option<u32> {
90        match self.contract {
91            None => Some(NATIVE_DECIMALS),
92            Some(_) => u32::try_from(i64::from(self.wei_decimals) + i64::from(self.evm_extra_wei_decimals)).ok(),
93        }
94    }
95
96    /// The most places an amount crossing either way may have: the fewer of
97    /// Core's and the EVM's.
98    #[must_use]
99    pub fn core_places(&self) -> Option<u32> {
100        self.evm_decimals().map(|evm| evm.min(self.wei_decimals))
101    }
102
103    /// The HyperEVM call that sends `amount` back to Core: HYPE as a plain value transfer, any
104    /// other token as an ERC-20 `transfer` to the system address. Exact, positive, and no finer
105    /// than [`Linked::core_places`].
106    pub fn to_core(&self, amount: Dec) -> Result<Call, BadAmount> {
107        let places = self.core_places().ok_or(BadAmount::TooLarge)?;
108        let decimals = self.evm_decimals().ok_or(BadAmount::TooLarge)?;
109        if !amount.is_positive() {
110            return Err(BadAmount::NotPositive(amount));
111        }
112        if amount.places() > places {
113            return Err(BadAmount::TooFine { value: amount, decimals: places });
114        }
115        let units = U256::from_dec(amount, decimals)?;
116        Ok(match self.contract {
117            None => Call { to: Some(HYPE_SYSTEM), value: units, data: Vec::new() },
118            Some(contract) => {
119                Call { to: Some(contract), value: U256::ZERO, data: erc20::transfer(self.system(), units) }
120            }
121        })
122    }
123}
124
125/// How `destinationRecipient` is written.
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127#[non_exhaustive]
128pub enum AddressEncoding {
129    /// `0x` and hex: an EVM address.
130    Hex,
131    /// Base58: an address on a chain such as Solana.
132    Base58,
133}
134
135impl AddressEncoding {
136    /// `hex` or `base58`.
137    #[must_use]
138    pub const fn wire(self) -> &'static str {
139        match self {
140            AddressEncoding::Hex => "hex",
141            AddressEncoding::Base58 => "base58",
142        }
143    }
144}
145
146/// Where the linked contract is asked to send the token on: a recipient in its encoding, on a
147/// chain by its id. The contract reads both; the venue passes them through.
148#[derive(Debug, Clone, PartialEq, Eq)]
149pub struct Destination {
150    recipient: String,
151    encoding: AddressEncoding,
152    chain_id: u32,
153}
154
155impl Destination {
156    /// An EVM address on the chain `chain_id`, written lowercase.
157    #[must_use]
158    pub fn evm(recipient: Address, chain_id: u32) -> Destination {
159        Destination { recipient: recipient.to_hex(), encoding: AddressEncoding::Hex, chain_id }
160    }
161
162    /// A base58 address on the chain `chain_id`, as given.
163    #[must_use]
164    pub fn base58(recipient: &str, chain_id: u32) -> Destination {
165        Destination { recipient: recipient.to_owned(), encoding: AddressEncoding::Base58, chain_id }
166    }
167
168    /// The recipient as posted.
169    #[must_use]
170    pub fn recipient(&self) -> &str {
171        &self.recipient
172    }
173
174    /// How the recipient is written.
175    #[must_use]
176    pub const fn encoding(&self) -> AddressEncoding {
177        self.encoding
178    }
179
180    /// The chain the recipient is on.
181    #[must_use]
182    pub const fn chain_id(&self) -> u32 {
183        self.chain_id
184    }
185}
186
187/// `sendToEvmWithData`: a linked token from a Core balance to its contract on HyperEVM, which the
188/// venue calls with `coreReceiveWithData(from, destinationRecipient, destinationChainId, amount,
189/// nonce, data)` in place of a transfer. The token must be linked to a contract that takes that
190/// call; nothing here checks it. User-signed, keys in the order `@nktkas/hyperliquid` 0.33.3 posts
191/// them: `token`, `amount`, `sourceDex`, `destinationRecipient`, `addressEncoding`,
192/// `destinationChainId`, `gasLimit`, `data` as `0x` and hex (signed as `bytes`), then the nonce.
193#[derive(Debug, Clone, PartialEq, Eq)]
194pub struct SendToEvmWithData {
195    token: String,
196    amount: Amount,
197    source_dex: String,
198    destination: Destination,
199    gas_limit: u64,
200    data: Vec<u8>,
201    nonce: u64,
202}
203
204impl SendToEvmWithData {
205    /// User-signed: only the account's own key.
206    pub const KEY: Signers = ActionKind::SendToEvmWithData.signers();
207
208    /// `amount` of `token` (`NAME:0x<tokenId>`, as `spotMeta` lists it) from the balance
209    /// `source_dex` names (`""` the main perp dex, `spot` the spot balance), for `destination`,
210    /// with `gas_limit` for the call on the destination chain and `data` passed to the contract.
211    #[must_use]
212    pub fn new(
213        token: &str,
214        amount: Amount,
215        source_dex: &str,
216        destination: Destination,
217        gas_limit: u64,
218        data: Vec<u8>,
219        nonce: u64,
220    ) -> SendToEvmWithData {
221        SendToEvmWithData {
222            token: token.to_owned(),
223            amount,
224            source_dex: source_dex.to_owned(),
225            destination,
226            gas_limit,
227            data,
228            nonce,
229        }
230    }
231
232    /// The amount sent.
233    #[must_use]
234    pub const fn amount(&self) -> &Amount {
235        &self.amount
236    }
237
238    /// Where the contract is asked to send it on.
239    #[must_use]
240    pub const fn destination(&self) -> &Destination {
241        &self.destination
242    }
243
244    /// The payload the contract is called with.
245    #[must_use]
246    pub fn data(&self) -> &[u8] {
247        &self.data
248    }
249}
250
251impl UserAction for SendToEvmWithData {
252    fn user_signed(&self) -> UserSigned<'_> {
253        UserSigned::new("sendToEvmWithData", "HyperliquidTransaction:SendToEvmWithData", NonceKey::Nonce, self.nonce)
254            .field("token", Field::String(&self.token))
255            .field("amount", Field::String(self.amount.as_str()))
256            .field("sourceDex", Field::String(&self.source_dex))
257            .field("destinationRecipient", Field::String(&self.destination.recipient))
258            .field("addressEncoding", Field::String(self.destination.encoding.wire()))
259            .field("destinationChainId", Field::Uint32(self.destination.chain_id))
260            .field("gasLimit", Field::Uint64(self.gas_limit))
261            .field("data", Field::Bytes(&self.data))
262    }
263}
264
265#[cfg(test)]
266#[path = "tests/evm.rs"]
267mod tests;