Testing quick start
hyper_vyper.testing contains CoreSim, a small, deterministic model of HyperCore for Titanoboa tests. Use it when a test needs to see what Core does after an action, not just the bytes of the action.
On this page you write a test that moves USDC from EVM to Core spot, back to EVM and then to perp, with CoreSim standing in for HyperCore. You don't need a wallet, an RPC endpoint or funds.
1. Install
Add the library, then add its testing extra and pytest to your test environment. The extra adds Titanoboa 0.2.8 and eth-abi.
2. Write the contract
Save this contract as spot_round_trip.vy. It is the same file as examples/spot_round_trip.vy, and it imports all five modules.
# pragma version 0.4.3
# pragma evm-version cancun
# pragma optimize gas
# SPDX-License-Identifier: MIT
"""
@title Spot round trip example
@notice Moves USDC from EVM to Core spot and back. The testing quick start
runs it against the HyperCore simulator.
@dev An example for the documentation. Nobody has audited it. It has no
access control. Do not deploy it with real funds.
"""
from ethereum.ercs import IERC20
from hyper_vyper import bridge
from hyper_vyper import constants
from hyper_vyper import conversions
from hyper_vyper import core_writer
from hyper_vyper import precompiles
@external
def deposit_to_spot(amount: uint256):
"""Send EVM USDC (6 decimals) to this contract's Core spot balance."""
bridge.bridge_usdc_to_core(amount, constants.SPOT_DEX)
@external
def move_to_perp(amount: uint64):
"""Move USDC from Core spot to perp. The amount is in perp units (6 decimals)."""
core_writer.transfer_usd_class(amount, True)
@external
def return_from_spot(amount: uint256):
"""Return USDC (6 decimals) from Core spot to this contract's EVM address."""
bridge.bridge_usdc_to_evm(amount, constants.SPOT_DEX)
@external
@view
def core_spot_usdc() -> uint64:
"""Core spot USDC in 8-decimal units, as of the start of this block."""
return precompiles.spot_balance(self, constants.USDC_TOKEN_INDEX).total
@external
@view
def evm_usdc() -> uint256:
"""EVM USDC in 6-decimal units."""
return staticcall IERC20(conversions.usdc_address()).balanceOf(self)
The contract has no access control, so use it only in tests.
3. Write the test
Save this test as test_spot_round_trip.py, next to the contract. It is the same file as examples/test_spot_round_trip.py.
"""Test examples/spot_round_trip.vy against the HyperCore simulator (CoreSim)."""
from pathlib import Path
import boa
import pytest
from hyper_vyper.testing import CoreSim
CONTRACT = Path(__file__).with_name("spot_round_trip.vy")
USDC = 10**6 # EVM USDC and perp USD: 6 decimals
CORE_USDC = 10**8 # Core spot USDC: 8 decimals
HYPE = 10**8 # Core HYPE: 8 decimals
@pytest.fixture
def sim():
boa.reset_env()
sim = CoreSim.install(chain_id=999) # mainnet addresses and token indices
yield sim
sim.close()
def test_spot_round_trip(sim):
contract = boa.load_partial(str(CONTRACT)).deploy()
sim.usdc.mint(contract.address, 100 * USDC)
# An activated account gets the full deposit, with no 1 USDC fee.
# HYPE on Core pays the return gas.
sim.activate(contract)
sim.set_hype(contract, 1 * HYPE)
sim.publish()
contract.deposit_to_spot(100 * USDC)
assert contract.core_spot_usdc() == 0 # Core runs after the EVM block
sim.advance()
assert contract.core_spot_usdc() == 100 * CORE_USDC
contract.return_from_spot(40 * USDC)
sim.advance()
assert contract.evm_usdc() == 40 * USDC
assert contract.core_spot_usdc() == 60 * CORE_USDC
contract.move_to_perp(10 * USDC)
sim.advance()
assert sim.perp(contract).usd == 10 * USDC
assert not sim.failures
The test works through these steps:
- The
simfixture resets the Titanoboa environment and installsCoreSimwith the mainnet addresses (chain 999). After the test, it removes the precompile callbacks. sim.usdc.mintgives the contract mock USDC on EVM.sim.activateandsim.set_hypecreate an activated Core account with a little HYPE. An activated account gets the exact deposit, with no 1 USDC fee, and the HYPE pays the gas of the return.sim.publish()makes this setup visible to reads immediately.deposit_to_spotsends the deposit. A read in the same block still shows 0, because Core runs after the EVM block.sim.advance()ends the block, Core applies the deposit, and the next read shows it.- The return and the move to perp work the same way, and each needs a
sim.advance()before its result is visible. sim.failuresis empty, so no action failed silently on Core.
4. Run the test
Next, test the failure paths too. For example, sim.fail_next("send_asset") makes the next return fail silently on Core, and you can check that your contract keeps the transfer as pending. Change Policy fields to test other Core behavior.
How CoreSim works
CoreSim.install(chain_id) prepares the Titanoboa EVM:
- It deploys mock USDC, a mock Circle CoreDepositWallet, a journal at the CoreWriter address and a mock at the HYPE system address (
0x2222...2222), each at its real address for the chain. - It registers Python callbacks at the read precompiles (
0x0800to0x0813). - It watches each transaction for a
Transferof a linked token to the token's system address.
After that, a test runs like this:
- Precompile reads give the Core state at the start of the block, so a transaction never sees its own Core effects.
- CoreWriter actions, USDC deposits and HYPE transfers go into a queue. A reverted EVM transaction leaves nothing in the queue.
sim.advance()ends the block. Core applies the queued items in order, pays Core-to-EVM returns on EVM and takes a new snapshot.- A failed item changes nothing on Core, and the EVM transaction does not revert.
sim.eventsandsim.failuresrecord the reason.
sequenceDiagram
participant T as Test
participant C as Your contract
participant S as CoreSim
T->>C: bridge_usdc_to_core(...)
C->>S: deposit goes into the queue
T->>C: read balances
S-->>C: state at block start (no deposit yet)
T->>S: advance()
S->>S: apply the deposit, take a new snapshot
T->>C: read balances
S-->>C: deposit is visible
Move blocks only with sim.advance(). A raw boa.env.time_travel moves the EVM block without moving Core, and the next read then raises an error.
What the model follows
These rules come from the Hyperliquid documentation, the Circle documentation, and, where those documents are silent, HyperCore's behavior.
- Reads show Core state as of the start of the EVM block.
- CoreWriter actions run after the EVM block, and failures are silent on EVM. A failed action pays no gas.
- A transfer, a return or a deposit sent in EVM block N shows in block N+1.
- Orders and vault transfers have an extra delay of a few seconds. Core runs a vault transfer about 4 s after its EVM block, so CoreSim runs it 4 blocks later with 1 s blocks.
- USDC has 6 decimals on EVM, 8 on Core spot and 6 for perp USD.
- Core token 0 (USDC) links to the CoreDepositWallet, not to the USDC token.
- A CoreDepositWallet deposit credits the exact amount, with no fee. A deposit to a DEX that does not exist credits spot.
- Activation, escrow and the 1 USDC fee follow security.
sim.account_stategives missing, escrow-only or activated, andsim.escrow(user)shows the escrow. Actions from an account that is not activated fail with "sender not activated". - A
send_assetmoves USDC between spot, perp DEX 0 and each HIP-3 DEX that exists.sim.add_perp_dex(dex),sim.set_perp(user, dex=dex)andsim.add_pnl(user, dex=dex)make a DEX exist. A transfer to or from another DEX fails with "unknown perp DEX". - A
send_assetfrom perp DEX 0 or a HIP-3 DEX to the USDC system address returns USDC to EVM. - In a transfer, perp DEX 0 keeps back the larger of the margin used and 10% of the notional, as security gives, with the 10% rounded up. A HIP-3 DEX keeps back only the margin used, isolated margin included.
add_api_walletfails for an address that is already a HyperCore user, as the exchange API does. The simulator accepts an escrow-only address.- The Core debit and the EVM credit of a return land in the same block, and the EVM credit is a system transaction at the start of that block.
- A USDC return pays gas as security describes. A HIP-3 DEX never pays the gas. If nothing can pay both the amount and the gas, the return fails.
- Each HIP-3 DEX has one collateral token, USDC unless
sim.add_perp_dex(dex, collateral=token)names another. Asend_assetto or from a DEX moves only its collateral token. - An ERC-20
Transferto a token's system address credits the sender's Core spot after the block, ifsim.link_evm_tokenlinked the token. It lands after the CoreWriter actions of the same transaction. A reverted transaction credits nothing. - An action with an amount of 0 fails with "zero amount". A failed staking or USD class action records a failed event with its reason.
CoreSim assumes the behavior above in these cases:
- the rounding of the 10% that perp DEX 0 keeps back
- an escrow-only address as an API wallet
- the order of a linked-token credit and the CoreWriter actions of the same transaction
- an action with an amount of 0, and a failed staking or USD class action
- the gas of a return, which
Policysets
Orders
- An order reads its market from the same metadata as the reads. Register it with
sim.add_perp,sim.add_spotandsim.add_token, or withsim.set_reply. - An order fails if its price breaks the tick rule or its value is below 10 USD. Core drops such an order with no record. A size rounds down to whole lots, and a size below one lot fails.
- A buy crosses when its limit is at or above the mark price (perp) or the spot price. It then fills in full at that price and pays the taker fee. There is no order book depth.
- An order that does not cross rests if its time in force is GTC or ALO, and fails if it is IOC. An ALO order that crosses fails. A resting order fills at its limit price, at the maker fee, in the first
sim.advance()at which the price crosses. - A resting spot order holds the quote token (buy) or the base token (sell) in the spot balance's
hold. A fill or a cancel releases it. - Spot buys pay fees in the base token they buy, and spot sells pay fees in the quote token they get.
- A perp order needs a leverage from
sim.set_leverage, because CoreWriter has no leverage action. An order that opens or adds to a position fails with "insufficient margin to place order" if the DEX's account value is below its margin used after the fill. A reduce-only order never increases a position. - A fill against a position realizes PnL at the position's average entry price. The margin summary adds each traded position at its mark price.
- At the start of each
sim.advance(), a DEX whose account value is below the maintenance margin (half the initial margin at the maximum leverage) loses its traded positions and its USD. This is a simplification, not HyperCore's liquidation. Don't use it as evidence of what happens to an account in a deep loss. - Cancels by order ID or client order ID release the order. An unknown order fails.
sim.place_orderputs an order on the book now, as an API wallet would.
Staking and vaults
staking_depositmoves spot HYPE to staking,delegate_tokenmoves it to a validator for at least 1 day, andstaking_withdrawpays it back to spot after 7 days. An account can have 5 pending withdrawals.sim.set_staking_yield_indexscales every delegation, as rewards do.sim.set_vault_multiplierscales every holder's equity in a vault, as its trading gains and losses do. A vault withdrawal below 1/10^8 of the vault's equity fails.- A vault deposit locks the depositor's equity in that vault until
vault_lock_msafter Core runs the deposit, so each new deposit restarts the lock. During the lock every withdrawal fails with "vault withdrawal locked", whatever the amount. A lock ends when the time in milliseconds passeslocked_until, as the library checks it. - A withdrawal above the depositor's equity fails with "insufficient vault equity", even when it is over by one unit. Core never pays part of it.
- A withdrawal that would leave more than $0 and less than $5 of the depositor's equity in the vault fails with "vault deposits must be at least $5".
- A withdrawal of
usd = 0takes the whole equity at the time Core runs it. Use it to empty a position whose equity can move between your read and the withdrawal.
Through CoreWriter, Core refuses a withdrawal silently. The EVM transaction succeeds, Core writes no ledger entry, and the equity does not change. A user vault locks a deposit for 1 day, and HLP for 4 days.
Settings
Policy holds the simulator's timing and behavior settings. The defaults follow HyperCore. To test your contract against other behavior, change a field:
Policy field |
Default | Meaning |
|---|---|---|
block_time |
1 |
Seconds per small EVM block. |
transfer_delay_blocks |
1 |
Blocks until Core applies an action: the next block. |
delayed_action_blocks |
3 |
Extra blocks for orders and vault transfers, after transfer_delay_blocks. The Hyperliquid documentation gives the delay as a few seconds. A vault transfer takes about 4 s. |
deposit_delay_blocks |
1 |
Blocks from the deposit wallet to Core: the next block. |
evm_credit_extra_blocks |
0 |
Extra blocks for the EVM payout after the Core debit. HyperCore lands both in the same block. |
evm_transfer_fee_hype_wei |
2_000 |
Return gas in Core HYPE units. |
evm_transfer_fee_usdc_fallback_wei |
92_700 |
Return gas in Core USDC units when spot has no HYPE: 0.000927 USDC. |
new_account_fee |
1_000_000 |
Activation fee: 1 USDC in perp units. |
deposit_to_inactive |
"activate" |
A CoreDepositWallet deposit to an account that is not activated: "activate" (it activates the account and pays the 1 USDC fee from the amount) or "drop" (the testnet wallet, for an address without a mainnet account). |
vault_lock_ms |
86_400_000 |
Lock of a user-vault deposit: 1 day. |
perp_taker_fee_ppm |
450 |
Hyperliquid's base-tier perp taker fee, for a crossing fill, in millionths of the notional. |
perp_maker_fee_ppm |
150 |
Perp maker fee, for a resting order's fill. |
spot_taker_fee_ppm |
700 |
Spot taker fee, for a crossing fill. |
spot_maker_fee_ppm |
400 |
Spot maker fee, for a resting order's fill. |
unstaking_delay_ms |
604_800_000 |
Wait from staking_withdraw to spot HYPE: 7 days. |
delegation_lock_ms |
86_400_000 |
Lock of a new delegation: 1 day. |
max_pending_withdrawals |
5 |
Staking withdrawals that an account can wait for. |
unified_mode |
False |
Apply the transfer rules of unified account mode to an account in abstraction mode 2. |
Other simplifications:
- One L1 block per EVM block. HyperCore makes about 13 to 20 L1 blocks per EVM block.
- Returned USDC comes from the mock deposit wallet's reserve, and the simulator mints more if the reserve is too small.
- A Core send of less than 1 USDC to an account that is not activated fails.
- A spot-to-perp amount in Core wei that is not a multiple of 100 fails.
- A return of a token other than USDC or HYPE fails without HYPE on Core.
- The simulator treats every position as cross margin. On a HIP-3 DEX, put isolated margin in
margin_used. To get anotherwithdrawableamount, setmargin_usedandntl_poswithsim.set_perp. sim.set_positionsets the position that the read shows, and adds nothing to the margin summary, so set those numbers withsim.set_perp.sim.set_leveragehands the position to orders, and the margin summary then counts it.- Resting perp orders hold no margin. CoreSim does not model funding.
- With
unified_mode, an account in mode 2 refuses every send from a perp DEX and every spot-perp move, a deposit to DEX 0 lands in spot, entering the mode moves the DEX 0 USDC above the margin used to spot, and leaving it fails while a traded position is open. CoreSim does not model margin shared across DEXes.
Limits
What the model follows lists each rule. The library's tests against the Solidity library check the encoding of each action, not how closely CoreSim follows HyperCore.
- The simulator records borrow and lend, builder fees and token finalization, but doesn't apply them.
- API wallets are only stored, so an API wallet places no orders. Use
sim.place_orderfor its orders. - A CoreDepositWallet deposit to a HIP-3 DEX credits spot. There are no sub-accounts.
- The simulator sees an ERC-20 sent to a system address only if the token emits
Transferandsim.link_evm_tokenlinked it. Otherwise callsim.bridge_in(user, token, amount_wei)after the send. A revert does not undobridge_in. Core sees an observed transfer after the CoreWriter actions of the same transaction. - The HYPE system mock writes to storage, so a HYPE send with the 2,300 gas stipend (
send) fails here even though it succeeds on chain. Useraw_call. - Setup helpers (
set_spot,set_perp,set_hype,activate) activate an account without a fee. - A precompile without a model reverts. Use
sim.set_replyto give it a fixed reply. - The journal stores actions in storage, so CoreWriter gas is higher than on chain. Don't use the simulator for gas measurements.
Useful methods
| Method | Use |
|---|---|
CoreSim.install(chain_id, policy) |
Deploy the mocks and register the precompiles. Use 999 (mainnet) or 998 (testnet). |
sim.close() |
Remove the precompile callbacks. |
sim.advance(blocks=1) |
End the block and let Core run. |
sim.activate(*users) |
Activate accounts without a fee, for test setup. |
sim.set_spot, sim.set_hype, sim.set_perp |
Set Core balances for test setup. |
sim.set_price, sim.set_position, sim.set_vault_equity |
Set prices, positions and vault equity. |
sim.add_perp, sim.add_spot, sim.add_token, sim.add_perp_dex |
Register markets, tokens and HIP-3 DEXes. |
sim.set_leverage, sim.place_order |
Let orders trade a perp, and place an API wallet's order. |
sim.set_staking, sim.set_delegation, sim.add_validator, sim.set_staking_yield_index |
Set up staking. |
sim.set_vault_multiplier |
Change a vault's equity for every holder. |
sim.position(user, perp), sim.orders, sim.fills, sim.liquidatable(user, dex) |
Inspect positions, resting orders and fills. |
sim.publish() |
Make setup changes visible to reads in the current block. |
sim.spot(user), sim.perp(user), sim.escrow(user) |
Read the live Core state. |
sim.events, sim.failures, sim.pending |
Inspect what Core did. |
sim.fail_next(name, reason) |
Make the next action fail on Core. |
sim.usdc |
The mock USDC contract. Use sim.usdc.mint(address, amount). |
hyper_vyper.testing also exports the addresses and values that the simulator uses:
| Name | Value |
|---|---|
USDC, WALLET |
The USDC token and the Circle CoreDepositWallet, as {chain_id: address} |
CORE_WRITER, HYPE_SYSTEM |
The CoreWriter address and the HYPE system address 0x2222...2222 |
USDC_TOKEN, HYPE_TOKEN |
The Core token index of USDC (0), and of HYPE as {chain_id: index} |
SPOT_DEX |
The DEX index for spot |
system_address(token, chain_id) |
The system address of a linked token |
live_reply(name, chain_id) |
A precompile reply recorded from the real chain |
Start from live HyperCore state
CoreSim.install(chain_id, seed=RPC_URL) starts Core state from a node. An account, a spot balance, a perp DEX, a vault equity or a price loads from the node the first time the test uses it, and the simulated changes then apply to that copy. A precompile without a model, such as token_supply, answers from the node.
- CoreSim reads each value once, so the block-start view and the live state agree.
- An account that exists on HyperCore loads its staking state at once. CoreSim splits the account's pending staking withdrawals evenly and pays them 7 days after the load, because no read gives each one.
- A perp DEX loads from its margin summary. A position on it becomes a traded position if you registered its perp with
sim.add_perpbefore the DEX loads. The read of any other position asks the node. - A HIP-3 DEX needs
sim.add_perp_dexbefore a transfer can reach it, because no read gives a DEX's collateral token. - Liquidation, staking withdrawals and the 1/10^8 vault minimum see only the accounts that the test has used.
seedcan also be a functionread(suffix, data) -> bytes | None, for example recorded replies, so a test runs without network access.installstill deploys the mocks at the USDC, CoreDepositWallet, CoreWriter and HYPE system addresses, also in a fork.
Test against live HyperCore state
forward_precompiles answers the HyperCore read precompiles from a live node instead of the simulator. Titanoboa's fork mode runs your contract on a local copy of the chain, and that copy has no HyperCore precompiles, so a contract that reads Core state needs this helper there:
import boa
from hyper_vyper.testing import forward_precompiles
RPC = "https://rpc.hyperliquid.xyz/evm"
with forward_precompiles(RPC):
boa.fork(RPC)
contract = boa.load("read_core.vy")
print(contract.core_usdc_balance("0xSOME_ADDRESS")) # the live Core balance
The helper works in network mode (boa.set_network_env) too, and the tutorial scripts use it in both modes.
- The node answers with the HyperCore state at its latest block, not at the block of the fork.
- A CoreWriter action in the fork only emits its event. Use
CoreSimto test what Core does after an action. - In network mode, Titanoboa compares each local view result with the node's. The local copy of the chain moves forward only when the script sends a transaction, so a view that returns
block.numberdiffers. Titanoboa then warns "local fork did not match node!" and returns the node's result.
Check on testnet
A simulator can share a wrong assumption with your contract. Before you put funds in a contract, run it on testnet with small amounts. The tutorials show how.