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