### Test Contracts: Simulate Hyperliquid Core with Foundry Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/docs/pages/intro/getting-started.mdx Example Solidity test contract for simulating Hyperliquid core actions using CoreSimulatorLib for testing contract interactions. ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Test} from "forge-std/Test.sol"; import {CoreSimulatorLib} from "@hyper-evm-lib/test/simulation/CoreSimulatorLib.sol"; contract ExampleTest is Test { function setUp() public { vm.createSelectFork("https://rpc.hyperliquid.xyz/evm"); // initialize the HyperCore simulator CoreSimulatorLib.init(); } function test() public { // Make any smart contract calls, // all CoreWriter and token bridging actions will be queued ... // move to the next block, performing all queued CoreWriter and bridging actions CoreSimulatorLib.nextBlock(); // Now, all precompiles calls will be //updated to account for the above executed actions } } ``` -------------------------------- ### Develop Contracts: Bridge and Send Tokens with Hyperliquid Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/docs/pages/intro/getting-started.mdx Example Solidity contract demonstrating how to bridge tokens to Hyperliquid core and send them to another address using CoreWriterLib and PrecompileLib. ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import {CoreWriterLib, HLConstants, HLConversions} from "@hyper-evm-lib/src/CoreWriterLib.sol"; import { PrecompileLib } from "@hyper-evm-lib/src/PrecompileLib.sol"; // Example use-cases of CoreWriterLib and PrecompileLib contract Example { /// @notice Demonstrates usage of PrecompileLib to read spot balance function getSpotBalance(address tokenAddress) external view returns (uint256) { // Get spot balance using tokenAddress // (the address is converted under the hood to tokenId using TokenRegistry) PrecompileLib.SpotBalance memory spotBalance = PrecompileLib.spotBalance(address(this), tokenAddress); return spotBalance.total; } /// @notice Bridges tokens to core and then sends them to another address function bridgeToCoreAndSend(address tokenAddress, uint256 evmAmount, address recipient) external payable { // Get token ID from address, using TokenRegistry uint64 tokenId = PrecompileLib.getTokenIndex(tokenAddress); // use CoreWriterLib to bridge tokens CoreWriterLib.bridgeToCore(tokenAddress, evmAmount); // Convert EVM amount to wei amount (used in HyperCore) uint64 coreAmount = HLConversions.evmToWei(tokenId, evmAmount); // use CoreWriterLib to call the spotSend CoreWriter action CoreWriterLib.spotSend(recipient, tokenId, coreAmount); } } ``` -------------------------------- ### Hyperliquid Testing Framework Setup and Usage Template Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/docs/pages/testing/quick-start.mdx This Solidity code snippet demonstrates the basic setup and usage of the Hyperliquid testing framework. It shows how to import `CoreSimulatorLib`, initialize it in `setUp()`, and simulate block progression with `nextBlock()` to execute queued actions. This is essential for testing smart contracts interacting with Hyperliquid. ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Test} from "forge-std/Test.sol"; import {CoreSimulatorLib} from "@hyper-evm-lib/test/simulation/CoreSimulatorLib.sol"; contract TemplateTest is Test { function setUp() public { vm.createSelectFork("https://rpc.hyperliquid.xyz/evm"); // initialize the HyperCore simulator CoreSimulatorLib.init(); } function test() public { // Make any smart contract calls, // all CoreWriter and token bridging actions will be queued ... // move to the next block, // performing all queued CoreWriter and bridging actions CoreSimulatorLib.nextBlock(); // Now, all precompiles calls will be //updated to account for the above executed actions } } ``` -------------------------------- ### Install Foundry with foundryup Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/foundry.mdx Installs the Foundry framework, including forge, cast, and anvil, using the foundryup script. Supports installing the latest stable or nightly release. ```bash # Download foundry installer `foundryup` curl -L https://foundry.paradigm.xyz | bash # Install forge, cast, anvil, chisel foundryup # Install the latest nightly release foundryup -i nightly ``` -------------------------------- ### Install hyper-evm-lib with Foundry Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/docs/pages/index.mdx This snippet shows how to install the hyper-evm-lib library in an existing Foundry project and configure remappings. It is essential for integrating the library into your smart contract development workflow. ```bash forge install hyperliquid-dev/hyper-evm-lib echo "@hyper-evm-lib=lib/hyper-evm-lib" >> remappings.txt ``` -------------------------------- ### Start a Local Anvil Node Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/foundry.mdx Starts Anvil, a local Ethereum development node that complies with the Ethereum JSON-RPC specification. Useful for rapid local testing and development. ```bash # Start a local node ``` -------------------------------- ### Start Anvil Node Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/foundry.mdx Starts a fresh Anvil node. Can be configured to fork from a specific mainnet state or load/dump state for persistence. ```bash anvil ``` ```bash # Fork latest mainnet state anvil --fork-url https://reth-ethereum.ithaca.xyz/rpc ``` ```bash # Load and dump state when initializing and shutting down anvil anvil --state ./path/to/state-file ``` -------------------------------- ### Bridge Tokens to Core Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/docs/pages/example.mdx Demonstrates how to convert EVM amounts to core amounts and bridge them to the HyperCore network. Requires knowledge of PrecompileLib and CoreWriterLib. ```solidity uint256 coreAmount = PrecompileLib.convertEvmToCoreAmount(uBTC, evmAmount); CoreWriterLib.bridgeToCore(uBTC, coreAmount, coreRecipient); ``` -------------------------------- ### Test Contract Bridging with HyperEVM Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/docs/pages/example.mdx A comprehensive example using Foundry's testing framework to simulate bridging operations within a test environment. It sets up an EVM fork, deploys a contract, and tests its bridging functionality. ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Test} from "@hyper-evm-lib/test/BaseSimulatorTest.sol"; import {CoreWriterLib} from "@hyper-evm-lib/src/CoreWriterLib.sol"; import {CoreSimulatorLib} from "@hyper-evm-lib/test/simulation/CoreSimulatorLib.sol"; contract ExampleTest is Test { uint64 constant HYPE = 150; ExampleContract example; function setUp() public { vm.createSelectFork("https://rpc.hyperliquid.xyz/evm"); // initialize the HyperCore simulator CoreSimulatorLib.init(); // deploy your contract in the test environment example = new ExampleContract(); CoreSimulatorLib.forceAccountActivation(address(example)); } function test_bridge() public { // this example contract bridges HYPE to HyperCore example.bridgeToCore{value: 1e18}(HYPE, 1e18); // move to the next block, performing all queued HyperCore interaction(s) CoreSimulatorLib.nextBlock(); } } contract ExampleContract { function bridgeToCore(uint64 tokenId, uint256 evmAmount) external payable { CoreWriterLib.bridgeToCore(tokenId, evmAmount); } } ``` -------------------------------- ### Read Precompiles by EVM Address Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/docs/pages/example.mdx Shows how to retrieve data like spot index and price using EVM addresses via precompiled contracts. Relies on PrecompileLib. ```solidity uint256 spotIdx = TokenRegistry.getSpotIndex(uBTC); uint256 px = PrecompileLib.spotPxByAddress(uBTC); ``` -------------------------------- ### Test Vault Deposit and Withdraw with HyperEVM Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/docs/pages/example.mdx Illustrates testing vault deposit and withdrawal logic within the HyperEVM simulation environment. This example covers asserting balances before and after operations and handling expected reverts due to lock periods. ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {console} from "forge-std/Test.sol"; import {BaseSimulatorTest} from "@hyper-evm-lib/test/BaseSimulatorTest.sol"; import {VaultExample} from "@hyper-evm-lib/src/examples/VaultExample.sol"; import {PrecompileLib} from "@hyper-evm-lib/src/PrecompileLib.sol"; import {CoreWriterLib} from "@hyper-evm-lib/src/CoreWriterLib.sol"; import {CoreSimulatorLib} from "@hyper-evm-lib/test/simulation/CoreSimulatorLib.sol"; contract ExampleVaultTest is BaseSimulatorTest { function test_exampleVaultDepositAndWithdraw() public { VaultExample vaultExampleContract = new VaultExample(); hyperCore.forceAccountActivation(address(vaultExampleContract)); hyperCore.forcePerpBalance(address(vaultExampleContract), 1000e6); address testVault = 0x07Fd993f0fA3A185F7207ADcCD29f7A87404689D; uint64 depositAmount = 100e6; uint64 balanceBefore = PrecompileLib.withdrawable(address(vaultExampleContract)); vaultExampleContract.depositToVault(testVault, depositAmount); CoreSimulatorLib.nextBlock(); // Try to withdraw before the lock period expires - should revert PrecompileLib.UserVaultEquity memory vaultEquity = PrecompileLib.userVaultEquity(address(vaultExampleContract), testVault); vm.expectRevert( abi.encodeWithSelector( CoreWriterLib.CoreWriterLib__StillLockedUntilTimestamp.selector, vaultEquity.lockedUntilTimestamp ) ); vaultExampleContract.withdrawFromVault(testVault, depositAmount); vm.warp(block.timestamp + 1 days + 1); vaultExampleContract.withdrawFromVault(testVault, depositAmount); CoreSimulatorLib.nextBlock(); uint64 balanceAfter = PrecompileLib.withdrawable(address(vaultExampleContract)); assertEq(balanceBefore, balanceAfter); } } ``` -------------------------------- ### Get Spot Market Index and Price using PrecompileLib Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/docs/pages/dev/precompiles.mdx Demonstrates how to use PrecompileLib to retrieve a spot market index from an EVM token address and subsequently get the spot price using either the index or the address directly. This abstracts the complexity of index lookups. ```solidity uint64 uBTC_address = 0x9fdbda0a5e284c32744d2f17ee5c74b284993463; uint64 spotIndex = PrecompileLib.getSpotIndex(uBTC_address); // Equivalent ways of obtaining spot price (via index, or via address) uint64 spotPrice = PrecompileLib.spotPx(spotIndex); // 1000000000000000000 uint64 spotPrice2 = PrecompileLib.spotPx(uBTC_address); ``` -------------------------------- ### Directly Get Token Index using TokenRegistry (Solidity) Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/docs/pages/dev/token-registry.mdx This code snippet demonstrates how to directly interact with the deployed `TokenRegistry` contract on HyperEVM to get the token index for a given EVM token address. It requires instantiating the `ITokenRegistry` interface with the contract's address. ```solidity ITokenRegistry tokenRegistry = ITokenRegistry(0x0b51d1a9098cf8a72c325003f44c194d41d7a85b); // Get the token index for an evm token address uint32 tokenIdx = tokenRegistry.getTokenIndex(tokenAddress); ``` -------------------------------- ### Bridge Tokens to Core and Send in Solidity Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/docs/pages/dev/corewriter.mdx This example demonstrates a function that bridges tokens from EVM to Core using CoreWriterLib.bridgeToCore, converts the amount to HyperCore's 'wei' decimals using HLConversions.evmToWei, and then sends the tokens to a specified recipient using CoreWriterLib.spotSend. ```solidity /// @notice Bridges tokens to core and then sends them to another address function bridgeToCoreAndSend(address tokenAddress, uint256 evmAmount, address recipient) external payable { // use CoreWriterLib to bridge tokens CoreWriterLib.bridgeToCore(tokenAddress, evmAmount); // Convert EVM amount to wei amount (used in HyperCore) uint64 coreAmount = HLConversions.evmToWei(tokenId, evmAmount); // use CoreWriterLib to call the spotSend CoreWriter action CoreWriterLib.spotSend(recipient, tokenId, coreAmount); } ``` -------------------------------- ### Get Token Index via PrecompileLib (Solidity) Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/docs/pages/dev/token-registry.mdx This snippet shows how to use the `PrecompileLib.getTokenIndex` function, which provides a convenient wrapper for reading token indices from the `TokenRegistry` contract. This method abstracts away direct contract interaction. ```solidity uint64 tokenIdx = PrecompileLib.getTokenIndex(tokenAddress); ``` -------------------------------- ### Register Token Information in TokenRegistry (Solidity) Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/docs/pages/dev/token-registry.mdx The `setTokenInfo` function registers a token by taking its index, calling the `getTokenAddress` precompile to get the corresponding EVM contract address, and then storing this mapping in the `addressToIndex` array. It includes error handling for cases where no EVM contract is found for the given token index. ```solidity /** * @notice Register a token by passing in its index * @param tokenIndex The index of the token to register * @dev Calls the token info precompile and stores the mapping */ function setTokenInfo(uint32 tokenIndex) public { // call the precompile address evmContract = getTokenAddress(tokenIndex); if (evmContract == address(0)) { revert NoEvmContract(tokenIndex); } addressToIndex[evmContract] = TokenData({index: tokenIndex, isSet: true}); } ``` -------------------------------- ### Initialize a Forge Project Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/foundry.mdx Initializes a new Forge project with a specified name. Forge is a smart contract build tool for Ethereum. ```bash # Initializes a project called `Counter` forge init Counter ``` -------------------------------- ### Deploy a Contract with Forge Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/foundry.mdx Deploys a smart contract using Forge scripts. Requires setting the private key as an environment variable and specifying the RPC URL for the target network. ```bash # Use forge scripts to deploy the Counter contract # Running `anvil` @ http://localhost:8545 # Set the private key in the env export PRIVATE_KEY="0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" # Address - 0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266 # Run the script and broadcast the deploy transaction forge script script/Counter.s.sol --rpc-url http://127.0.0.1:8545 --broadcast --private-key $PRIVATE_KEY ``` -------------------------------- ### Hyperliquid Test Utility Functions: Price Setters Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/docs/pages/testing/quick-start.mdx These Solidity functions from `CoreSimulatorLib` enable setting the mark price for perpetual markets and the price for spot markets. They offer direct price setting and relative adjustments using basis points (bps), providing granular control over market conditions during testing. ```solidity // set the mark price of a perp market function setMarkPx(uint32 perp, uint64 markPx) internal; // set the mark price by specifying a price difference in bps function setMarkPx(uint32 perp, uint64 priceDiffBps, bool isIncrease) internal; // set the price of a spot market function setSpotPx(uint32 spotMarketId, uint64 spotPx) internal; // set the spot price by specifying a price difference in bps function setSpotPx(uint32 spotMarketId, uint64 priceDiffBps, bool isIncrease) internal; ``` -------------------------------- ### Clone Onchain Contract with Forge Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/foundry.mdx Clones an existing smart contract from the blockchain and sets up a corresponding Forge project for analysis or interaction. ```bash # Clones an onchain contract and sets up a forge project forge clone 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 ``` -------------------------------- ### Import PrecompileLib in Solidity Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/docs/pages/dev/precompiles.mdx This snippet shows how to import the PrecompileLib contract into your Solidity project. It's a prerequisite for using any of its functionalities. ```solidity import { PrecompileLib } from "@hyper-evm-lib/src/PrecompileLib.sol"; ``` -------------------------------- ### Run Forge Tests Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/foundry.mdx Executes tests for smart contracts within a Forge project. Supports running tests against a forked chain state using a provided RPC URL. ```bash # Run tests for the Counter contract forge test # You can run tests against chain state by forking forge test --fork-url https://reth-ethereum.ithaca.xyz/rpc ``` -------------------------------- ### Hyperliquid Test Utility Functions: Balance Setters Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/docs/pages/testing/quick-start.mdx This group of Solidity functions from `CoreSimulatorLib` allows precise control over various account balances within the Hyperliquid ecosystem. You can force spot balances for tokens, perp USD balances, staking balances, delegation amounts, and vault equity, including lock timestamps, facilitating comprehensive testing of financial operations. ```solidity // set an account's spot balance for a token function forceSpotBalance(address account, uint64 token, uint64 _wei) internal; // set an account's withdrawable perp USD function forcePerpBalance(address account, uint64 usd) internal; // set an account's staking balance function forceStakingBalance(address account, uint64 _wei) internal; // set an account's delegation amount and locked until timestamp for a validator function forceDelegation(address account, address validator, uint64 amount, uint64 lockedUntilTimestamp) internal; // set an account's vault equity and lock timestamp for a vault function forceVaultEquity(address account, address vault, uint64 usd, uint64 lockedUntilTimestamp) internal; ``` -------------------------------- ### Hyperliquid Test Utility Functions: Force Account Activation Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/docs/pages/testing/quick-start.mdx This Solidity function `forceAccountActivation` from `CoreSimulatorLib` allows forcing the activation of a Hyperliquid account without requiring token transfers or paying the associated fee. This is useful for setting up specific test scenarios where account activation is a prerequisite. ```solidity // force activate a Core account (without having to transfer tokens and pay the $1 fee) function forceAccountActivation(address account) internal; ``` -------------------------------- ### Hyperliquid Test Utility Functions: Yield/Loss Accrual Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/docs/pages/testing/quick-start.mdx This Solidity utility function `setVaultMultiplier` allows scaling vault equity to simulate profit or loss scenarios for specific vaults. The `setStakingYieldIndex` function simulates staking yield by adjusting an index multiplier. These are crucial for testing yield-bearing mechanisms. ```solidity // scale vault equity to simulate profit/loss scenarios function setVaultMultiplier(address vault, uint256 multiplier) internal; // simulate staking yield function setStakingYieldIndex(uint256 multiplier) internal; ``` -------------------------------- ### Import CoreWriterLib in Solidity Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/docs/pages/dev/corewriter.mdx This snippet shows how to import the CoreWriterLib contract into your Solidity smart contract. It's a prerequisite for using any of its functionalities. ```solidity import {CoreWriterLib} from "@hyper-evm-lib/src/CoreWriterLib.sol"; ``` -------------------------------- ### Cast: Call Contract Function Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/foundry.mdx Performs an eth_call on a contract to read data, such as account balances. Requires the contract address, function signature, and arguments. ```bash # Perform an `eth_call` on a contract to read balances cast call 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 \ "balanceOf(address)" 0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045 \ --rpc-url https://reth-ethereum.ithaca.xyz/rpc ``` -------------------------------- ### Cast: Call JSON-RPC Methods Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/foundry.mdx Calls arbitrary JSON-RPC methods on a node. Accepts the method name and parameters. The `cast 2h` command can convert integers to hexadecimal. ```bash # Calls the `eth_getHeaderByNumber` RPC method with the number param in hexadecimal # cast 2h converts integer to hex cast rpc eth_getHeaderByNumber $(cast 2h 22539851) --rpc-url https://reth-ethereum.ithaca.xyz/rpc ``` -------------------------------- ### Cast: Send Transaction Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/foundry.mdx Sends a transaction to the blockchain. Requires the recipient address, value to send, and a private key for signing. Can also fetch balances. ```bash # Running `anvil` @ http://localhost:8545 # Set the private key in the env export PRIVATE_KEY="0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" # Send the transaction cast send 0x70997970C51812dc3A010C7d01b50e0d17dc79C8 --value 10000000 --private-key $PRIVATE_KEY && \ # Fetch ETH balances echo "\nBalance Of 0x7099:" && cast balance 0x70997970C51812dc3A010C7d01b50e0d17dc79C8 && \ echo "\nBalance Of 0xf39F:" && cast balance 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 ``` -------------------------------- ### Retrieve Token Index from TokenRegistry (Solidity) Source: https://github.com/hyperliquid-dev/hyperlib-docs/blob/main/docs/pages/dev/token-registry.mdx The `getTokenIndex` function retrieves the token index associated with a given EVM contract address. It accesses the `addressToIndex` mapping and reverts with a `TokenNotFound` error if the address has not been registered. ```solidity function getTokenIndex(address evmContract) external view returns (uint32 index) { TokenData memory data = addressToIndex[evmContract]; if (!data.isSet) { revert TokenNotFound(evmContract); } return data.index; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.