Hyperliquid 백서

Hyperliquid

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 27쪽 중 18쪽

n_user_signed_action`).\ 2\. Not realizing that the order of fields matter for msgpack.\ 3\. Issues with trailing zeroes on numbers.\ 4\. Issues with upper case characters in address fields. It is recommended to lowercase any address before signing and sending. Sometimes the field is parsed as bytes, causing it to be lowercased automatically across the network.\ 5\. Believing that the signature must be correct because calling recover signer locally results in the correct address. The payload for recover signer is constructed based on the action and does not necessarily match. # Rate limits and user limits The following rate limits apply per IP address: * REST requests share an aggregated weight limit of 1200 per minute.&#x20; * All documented `exchange` API requests have a weight of `1 + floor(batch_length / 40)`. For example, unbatched actions have weight `1` and a batched order request of length 79 has weight `2`. Here, `batch_length`is the length of the array in the action, e.g. the number of orders in a batched order action. * The following `info` requests have weight 2: `l2Book, allMids, clearinghouseState, orderStatus, spotClearinghouseState, exchangeStatus.` * The following `info` requests have weight 60: `userRole` . * All other documented `info` requests have weight 20.&#x20; * The following `info` endpoints have an additional rate limit weight per 20 items returned in the response: `recentTrades`, `historicalOrders`, `userFills`, `userFillsByTime`, `fundingHistory`, `userFunding`, `nonUserFundingUpdates`, `twapHistory`, `userTwapSliceFills`, `userTwapSliceFillsByTime`, `delegatorHistory`, `delegatorRewards`, `validatorStats` . * The `candleSnapshot` info endpoint has an additional rate limit weight per 60 items returned in the response. * All `explorer` API requests have a weight of 40. `blockList` has an additional rate limit of 1 per block. Note that older blocks which have not been recently queried may be weighted more heavily. For large batch requests, use the S3 bucket instead. * Maximum of 10 websocket connections * Maximum of 30 new websocket connections per minute * Maximum of 1000 websocket subscriptions * Maximum of 10 unique users across user-specific websocket subscriptions * Maximum of 2000 messages sent to Hyperliquid per minute across all websocket connections * Maximum of 100 simultaneous inflight post messages across all websocket connections * Maximum of 100 EVM JSON-RPC requests per minute for `rpc.hyperliquid.xyz/evm`. Note that other JSON-RPC providers have more sophisticated rate limiting logic and archive node functionality.&#x20; Use websockets for lowest latency realtime data. See the python SDK for a full-featured example. ### Address-based limits Address-based limits apply per user, with sub-accounts treated as separate users. The rate limiting logic allows 1 request per 1 USDC traded cumulatively since address inception. For example, with an order value of 100 USDC, this requires a fill rate of 1%. Each address starts with an initial buffer of 10000 requests. When rate limited, an address is allowed one request every 10 seconds. Cancels have cumulative limit `min(limit + 100000, limit * 2)` where `limit` is the default limit for other actions. This way, hitting the address-based rate limit still allows open orders to be canceled. Note that this rate limit only applies to actions, not info requests.&#x20; Each user has a default open order limit of 1000 plus one additional order for every 5M USDC of volume, capped at a total of 5000 open orders. When an order is placed with at least 1000 other open orders by the same user, it will be rejected if it is reduce-only or a trigger order.&#x20; During high congestion, addresses are limited to use 2x their previous day maker share percentage of the block space. The maker share is scaled by the same factor as the volume contribution of that asset towards fee tiers. For example, HIP-3 assets under growth mode count less towards this rate limit. The maker share is computed once per UTC date. During high traffic, it can therefore be helpful to not resend cancels whose results have already been returned via the API.&#x20; ### Batched Requests A batched request with `n` orders (or cancels) is treated as one request for IP based rate limiting, but as `n` requests for address-based rate limiting. &#x20; # Activation gas fee New HyperCore accounts require 1 quote token (e.g., 1 USDC, 1 USDT) of fees for the first transaction which has the new account as destination address. This applies regardless of the asset being transfered to the new account.&#x20; Unactivated accounts cannot send CoreWriter actions. Contract deployers who do not want this one-time behavior could manually send an activation transaction to the EVM contract address on HyperCore.&#x20; # Optimizing latency The suggestions below are for informational purposes only and a non-comprehensive starting point. They are not trading advice and do not guarantee any latency or trading outcome.&#x20; ### Optimizing read latency (receiving market data) 1. Run a non-validating node against a reliable peer, such as Hyper Foundation non-validator.&#x20; 2. Run node with `--disable-output-file-buffering` to get outputs as soon as blocks are executed 3. Run node with sufficient machines specs, at least 32 logical cores, 128 GB RAM, and 500 MB/s disk throughput. Increasing cores can reduce latency because blocks will be faster to execute. 4. Construct book and other exchange state locally using outputs from node, which has faster and more granular data than the API. See <https://github.com/hyperliquid-dex/order_book_server> for an example on how to build an order book on the same machine that is running a node. This repo is not actively maintained. It is recommended to fork the repo or write an implementation from scratch to incorporate details such as ALO priority fees or other edge cases. 5. `--batch-by-block` on the node will wait until the end of the block to write the data. The example order book server above uses this to simplify logic, but a further optimization could include turning the flag off and inferring block boundaries otherwise. 6. Latency-sensitive users may find `split_client_blocks: true` useful, as it streams transactions to be committed before they are included in client blocks. This can lead to 70-150ms improvement in latency when reading inputs. As documented in the node repository, these are the fastest transaction inputs to execution, broadcast even before they are executed by the L1. The tradeoff with the faster input data is that the results from execution are not yet available. However, with simple actions like orders, the consumer can stream estimated account values for all users to predict execution results with reasonable accuracy. 7. The foundation non-validator is one of the highest uptime and low latency non-validator peers. See [here](/hyperliquid-docs/for-developers/nodes/foundation-non-validating-node) for details on access for latency-sensitive users. &#x20; 8. Read priority fees are the fastest way to read raw data from the network. See [here](/hyperliquid-docs/for-developers/api/priority-fees) for more details.&#x20; ### Optimizing write latency (sending orders and cancels) 1. Cancels should be sent with the [fast](/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s) flag. There is no disadvantage to the fast flag, except that fast cancels cannot be used to cancel trigger orders.&#x20; 2. Write priority fees are the fastest way to send orders to the network. See [here](/hyperliquid-docs/for-developers/api/priority-fees) for more details.&#x20; 3. Hyperliquid's execution logic is designed to protect makers against toxic flow, so that end users see tight spreads and deep liquidity even during volatility. The primary driver of this effect is that cancels and ALO orders sent at time `t` will almost always execute before IOC and GTC orders sent at time `t`. This prioritization spans several blocks. The secondary effect is that each L1 block contains only a few consensus bundles. Within each bundle, ALO and cancels are executed before other transactions.&#x20; 4. End-to-end latency on Hyperliquid is not apples-to-apples with centralized matching engines, because the order book is fully onchain. End-to-end latency includes time to API server, mempool inclusion time, and time to commit (usually 2 blocks in pipelined HyperBFT consensus). The sequencing of transactions has far less noise than the end-to-end latency suggests. While a cancel or ALO order can show \~380ms end-to-end latency, users should be able to run experiments with <10ms variation between send times and see predictable ordering on the L1.&#x20; 5. Users who care to reduce the end-to-end write latency (for example to predict the sequence of transactions that will be committed) can read them from split client blocks in the non-validating node (see read latency section above). This approach does not include the execution result of the transaction. # Priority fees Advanced feature for latency-sensitive users ### Gossip (read) priority There are 2 independent Dutch auctions synced to the same 3 minute schedule. The auction indices are optionally interpreted by nodes as an ordering for their peers when sending data. The priority ordering affects both split client blocks and normal client blocks that include responses. The foundation non-validator will opt into respecting the gossip priority auction ordering.&#x20; The independent slot auctions are not additive, so an IP bidding multiple slots will be prioritized according to its lowest slot. For the auction to affect latency, the onchain IP must exactly match the IP seen by the peer sending data. Each auction's results only affect the duration of the following auction. For nodes that are connected via a chain of nodes to the validating network, note that each network hop may or may not respect the priority auction depending on how the parent node is configured.&#x20; The lower auction indices are strictly prioritized over higher indices. The prioritization applies to all data in the mempool transactions stream equally. The ordering should be relatively consistent in expectation but is subject to variance from the p2p consensus network. Gossip priority applies only to reading data. For prioritization of sending data, see the section below on order priority. Nodes respecting gossip priority will use the previous auction winners relative to that node's current execution state. Similar to token, spot, and perp deployment auctions, fees come out of spot balance are burned. The previous auction winners (i.e., current gossip priority ordering) and current auction statuses can be queried using the info request `{ "type": "gossipPriorityAuctionStatus"}`.&#x20; Gossip priority reduces the need for market makers to hyper-optimize their infrastructure to remain competitive. To participate in the auction, users send action `{"type": "gossipPriorityBid", "slotId": 0, "ip": "1.2.3.4", "maxGas": 100000000}` where gas is wei (i.e. units of `0.00000001` HYPE) of HYPE charged from spot balance. Each auction resets to 10 times the previous winning price of that slot, and have a minimum price of `0.1 HYPE`. Any address may bid on behalf of any IP address.&#x20; The current empirical effect of gossip priority on mainnet is approximately 25 ms reduction in latency per auction slot. ### Order (write) priority Order priority reduces the need for market makers to hyper-optimize their order entry and connectivity, and instead focus on the strategy itself. It further protects makers and allows responsiveness to price moves driven by other venues. Priority grouping is only supported for order actions where both 1. every order is on a non-outcome asset 2. every order is IOC, or every order is a non-reduce-only ALO Orders can be sent with grouping of the form `{"p": 12345}` where the rate is interpreted as a fraction `p / 100000000.0`. The rate is charged from undelegated staking balance as a fraction of the filled notional in the case of IOC, and resting notional in the case of ALO. The priority gas charged is converted to HYPE using the spot mark price. &#x20; #### IOC priority The priority rate has a linear effect on end-to-end latency from 0-8bps, i.e. `p = 80000`. The current empirical effect of order priority fees on mainnet is approximately 45 ms reduction in end-to-end latency per 1 bp of priority fee paid. Even with order priority, all cancels are prioritized before all immediately executable orders. However, higher priority orders are prioritized before lower priority orders as a linear function of priority rate.&#x20; The max priority rate is 100%. Any priority between 8bps and 100% is treated with identical time preference in the mempool. However, IOC orders with at least 8bps priority fee that would be executed by the block proposer in each 70ms unix time bucket (usually corresponding to 1 block) are sorted in decreasing order of priority fee. In other words, the 0-8bps range effects temporal prioritization, and 8bps-100% range breaks ties among orders in this range received at a similar time. As a concrete example, if the unix milliseconds boundary is `(T, T + 70ms)` , the orders with `(mempool_receive_time, priority)` equal to `(T, 8bps)`, `(T + 30ms, 9bps)`, `(T + 69ms, 10bps)` would be sorted in reverse order of receive time. Although blocks are discrete, order prioritization is continuous with respect to order write priority fee. The mempool transactions are effectively sorted by `effective_time = arrival_time + f(action, priority_fee)` where `f` is a strictly decreasing function of priority fee, and zero for prioritized actions such as cancels. For a given action type, boundaries between blocks are not relevant for relative prioritization, as the transactions within a block are still sorted according to `effective_time` . Order priority applies only to sending data. For prioritization of reading data, see the previous section on gossip priority. Similar to gossip priority auctions, order priority fees are burned. IOC priority fee paid can be read from the `user_fills` file written by the nodes as field `priorityGas` . #### ALO priority&#x20; On the timescale of `T = 400ms`, ALO orders are sorted by priority. More precisely, the tail of the queue at each level consisting of orders placed within the past `T` will be sorted in decreasing order of priority rate.&#x20; As a consequence, any slot in the queue is eligible for priority fee bidding for a window of duration `T`. Each new order compares against the tail of orders less than `T` old at placement time. In other words, the `T` window is continuous, not bucketed. ALO priority fees are deducted at time of placing the order regardless of whether the order fills.&#x20; Unlike for IOC orders, ALO priority fees do not effect mempool prioritization. ALO orders are processed FIFO as transactions always, with similar end-to-end latency as cancels. The priority fee implementation affects place in queue across transactions. In other words, ALO orders are prioritized similarly in the mempool regardless of their priority, but queue position can change on a 400ms time scale after orders transactions are executed on the L1. A concrete example: a new level `L` opens and is empty at time `t`. The first order `A` at level `L` is applied onchain (as above, this means executed on the L1) at time `t' > t` with zero priority fee. The next order `B` is applied onchain at time `t' + T - 1ms` with priority `p > 0`. Assuming `A` and `B` are the only orders at level `L`, the ordering at time `t' + T` will have `B` in front of `A`. A third order `C` is applied at time `t' + T + 1ms` with priority `p' > p`. The ordering at time `t' + T + 1ms` is `B > A > C` . Even though `C` has higher priority, `B` has already locked in its place in queue because `A` has been on the book for `T`, and `B` sits before `A`. &#x20; Gossip priority fees can be read from the `replica_cmds` files recorded by nodes. The USDC value of the priority fee amounts can be computed as `order_price * order_sz * grouping_priority_rate` . The [order\_book\_server](https://github.com/hyperliquid-dex/order_book_server) maintains the correct level ordering by using the `insertBefore` field on `RawBookDiff::New` from the `raw_book_diff` files. # USDC CCTP is the preferred method for minting USDC natively on the Hyperliquid L1. See <https://github.com/circlefin/hyperevm-circle-contracts> for Circle's published contracts and flows. ### Legacy Bridge CCTP supports more chains and functionality. The legacy bridge is deprecated. Contract: <https://arbiscan.io/address/0x2df1c51e09aecf9cacb7bc98cb1742757f163df7> Source: <https://github.com/hyperliquid-dex/contracts/blob/master/Bridge2.sol> #### Deposit The deposit flow for the bridge is simple. The user sends native USDC to the bridge, and it is credited to the account that sent it in less than 1 minute. The minimum deposit amount is 5 USDC. If you send an amount less than this, it will not be credited and be lost forever.&#x20; #### Withdraw The withdrawal flow requires a user wallet signature on Hyperliquid only, and no Arbitrum transaction. The withdrawal from Arbitrum is handled entirely by validators, and the funds arrive in the user wallet in 3-4 minutes. This payload for signTypedData is ```rust #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] #[serde(deny_unknown_fields)] pub(crate) struct WithdrawAction3 { pub(crate) signature_chain_id: U256, pub(crate) hyperliquid_chain: Chain, pub(crate) destination: String, pub(crate) amount: String, pub(crate) time: u64, } impl Eip712 for WithdrawAction3 { type Error = Eip712Error; fn domain(&self) -> StdResult<EIP712Domain, Self::Error> { Ok(eip_712_domain(self.signature_chain_id)) } fn type_hash() -> StdResult<[u8; 32], Self::Error> { Ok(eip712::make_type_hash( format!("{HYPERLIQUID_EIP_PREFIX}Withdraw"), &[ ("hyperliquidChain".to_string(), ParamType::String), ("destination".to_string(), ParamType::String), ("amount".to_string(), ParamType::String), ("time".to_string(), ParamType::Uint(64)), ], )) } fn struct_hash(&self) -> StdResult<[u8; 32], Self::Error> { let Self { signature_chain_id: _, hyperliquid_chain, destination, amount, time } = self; let items = vec![ ethers::abi::Token::Uint(Self::type_hash()?.into()), encode_eip712_type(hyperliquid_chain.to_string().into_token()), encode_eip712_type(destination.clone().into_token()), encode_eip712_type(amount.clone().into_token()), encode_eip712_type(time.into_token()), ]; Ok(keccak256(encode(&items))) } } ``` Example signed Hyperliquid action: ```json { "action": { "type": "withdraw3", "signatureChainId": "0xa4b1", "hyperliquidChain": "Mainnet" or "Testnet" "destination": "0x000....0", "amount": "12.3", "time": 1698693262 }, "nonce": 1698693262 // IMPORTANT: this must match "time", "signature": {"r": ..., "s": ..., "v": ... } // signedTypedData output based on Eip712 implementation above. See python sdk for equivalent python code } ``` #### Deposit with permit The bridge supports depositing on behalf of another user via the `batchedDepositWithPermit`function. Example code for how the user can sign the PermitPayload ```typescript const payload: PermitPayload = { owner, // The address of the user with funds they want to deposit spender, // The address of the bridge 0x2df1c51e09aecf9cacb7bc98cb1742757f163df7 on mainnet and 0x08cfc1B6b2dCF36A1480b99353A354AA8AC56f89 on testnet value, nonce, deadline, }; const isMainnet = true; const domain = { name: isMainnet ? "USD Coin" : "USDC2", version: isMainnet ? "2" : "1", chainId: isMainnet ? 42161 : 421614, verifyingContract: isMainnet ? "0xaf88d065e77c8cC2239327C5EDb3A432268e5831" : "0x1baAbB04529D43a73232B713C0FE471f7c7334d5
프로젝트로 돌아가기