Hyperliquid 백서

Hyperliquid

원문

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

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 1 | Limit order | (asset, isBuy, limitPx, sz, reduceOnly, encodedTif, cloid) | (uint32, bool, uint64, uint64, bool, uint8, uint128) | Tif encoding: `1` for `Alo` , `2` for `Gtc` , `3` for `Ioc` . Cloid encoding: 0 means no cloid, otherwise uses the number as the cloid. limitPx and sz should be sent as 10^8 \* the human readable value | | 2 | Vault transfer | (vault, isDeposit, usd) | (address, bool, uint64) | | | 3 | Token delegate | (validator, wei, isUndelegate) | (address, uint64, bool) | | | 4 | Staking deposit | wei | uint64 | | | 5 | Staking withdraw | wei | uint64 | | | 6 | Spot send | (destination, token, wei) | (address, uint64, uint64) | | | 7 | USD class transfer | (ntl, toPerp) | (uint64, bool) | | | 8 | Finalize EVM Contract | (token, encodedFinalizeEvmContractVariant, createNonce) | (uint64, uint8, uint64) | encodedFinalizeEvmContractVariant `1` for `Create`, `2` for `FirstStorageSlot` , `3` for `CustomStorageSlot` . If `Create` variant, then `createNonce` input argument is used. | | 9 | Add API wallet | (API wallet address, API wallet name) | (address, string) | If the API wallet name is empty then this becomes the main API wallet / agent | | 10 | Cancel order by oid | (asset, oid) | (uint32, uint64) | | | 11 | Cancel order by cloid | (asset, cloid) | (uint32, uint128) | | | 12 | Approve builder fee | (maxFeeRate, builder address) | (uint64, address) | maxFeeRate is in decibps. To approve a builder fee of 0.01% maxFreeRate should be 10. | | 13 | Send asset | (destination, subAccount, source\_dex, destination\_dex, token, wei) | (address, address, uint32, uint32, uint64, uint64) | If subAccount is not the zero address, then transfer from subAccount. Specify uint32::MAX for the source\_dex or destination\_dex for spot. | | 15 | Borrow lend operation | (encodedOperation, token, wei) | (uint8, uint64, uint64) | encodedOperation `0` for `Supply`, `1` for `Withdraw` . If `wei` is 0 then maximally apply the operation, e.g. withdraw full balance from reserve. | | 16 | Set abstraction | (user, abstraction) | (address, uint8) | abstraction `1` for `disabled`, `2` for `unifiedAccount` , `3` for `portfolioMargin` . `user` can either be the master user or a sub-account. | | 17 | Outcome operation | (encodedOperation, question, outcome, wei) | (uint8, uint32, uint32, uint64) | <p></p><p>encodedOperation <code>0</code> for <code>SplitOutcome</code>, <code>1</code> for <code>MergeOutcome</code>, <code>2</code> for <code>MergeQuestion</code>, <code>3</code> for <code>NegateOutcome</code>. Unused fields must be set to 0: <code>SplitOutcome</code> and <code>MergeOutcome</code> ignore question; <code>MergeQuestion</code> ignores outcome. negate uses both. Payloads with non-zero unused fields are dropped. <code>wei</code> must be a multiple of size. For the merge operations 0 means merge the maximal amount.</p> | Below is an example contract that would send an action on behalf of its own contract address on HyperCore, which also demonstrates one way to construct the encoded action in Solidity. ``` contract CoreWriterCaller { function sendUsdClassTransfer(uint64 ntl, bool toPerp) external { bytes memory encodedAction = abi.encode(ntl, toPerp); bytes memory data = new bytes(4 + encodedAction.length); data[0] = 0x01; data[1] = 0x00; data[2] = 0x00; data[3] = 0x07; for (uint256 i = 0; i < encodedAction.length; i++) { data[4 + i] = encodedAction[i]; } CoreWriter(0x3333333333333333333333333333333333333333).sendRawAction(data); } } ``` \ Happy building. Any feedback is appreciated. {% file src="/files/4dRObNCsfvnrcSVeJXgc" %} {% file src="/files/Nsv6L7FugL44GNDvyDq2" %} # HyperCore <> HyperEVM transfers ## Introduction Spot assets can be sent between HyperCore and the HyperEVM. In the context of these transfers, spot assets on HyperCore are called `Core spot` while ones on the EVM are called `EVM spot`. The spot deployer can link their Core spot asset to any ERC20 contract deployed to the EVM. The Core spot asset and ERC20 token can be deployed in either order. As the native token on HyperCore, HYPE also links to the native HyperEVM balance rather than an ERC20 contract. ## System Addresses Every token has a system address on the Core, which is the address with first byte `0x20` and the remaining bytes all zeros, except for the token index encoded in big-endian format. For example, for token index 200, the system address would be `0x20000000000000000000000000000000000000c8` . The exception is HYPE, which has a system address of `0x2222222222222222222222222222222222222222` . ## Transferring HYPE HYPE is a special case as the native gas token on the HyperEVM. HYPE is received on the EVM side of a transfer as the native gas token instead of an ERC20 token. To transfer back to HyperCore, HYPE can be sent as a transaction value. The EVM transfer address `0x222..2` is a system contract that emits `event Received(address indexed user, uint256 amount)` as its payable `receive()` function. Here `user` is `msg.sender`, so this implementation enables both smart contracts and EOAs to transfer HYPE back to HyperCore. Note that there is a small gas cost to emitting this log on the EVM side. ## Transferring between Core and EVM Only once a token is linked, it can be converted between HyperCore and HyperEVM spot using a sendAsset action (or via the frontend) and on the EVM by using an ERC20 transfer. Transferring tokens from HyperCore to HyperEVM can be done using a sendAsset action (or via the frontend) with the corresponding system address as the destination. The tokens are credited by a system transaction that calls `transfer(recipient, amount)` on the linked contract as the system address, where recipient is the sender of the sendAsset action.&#x20; Transferring tokens from HyperEVM to HyperCore can be done using an ERC20 transfer with the corresponding system address as the destination. The tokens are credited to the Core based on the emitted `Transfer(address from, address to, uint256 value)` from the linked contract. Do not blindly assume accurate fungibility between Core and EVM spot. See [#caveats](#caveats "mention") for more details. ## Gas costs A transfer from HyperEVM to HyperCore costs similar gas to the equivalent transfer of the ERC20 token or HYPE to any other address on the HyperEVM that has an existing balance. A transfer from HyperCore to HyperEVM costs 200k gas at the base gas price of the next HyperEVM block. ## Linking Core and EVM Spot Assets In order for transfers between Core spot and EVM spot to work the token's system address must have the total non-system balance on the other side. For example, to deploy an ERC20 contract for an existing Core spot asset, the system contract should have the entirety of the EVM spot supply equal to the max Core spot supply.\ \ Once this is done the spot deployer needs to send a spot deploy action to link the token to the EVM: ```javascript /** * @param token - The token index to link * @param address - The address of the ERC20 contract on the evm. * @param evmExtraWeiDecimals - The difference in Wei decimals between Core and EVM spot. E.g. Core PURR has 5 weiDecimals but EVM PURR has 18, so this would be 13. evmExtraWeiDecimals should be in the range [-2, 18] inclusive */ interface RequestEvmContract { type: “requestEvmContract”; token: number; Address: address; evmExtraWeiDecimals: number; } ``` After sending this action, HyperCore will store the pending EVM address to be linked. The deployer of the EVM contract must then verify their intention to link to the HyperCore token in one of two ways: 1. If the EVM contract was deployed from an EOA, the EVM user can send an action using the nonce that was used to deploy the EVM contract. 2. If the EVM contract was deployed by another contract (e.g. create2 via a multisig), the contract's first storage slot or slot at keccak256("HyperCore deployer") must store the address of a finalizer user. To finalize the link, the finalizer user sends the following action (note that this not nested in a spot deploy action). In the "create" case, the EVM deployer sends the action. In the "firstStorageSlot" or "customStorageSlot" case, the finalizer must match the value in the corresponding slot. ```javascript /** * @param input - One of the EVM deployer options above */ interface FinalizeEvmContract { type: “finalizeEvmContract”; token: number; input: {"create": {"nonce": number}} | "firstStorageSlot" | "customStorageSlot"}; } ``` ## Caveats There are currently no checks that the system address has sufficient supply or that the contract is a valid ERC20, so be careful when sending funds. In particular, the linked contract may have arbitrary bytecode, so it's prudent to verify that its implementation is correct. There are no guarantees about what the `transfer` call does on the EVM, so make sure to verify the source code and total balance of the linked EVM contract.&#x20; If the EVM contract has extra Wei decimals, then if the relevant log emitted has a value that is not round (does not end in `extraEvmWeiDecimals` zeros), the non-round amount is burned (guaranteed to be <1 Wei). This is true for both HYPE and any other spot tokens. ## Mainnet PURR Mainnet PURR is deployed as an ERC20 contract at `0x9b498C3c8A0b8CD8BA1D9851d40D186F1872b44E` with the following code. It will be linked to PURR on HyperCore once linking is enabled on mainnet. ```solidity // SPDX-License-Identifier: MIT pragma solidity 0.8.28; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol"; contract Purr is ERC20Permit { constructor() ERC20("Purr", "PURR") ERC20Permit("Purr") { address initialHolder = 0x2000000000000000000000000000000000000001; uint256 initialBalance = 600000000; _mint(initialHolder, initialBalance * 10 ** decimals()); } } ``` ## Final Notes Attached is a sample script for deploying an ERC20 token to the EVM and linking it to a Core spot token. {% file src="/files/ByYbxCDq0BaOoY6akDhN" %} # Interaction timings ## Transfer Timing Transfers from HyperCore to HyperEVM are queued on the L1 until the next HyperEVM block. Transfers from HyperEVM to HyperCore happen in the same L1 block as the HyperEVM block, immediately after the HyperEVM block is built. ## Timing within a HyperEVM block On an L1 block that produces a HyperEVM block: 1. L1 block is built 2. EVM block is built 3. EVM -> Core transfers are processed&#x20; 4. CoreWriter actions are processed&#x20; Note that the account performing the CoreWriter action must exist on HyperCore before the EVM block is built. An EVM -> Core transfer to initialize the account in the same block will still result in the CoreWriter action being rejected. --- [Next Page](https://hyperliquid.gitbook.io/hyperliquid-docs/llms-full.txt/1) # Wrapped HYPE A canonical system contract for wrapped HYPE is deployed at `0x555...5`. The contract is immutable, with the same source code as wrapped ETH on Ethereum, apart from the token name and symbol.&#x20; The source code for WHYPE is provided below. Note that this is based on the WETH contract on Ethereum mainnet and other EVM chains. ```solidity pragma solidity >=0.4.22 <0.6; contract WHYPE9 { string public name = "Wrapped HYPE"; string public symbol = "WHYPE"; uint8 public decimals = 18; event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); event Deposit(address indexed dst, uint wad); event Withdrawal(address indexed src, uint wad); mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; function() external payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value); } function withdraw(uint wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; msg.sender.transfer(wad); emit Withdrawal(msg.sender, wad); } function totalSupply() public view returns (uint) { return address(this).balance; } function approve(address guy, uint wad) public returns (bool) { allowance[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; emit Transfer(src, dst, wad); return true; } } ``` # JSON-RPC The following RPC endpoints are available * `net_version` * `web3_clientVersion` * `eth_blockNumber` * `eth_call` * only the latest block is supported * `eth_chainId` * `eth_estimateGas` * only the latest block is supported * `eth_feeHistory` * `eth_gasPrice` * returns the base fee for the next small block * `eth_getBalance` * only the latest block is supported * `eth_getBlockByHash` * `eth_getBlockByNumber` * `eth_getBlockReceipts` * `eth_getBlockTransactionCountByHash` * `eth_getBlockTransactionCountByNumber` * `eth_getCode` * only the latest block is supported * `eth_getLogs` * up to 4 topics * up to 50 blocks in query range * `eth_getStorageAt` * only the latest block is supported * `eth_getTransactionByBlockHashAndIndex` * `eth_getTransactionByBlockNumberAndIndex` * `eth_getTransactionByHash` * `eth_getTransactionCount` * only the latest block is supported * `eth_getTransactionReceipt` * `eth_maxPriorityFeePerGas` * always returns zero currently * `eth_syncing` * always returns false The following custom endpoints are available * `eth_bigBlockGasPrice` * returns the base fee for the next big block * `eth_usingBigBlocks` * returns whether the address is using big blocks * `eth_getSystemTxsByBlockHash` and `eth_getSystemTxsByBlockNumber` * similar to the "getTransaction" analogs but returns the system transactions that originate from HyperCore Unsupported requests * Requests that require historical state are not supported at this time on the default RPC implementation. However, independent archive node implementations are available for use, and the GitHub repository has examples on how to get started indexing historical data locally. Note that read precompiles are only recorded for the calls actually made on each block. Hypothetical read precompile results could be obtained from a full L1 replay. Rate limits: IP based rate limits are the same as the API server.&#x20; # Nodes Documentation for running nodes You can run a node by following the non-validator and validator nodes by following the steps in <https://github.com/hyperliquid-dex/node>. # L1 data schemas The node writes data to `~/hl/data`. With default settings, the network will generate around 100 GB of logs per day, so it is recommended to archive or delete old files. The command line flags to generate the auxiliary data below can be found at <https://github.com/hyperliquid-dex/node>&#x20; #### Transaction blocks Blocks parsed as transactions are streamed to ``` ~/hl/data/replica_cmds/{start_time}/{date}/{height} ``` **State snapshots** State snapshots are saved every 10,000 blocks to ``` ~/hl/data/periodic_abci_states/{date}/{height}.rmp ``` #### Trades Trades data is saved to&#x20; ``` ~/hl/data/node_trades/hourly/{date}/{hour} ``` ```json // Example trade { "coin": "COMP", "side": "B", "time": "2024-07-26T08:26:25.899", "px": "51.367", "sz": "0.31", "hash": "0xad8e0566e813bdf98176040e6d51bd011100efa789e89430cdf17964235f55d8", "trade_dir_override":"Na", // side_info always has length 2 // side_info[0] is the buyer // side_info[1] is the seller "side_info": [ { "user": "0xc64cc00b46101bd40aa1c3121195e85c0b0918d8", "start_pos": "996.67", "oid": 12212201265, "twap_id": null, "cloid": null }, { "user": "0x768484f7e2ebb675c57838366c02ae99ba2a9b08", "start_pos": "-996.7", "oid": 12212198275, "twap_id": null, "cloid": null } ] } ``` #### Order statuses Order status data is saved to ``` ~/hl/data/node_order_statuses/hourly/{date}/{hour} ``` ```json // Example order status { "time": "2024-07-26T08:31:48.717", "user": "0xc64cc00b46101bd40aa1c3121195e85c0b0918d8", "status": "canceled", "order": { "coin": "INJ", "side": "A", "limitPx": "25.381", // filled size "sz": "257.0", "oid": 12212359592, "timestamp": 1721982700270, "triggerCondition": "N/A", "isTrigger": false, "triggerPx": "0.0", "children": [], "isPositionTpsl": false, "reduceOnly": false, "orderType": "Limit", // original order size "origSz": "257.0", "tif": "Alo", "cloid": null } } ``` #### Raw book diffs Raw book diffs data is saved to ``` ~/hl/data/node_raw_book_diffs/hourly/{date}/{hour} ``` ```json // Example raw book diffs // new resting order { "user":"0x768484f7e2ebb675c57838366c02ae99ba2a9b08", "oid":35061046831, "coin":"CHILLGUY", "side": "Bid", "px": "1.36", "raw_book_diff": { "new":{"sz":"186910.0"} } } // resting order update { "user":"0x768484f7e2ebb675c57838366c02ae99ba2a9b08", "oid":35061055064, "coin":"BTC", "side": "Bid", "px": "115323.2", "raw_book_diff": { "update":{"origSz":"0.2086","newSz":"0.2076"} } } // order removal { "user":"0xc64cc00b46101bd40aa1c3121195e85c0b0918d8", "oid":35061057543, "side": "Ask", "px": "115200.2" "coin":"HYPE", "raw_book_diff":"remove" } ``` #### Miscellaneous events Miscellaneous event data is saved to ``` ~/hl/data/misc_events/hourly/{date}/{hour} ``` Miscellaneous events currently include the following * Staking deposits * Staking delegations * Staking withdrawals * Validator rewards * Ledger updates (funding distributions, spot transfers, etc) <pre class="language-typescript"><code class="lang-typescript"><strong>type MiscEvent = { </strong><strong> time: string; </strong><strong> hash: string; </strong><strong> inner: MiscEventInner; </strong><strong>} </strong><strong> </strong><strong>type MiscEventInner = CDeposit | Delegation | CWithdrawal | ValidatorRewards | Funding | LedgerUpdate; </strong> type CDeposit = { user: string; amount: number; } type Delegation = { user: string; validator: string; amount: number; is_undelegate: boolean; } type CWithdrawal = { user: string; amount: number; is_finalized: boolean; } type ValidatorRewards = { validator_to_reward: Array&#x3C;[string, number]>; } type Funding { coin: string; usdc: number; szi: number; fundingRate: number; nSamples: number; } type LedgerUpdate = { users: Array&#x3C;string>; delta: LedgerDelta; } // InternalTransfer means Perp USDC transfer // RewardsClaim is for builder and referrer fees // Deposit/Withdraw refer to Arbitrum USDC bridge type LedgerDelta = Withdraw | Deposit | VaultCreate | VaultDeposit | VaultWithdraw | VaultDistribution | VaultLeaderCommission | Liquidation | InternalTransfer | SubAccountTransfer | SpotTransfer | SpotGenesis | RewardsClaim | AccountActivationGas | PerpDexClassTransfer | DeployGasAuction; type Withdraw = { usdc: number; nonce: number; fee: number; } type Deposit = { usdc: number; } type VaultCreate { vault: string; usdc: number; fee: number; } type VaultWithdraw { vault: string; user: string; requestedUsd: number; commission: number; closingCost: number; basis: number; } type VaultDistribution { vault: string; usdc: number; } type Liquidation { liquidatedNtlPos: number;
프로젝트로 돌아가기