Hyperliquid 백서

Hyperliquid

원문

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

dity is inspired by Uniswap, while interoperating with a native onchain order book to support sophisticated order book liquidity from end users. HIP-2 is a fully decentralized onchain strategy that is part of Hyperliquid's block transition logic. Unlike conventional automated order book strategies, there are no operators. The strategy logic is secured by the same consensus that operates the order book itself. Note that Hyperliquidity is currently only available on spot pairs against USDC.&#x20; Hyperliquidity is parametrized by 1. `spot`: a spot order book asset with USDC quote returned by a deployment of HIP-1 2. `startPx`: the initial price of the range 3. `nOrders`: the number of orders in the range 4. `orderSz`: the size of a full order in the range 5. `nSeededLevels`: the number of levels that begin as bids instead of asks. Note that for each additional bid level added by incrementing `nSeededLevels` the deployer needs to fund Hyperliquidity with `px * sz` worth of USDC. For fixed `nOrders`, increasing seeded levels decreases the total supply because it reduces the genesis supply of Hyperliquidity. Each Hyperliquidity strategy has a price range defined recursively `px_0 = startPx`, `px_i = round(px_{i-1} * 1.003)`. The strategy updates on every block where the block time is at least 3 seconds since the previous update block. After each update: 1. Strategy targets `nFull = floor(balance / orderSz)` full ask orders and a `balance % orderSz` partial ask order if the partial order is nonzero. To the extent that ALO orders are not rejected, these orders are ensured. 2. Each fully filled tranche is modified to an order of size `orderSz` on the side with available balance, with the exception of the single partial order from (1) if it exists. The resulting strategy guarantees a 0.3% spread every 3 seconds. Like smart-contract based pools on general-purpose chains, Hyperliquidity requires no maintenance in the form of user transactions. One key improvement is that Hyperliquidity participates in a general-purpose order book. Active liquidity providers can join in liquidity provision alongside Hyperliquidity at any time, allowing markets to adapt to increasing demand for liquidity. # HIP-3: Builder-deployed perpetuals The Hyperliquid protocol supports permissionless builder-deployed perps (HIP-3), a key milestone toward fully decentralizing the perp listing process.&#x20; The deployer of a perp market is responsible for 1. Market definition, including the oracle definition and contract specifications 2. Market operation, including setting oracle prices, leverage limits, and settling the market if needed HIP-3 inherits the HyperCore stack including its high performance margining and order books. For example, the API to trade HIP-3 perps is unified with other HyperCore actions. To trade HIP-3 assets, the asset ID simply needs to be set using the schema [here](/hyperliquid-docs/for-developers/api/asset-ids). ### Spec 1. The staking requirement for mainnet will be 500k HYPE. This requirement is expected to decrease over time as the infrastructure matures. Any amount staked above the most recent requirement can be unstaked. The staking requirement is maintained for a minimum of 183 days after the dex is deployed. 2. Any deployer that meets the staking requirement can deploy one perp dex. As a reminder, each perp dex features independent margining, order books, and deployer settings. A future upgrade may support multiple dex deployments sharing the same deployer and staking requirement. 3. Any quote asset can be used as the collateral asset for a dex. As a reminder, assets that fail to meet the permissionless quote asset requirements will lose quote asset status based on onchain validator vote. Such a vote would also disable perp dexs that use this asset as collateral. A deployer-initiated disabling of quote asset does not disable the corresponding perp dexs. 4. HIP-3 deployers are not subject to slashing related to quote assets. On a future upgrade, dexs with disabled quote assets would support migration to a new collateral token. This is not expected to happen on mainnet, as quote token deployers have their separate staking and slashing conditions. In summary, the quote asset choice is important for trading fee and product considerations, but is not an existential risk for HIP-3 deployers. 5. The first 3 assets deployed in any perp dex do not require auction participation. Additional assets go through a Dutch auction with the same hyperparameters (including frequency and minimum price) as the HIP-1 auction. The HIP-3 auction for additional perps is shared across all perp dexs. Future upgrades will support improved ergonomics around reserving assets for time-sensitive future deployments. Deployers also get `7 + 0.2 * n_auction_deployments` reserve deployments that can be used at the current auction price, but bypassing the auction timer. 6. HIP-3 markets incorporate the usual sources of trading fee discounts, including staking discounts, referral rewards, and aligned collateral discount. HIP-3 deployers can configure an additional fee share between 0-300% (0-100% for growth mode). If the share is above 100%, the protocol fee is also increased to be equal to the deployer fee. 7. Aligned stablecoin collateral will automatically receive reduced fees once the alignment condition (which is being updated based on user and deployer feedback) is implemented. ### Settlement The deployer may settle an asset using the `haltTrading` action. This cancels all orders and settles positions to the current mark price. The same action can be used to resume trading, effectively recycling the asset. This could be used to list dated contracts without participating in the deployment auction for each new contract. Once all assets are settled, a deployer's required stake is free to be unstaked. ### Oracle While the oracle is completely general at the protocol level, perps make the most mathematical sense when there is a well-defined underlying asset or data feed which is difficult to manipulate and has underlying economic significance. Most price indices are not amenable as perp oracle sources. Deployers should consider edge cases carefully before listing markets, as they are subject to slashing for all listed markets on their DEX. ### Slashing&#x20; Note: in all usages below, "slashing" is only in the context of HIP-3.&#x20; To ensure high quality markets and protect users, deployers must maintain 500k staked HYPE. In the event of malicious market operation, validators have the authority to slash the deployer’s stake by conducting a stake-weighted vote. Even if the deployer has unstaked and initiated a staking withdrawal, the stake is still slashable during the 7-day unstaking queue.&#x20; While slashing is ultimately by validator quorum, the protocol guidelines have been distilled from careful testnet analysis, user feedback, and deployer feedback. The guiding principle is that slashing is to prevent behavior that jeopardizes protocol correctness, uptime, or performance. A useful rule of thumb is that any slashable behavior should be accompanied by a bug fix in the protocol implementation. Therefore, HIP-3 should not require slashing in its final state. However, slashing is an important safety mechanism for a practical rollout of this large feature set.&#x20; Slashing is technical and does not distinguish between malicious and incompetent behavior. Relatedly, slashing does not distinguish between 1. A deployer that deviates from a well-designed contract spec 2. A deployer that faithfully follows a poorly designed contract spec 3. A deployer whose private keys are compromised The key factor is the effect of the deployer's actions on the protocol. Note that any bugs discovered are generously covered by the bug bounty program, provided such discoveries meet the terms of that program, including being responsibly disclosed without being exploited. These reports are greatly appreciated.&#x20; Even attempted malicious deployer inputs that do not cause protocol issues are slashable. Similarly, inputs that do cause protocol issues but that are not irregular are not slashable. In particular, bugs under normal operation that are unrelated to the deployer inputs are not within scope of slashing. The interpretation of "irregular" inputs is to be determined by validator vote, and includes inputs that exploit edge cases or loopholes that circumvent system limits. All deployer transactions are onchain, and can be independently analyzed by any interested parties.&#x20; Some malicious behavior is valid by protocol definition, but incorrect by certain subjective interpretations. The slashing principle provides that the protocol should not intervene in subjective matters. The motivation is that while proof-of-stake blockchains could hard fork on undesirable state transitions, they very rarely do. Neutrality of the platform is an incredibly important feature to preserve. Relatedly, the slashed stake by the deployer is burned instead of being distributed to affected users. This is again based on proof-of-stake principles and prevents some forms of misaligned incentives between users and deployers. While the protocol layer does not enforce subjective irregularities, the downstream application and social layers can. Ultimately, the deployer's reputation and future success are always at stake.&#x20; The amount slashed in a given instance is ultimately a stake-weighted median of validator votes. However, as a general guideline, irregular inputs that cause invalid state transitions or prolonged network downtime can be slashed up to 100%. Irregular inputs causing brief network downtime can be partially slashed up to 50%. Invalid inputs that cause network degradation or performance issues can be partially slashed up to 20%.&#x20; Lastly, the slashing conditions are independent of the staker composition. Therefore, LST operators should carefully diligence deployers. LST operators should also carefully and clearly communicate slashing risks to their users. A self-bonding requirement for deployers could make sense.&#x20; In the most likely outcome, slashing never happens on mainnet. A large amount of technical work has gone into making HIP-3 a self-contained and technically robust system. Barring implementation issues, HIP-3 inherits Hyperliquid's carefully designed mathematical solvency guarantees. ### Cross margin IMPORTANT: Enabling cross margin on an asset is irreversible. Deployers should carefully consider the conditions below before enabling. Despite the system-level protection, users still take greater risk when using cross margin across DEXs with different deployers. To better protect users, mainnet validators will enforce that HIP-3 deployers only enable cross margin on assets that satisfy defined eligibility standards, including: sufficient observable liquidity, a reliable external oracle source, and resilience to price manipulation. In particular, each time the \`externalPerpPx\` of an asset moves more than 50% relative to the start of day price, validators will conduct a review to determine whether the deployer should be slashed due to manipulation. Assets where 50% daily moves are expected more than once a month are ineligible for cross margin and are subject to deployer slashing. ### Backstop liquidator Each HIP-3 DEX is associated with a fully onchain strategy at `0x400..00 + {dex_index}` that takes over backstop liquidatable positions from the designated HIP-3 DEX. The onchain backstop liquidators only accept assets where cross margin is enabled, making those assets significantly less likely to experience ADL going forward during high volatility events. Each DEX’s onchain backstop liquidator is an independent user and falls back to ADL to mathematically guarantee solvency of the DEX. There is no action item for users. Once scaled out, the backstop liquidators will absorb undercollateralized positions while simultaneously avoiding bad debt and reducing the need for ADL. # HIP-4: Outcome markets ### Overview Outcomes are fully collateralized contracts that settle within a fixed range. HIP-4 is a general-purpose primitive that is useful for applications such as prediction markets and bounded options-like instruments.&#x20; Outcomes bring non-linearity, dated contracts, and an alternative form of derivative trading that does not involve leverage or liquidations. The outcome primitive expands the expressivity of HyperCore, while composing with other primitives such as portfolio margin and the HyperEVM. The first market is a recurring binary outcome that settles daily at 06:00 UTC to the BTC mark price on HyperCore mark prices. See the spec [here](/hyperliquid-docs/trading/contract-specifications#recurring-outcomes). Multi-outcome markets will be supported but are not part of the initial mainnet release. Additional features and markets will be rolled out in stages. The outcome trading API is similar to spot, with key differences highlighted here: <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/asset-ids>. ### Mechanics Each outcome market consists of two sides, each with a token. The tokens are labeled by `sideSpecs` in the `outcomeMeta` info endpoint, often `Yes` and `No`. Settlement automatically converts either Yes to `settleFraction` quote tokens and No to `1 - settleFraction` quote tokens. In particular, `settleFraction = 1` for "binary yes" and `settleFraction = 0` for "binary no" settlement. The order books of Yes and No tokens for the same outcome are merged to share liquidity. For example, an order to buy Yes at price `p` is equivalent to an order to sell No at price `1-p`. Under the merged book, price-time priority generalizes to price-side-time priority. In other words, *for orders at the same merged price level*, the resting sell orders are sorted before all resting buy dual orders. Advanced users may also manually split and merge outcomes to convert between primary and dual balances. See [here](/hyperliquid-docs/for-developers/api/exchange-endpoint#split-outcome) for API examples. Most operations abstract the dual book's liquidity from the user's perspective. However, there are a few examples whose ergonomics will be improved on a future network upgrade. For example, historical orders can return the primary and dual orders separately if a user sends an order that both matches and rests on the book. *Questions* are collections of outcomes where exactly one outcome will settle to Yes, and all others will settle to No. Each outcome trades on a separate order book, but is linked by `negate` and `merge` operations. See [here](/hyperliquid-docs/for-developers/api/exchange-endpoint#negate-outcome) for API examples. In other words, users with No shares on different outcomes of the same question can redeem quote tokens before the underlying outcomes settle. Fees are currently zero for outcome markets for initial testing. However, builder codes do work the same as normal spot trading, where builders earn builder fees on sell orders that specify their builder code.&#x20; # Frontend checks There are many ways to reach invalid configurations during the spot deploy process. To avoid this, deployers can try intended deployments on testnet first. For automated deployment integrations, the following is a list of client-side checks that may be helpful. ### Token Deployment ```typescript if (szDecimals === undefined || weiDecimals === undefined) { displayAlert( "Size decimals and Wei decimals must be specified.", "error" ); return; } if (szDecimals > 2 || szDecimals < 0) { displayAlert("Size decimals must be between 0 and 2.", "error"); return; } if (weiDecimals > 8 || weiDecimals < 0) { displayAlert("Wei decimals must be between 0 and 8.", "error"); return; } if (szDecimals + 5 > weiDecimals) { displayAlert("weiDecimals must be at least szDecimals + 5.", "error"); return; } ``` ### Set Deployer Trading Fee Share ```typescript if (deployerTradingFeeShare === undefined) { displayAlert("Deployer trading fee share must be specified.", "error"); return; } if (deployerTradingFeeShare < 0 || deployerTradingFeeShare > 100) { displayAlert( "Deployer trading fee share must be between 0 and 100.", "error" ); return; } ``` ### User and Anchor Token Genesis ```typescript if (blacklistUser !== "") { if (amount !== "" || user !== "" || existingToken !== undefined) { displayAlert("Can only specify blacklist user by itself.", "error"); return; } } else { if (amount.toString().length > 19) { displayAlert(`Can only enter up to 19 digits for Amount.`, "error"); return; } const hypotheticalTotalSupply = BigInt(activeTokenDeployState?.totalGenesisBalanceWei ?? 0) + BigInt(amount); if (hypotheticalTotalSupply > MAX_UINT_64 / BigInt(2)) { displayAlert( "Total supply would be too large with this addition", "error" ); return; } const minStartPrice = getMinStartPrice(szDecimals); if ( minStartPrice * Number(formatUnits(hypotheticalTotalSupply, weiDecimals)) > MAX_MARKET_CAP_MILLIONS_START * 1e6 ) { displayAlert( "Total supply would be too large even at smallest possible Hyperliquidity initial price", "error" ); return; } if ( (!isAddress(user) && existingToken === undefined) || (isAddress(user) && existingToken !== undefined) ) { displayAlert( "Exactly one of user or existing token must be specified.", "error" ); return; } if (user.toLowerCase() === HYPERLIQUIDITY_USER) { displayAlert( "Cannot assign genesis balance to hyperliquidity user", "error" ); return; } } if (!activeTokenDeployState || activeTokenDeployState.token === undefined) { displayAlert( "Need to handle fetching previously created token.", "error" ); return; } const minWei = getWei(100000, activeTokenDeployState.spec.weiDecimals); if ( existingToken !== undefined && !isAddress(user) && BigInt(amount) < BigInt(minWei) ) { displayAlert( `Using an existing token as anchor token for genesis requires a minimum amount of 100,000 ${activeTokenDeployState.spec.name} (wei=${minWei}).`, "error" ); return; } ``` ### Hyperliquidity <pre class="language-typescript"><code class="lang-typescript"> const PX_GAP = 0.003; const MAX_N_ORDERS = 4000; const MAX_MARKET_CAP_BILLIONS_END = 100; const MIN_MARKET_CAP_BILLIONS_END = 1; <strong> const MAX_MARKET_CAP_MILLIONS_START = 10; </strong><strong> const MAX_UINT_64 = BigInt("18446744073709551615"); </strong> if ( startPx === undefined || orderSz === undefined || orderCount === undefined || nSeededLevels === undefined ) { displayAlert( "Lowest price, order size, number of orders and number of seeded levels must be specified.", "error" ); return; } const minStartPx = getMinStartPx(szDecimals); if (startPx &#x3C; minStartPx) { displayAlert( `First order price must be at least ${roundPx( minStartPx, szDecimals, true )}`, "error" ); return; } if (startPx * orderSz &#x3C; 1) { displayAlert("First order size must be at least 1 USDC", "error"); return; } if (!activeTokenDeployState || activeTokenDeployState.spots.length === 0) { displayAlert( "Unexpected error: spot and token should already be registered.", "error" ); return; } const pxRange = Math.ceil(Math.pow(1 + PX_GAP, orderCount)); const endPx = startPx * pxRange; // 1e9 instead of 1e8 because backend checks against u64::MAX / 10 if ( pxRange > 1_000_000 || hyperliquidityTotalWei > MAX_UINT_64 || endPx * orderSz * 1e9 > MAX_UINT_64 ) { displayAlert( "Total Hyperliquidity token allocation is too large.", "error" ); return; } const minTotalGenesisBalanceSz = 100_000_000; if (totalSupply * Math.pow(10, szDecimals) &#x3C; minTotalGenesisBalanceSz) { displayAlert( `Total genesis balance must be at least ${minTotalGenesisBalanceSz} lots (minimal tradeable units, i.e. one lot is 0.01 if szDecimals is 2)`, "error" ); r
프로젝트로 돌아가기