Docs

Vault managers

Trading engine

How HyperPerpEngine steps a vault toward a target, the guardrails on every step, CoreWriter orders, USDC bridging and a keeper loop.

Markdown
On this page

HyperPerpEngine trades one vault's HyperCore account. Each call steps one perp market toward a target weight, inside the vault's DNA and risk params, and sends at most one limit order through CoreWriter.

Who can trade#

Three callers can step, bridge and heartbeat: the vault's keeper, its strategy manager and the council. The engine reads all three live from the vault and HyperVaultConfig. There is no API wallet, agent key or signature check. A model running anywhere, including in a TEE, trades by sending transactions from the keeper or manager address.

Anyone may call flatten when a stop allows it, plus the bookkeeping calls syncReturnedUsdc, syncOpenAssets and pruneClosedAssets.

Two ways to step#

Solidity
function stepMarket(uint32 assetId) external;
function stepMarketTarget(uint32 assetId, int16 targetWeightBps) external;
stepMarketstepMarketTarget
TargetThe latest round of vault.forecastJobId() in HyperSignalBook, or job 1 when that is 0The caller's targetWeightBps
Stale signalAn expired or missing round steps toward 0Not applicable
GuardrailsSameSame

Weights are signed bps of engine equity: 5,000 is 50% of equity long, -2,500 is 25% short. The target is clamped to the asset's cap before anything else. Every stepped market must be listed in HyperSignalBook, for flagship and third-party vaults alike; the engine also takes the market's szDecimals from there. See Jobs and rounds for how rounds are posted.

What one step does#

  1. Reverts with BridgeInFlight() inside a 30-second bridge window. Credits any USDC that arrived from HyperCore. Reverts with ZeroAmount() if equity is 0.
  2. Starts a new UTC day if needed (records day-start equity, clears the turnover counter), then checks the daily loss stop and the drawdown latch. See Risk.
  3. Records activity (lastActivityAt), which resets the inactivity clock.
  4. Checks the market: listed (MarketNotActive(assetId)), allowed for the vault's market tier (MarketNotInTier(assetId, marketTier)), a non-zero oracle price (BadOraclePrice(assetId)), and at least 30 seconds since the last order on this asset (StepTooSoon()).
  5. Resolves the target and clamps it to the per-asset cap.
  6. Moves at most maxStepBps from the current weight toward the target (0 means the full distance) and sizes the order in whole lots.
  7. If the position is already at that size, cancels any resting order and stops.
  8. Checks portfolio exposure, the margin floor and daily turnover, then cancels the previous resting order and sends the new one.

A step that trips the daily loss stop or the drawdown latch returns without trading, so the latch is saved. Later steps revert with DayStopped() or DrawdownStopped().

Guardrails on every step#

GuardrailSourceRuleRevert
Per-asset capHyperVaultConfig.isAssetAllowedForVaultMarket-tier weight times the vault-tier multiplier, at most 100%. Flagships also take the signal book's maxWeightBps.Clamped, no revert
Step sizemaxStepBpsWeight change per stepClamped, no revert
GrossDNA maxGrossBpsGross may not grow above itGrossLeverageExceeded(nextGrossBps, maxGrossBps)
NetDNA maxNetExposureBpsAbsolute net may not grow above itNetExposureExceeded(nextNetBps, maxNetBps)
Margin floorminMarginRatioBpsEquity over notional, when the asset's gross growsMarginRatioTooLow(nextMarginRatioBps, minMarginRatioBps)
TurnovermaxDailyTurnoverBpsDay turnover plus this order, at most that share of day-start equity. Reducing orders count.DailyTurnoverExceeded(nextTurnoverUsdc, maxTurnoverUsdc)
Minimum orderMIN_ORDER_NOTIONAL_USDCOrders below 10 USDC notional are skipped, except a close to 0Skipped
Settle windowORDER_SETTLE_SECS30 seconds per asset between ordersStepTooSoon()

Exposure checks count the live portfolio plus orders sent in the current and previous 30-second windows, so a burst of steps cannot outrun HyperCore's state. A resting order older than 30 seconds counts at whichever is larger: the position or the order's target.

Two cases close regardless of target and skip the turnover cap: a market paused in the signal book, and a vault in wind-down. An asset delisted from your tier can only be stepped to 0.

Order pricing#

defaultTifCodeLimit price
ALO (post-only)1Buy at oracle × (1 − makerOffsetBps), sell at oracle × (1 + makerOffsetBps)
GTC2Buy at oracle × (1 + maxSlippageBps), sell at oracle × (1 − maxSlippageBps)
IOC3Same as GTC

Prices round to HyperCore's perp tick: 5 significant figures and at most 6 − szDecimals decimals, down for buys and up for sells. If rounding would put a crossing order on the wrong side of the oracle, the order is skipped. Sizes round down to whole lots, 10^(8 − szDecimals) in 1e8 units. A step sizes from the target, so a close leaves no dust.

flatten and deleverage trims always use reduce-only IOC at maxSlippageBps.

CoreWriter actions#

Every action is CoreWriter.sendRawAction(abi.encodePacked(uint8(1), uint24(actionId), abi.encode(...))). The engine uses three:

ActionIdPayloadUsed by
Limit order1(uint32 assetId, bool isBuy, uint64 limitPx, uint64 sz, bool reduceOnly, uint8 tif, uint128 cloid), price and size 1e8-scaledSteps, flatten, deleverage trims
Cancel by cloid11(uint32 assetId, uint128 cloid)Before each new order on an asset; at target; in flatten
Send asset13(address destination, address subAccount, uint32 sourceDex, uint32 destinationDex, uint64 token, uint64 wei), token 0 (USDC), wei = usdc × 100HyperCore to HyperEVM, and between dexes

Each engine numbers its orders with a monotonic cloid. Orders emit CoreOrderDispatched(assetId, cloid, isBuy, sz, limitPx, tif, reduceOnly, targetWeightBps) and cancels emit CoreOrderCancelled(assetId, cloid). CoreWriter actions settle on HyperCore after the EVM block, so a transaction that succeeds on HyperEVM can still see its order rejected by HyperCore. Read positions back before you assume a fill.

Moving USDC#

Solidity
// HyperVault (keeper, manager or council)
function deployToEngine(uint256 usdcAmount) external;
// HyperPerpEngine (keeper, manager or council)
function bridgeUsdcToCore(uint256 usdcAmount, uint32 destinationDex) external;
function bridgeUsdcFromCore(uint64 usdcAmount, uint32 sourceDex) external;
function transferMarginBetweenDexes(uint32 sourceDex, uint32 destinationDex, uint64 usdcAmount) external;
// HyperPerpEngine (anyone)
function syncReturnedUsdc() external returns (uint256 credited);

All amounts are USDC with 6 decimals.

  • Vault to engine. deployToEngine moves idle USDC into the engine's HyperEVM balance. It reverts with VaultWindingDown() or EngineDrawdownStopped() when either applies. It does not hold back USDC owed to unsettled withdrawals, so keep enough idle for the next roll.
  • HyperEVM to HyperCore. bridgeUsdcToCore calls the Circle CoreDepositWallet.deposit(amount, destinationDex), with destinationDex 0 (perp dex 0) or 4294967295 (SPOT_DEX). Minimum 1 USDC. Blocked during wind-down.
  • HyperCore to HyperEVM. bridgeUsdcFromCore sends action 13 to the USDC system address 0x2000000000000000000000000000000000000000. The amount must be at most what the source can release, dexWithdrawableUsdc(engine, sourceDex). The engine books it as pending; syncReturnedUsdc credits it when it lands. Pending USDC that has not arrived after 10 minutes moves to lateFromCoreUsdc and can still be credited later.
  • Between dexes. transferMarginBetweenDexes moves margin between tracked perp dexes and spot with action 13 to the engine itself.

Each bridge in either direction opens a 30-second window (isBridging()). In that window, steps, vault deposits, rolls and withdrawal settlement revert with BridgeInFlight(), because in-flight USDC is not yet in NAV. The next bridge must wait 2 minutes (BridgeTooSoon(nextAllowedAt)).

The engine sends USDC back to the vault only when the vault asks: at the roll, in withdrawal settlement and in flushAccruedFees. Nobody else can move engine USDC.

Multi-dex margin#

The engine's equity is its HyperEVM idle USDC plus the account value on every tracked perp dex and its spot USDC. Perp dex 0 is always tracked. The adapter admin can track up to 16 dexes in total, HIP-3 dexes included. HIP-3 asset ids are 100000 + dex × 10000 + index.

  • On a HIP-3 dex, the releasable amount is account value minus the larger of margin used and 10% of open notional.
  • CoreWriter cannot set leverage or margin mode. Assets that HyperCore marks isolated-only are capped by the adapter's isolatedCapBps, and a cap of 0 forces them flat.
  • If any tracked dex's margin read fails, every NAV read reverts until the dex is removed. A dex is removed only once no engine holds anything on it.

Heartbeat and inactivity#

Every successful step records activity. If your model holds positions without changing them, call heartbeat() before maxIdleSecs runs out. Once the vault is idle for maxIdleSecs, isInactive() turns true and anyone may flatten the book. Nothing closes automatically; someone has to call it. See Risk.

HyperCore reads#

The engine reads HyperCore through HyperL1ReadAdapter, which wraps the L1Read precompiles and normalizes to 1e8 prices and sizes and 1e6 USDC.

PrecompileReadEngine use
0x0801spotBalanceSpot USDC in equity; spot withdrawable
0x0803withdrawableReleasable USDC on dex 0
0x0807oraclePxOrder pricing and position notional
0x0808spotPxToken-launch contracts only
0x080aperpAssetInfoChecking szDecimals and isolated-only flags when an asset is configured
0x080CtokenInfoToken-launch contracts only
0x080ebboToken-launch contracts only
0x080FaccountMarginSummaryEquity and margin per dex
0x0813position2Position size

A keeper loop#

This loop rolls the vault each UTC day, then steps each asset toward your model's target with stepMarketTarget. It skips assets still inside their 30-second window and stops on a latched stop.

keeper.ts
import {
  BaseError, ContractFunctionRevertedError, createPublicClient, createWalletClient,
  defineChain, http, parseAbi, type Address,
} from "viem";
import { privateKeyToAccount } from "viem/accounts";

const hyperEvm = defineChain({
  id: 999,
  name: "HyperEVM",
  nativeCurrency: { name: "HYPE", symbol: "HYPE", decimals: 18 },
  rpcUrls: { default: { http: ["https://rpc.hyperliquid.xyz/evm"] } },
});

const VAULT = process.env.VAULT as Address;   // placeholder, published at launch
const ENGINE = process.env.ENGINE as Address; // placeholder, published at launch
const keeper = privateKeyToAccount(process.env.KEEPER_KEY as `0x${string}`);

const publicClient = createPublicClient({ chain: hyperEvm, transport: http() });
const wallet = createWalletClient({ account: keeper, chain: hyperEvm, transport: http() });

const vaultAbi = parseAbi([
  "function rollDue() view returns (bool)",
  "function roll()",
  "error RollNotDue()",
  "error BridgeInFlight()",
  "error Unauthorized()",
]);

const engineAbi = parseAbi([
  "struct EngineState { address vaultConfig; address coreDepositWallet; bool windingDown; bool emergencyFlattening; bool dayLossStopped; bool drawdownStopped; uint64 currentUtcDay; uint64 lastActivityAt; uint64 lastBridgeAt; uint64 lastDeleverageAt; uint64 pendingFromCoreSetAt; uint64 drawdownResetDay; uint128 drawdownPeakPps; uint128 nextCloid; uint256 dayStartEquityUsdc; uint256 dayTurnoverUsdc; uint256 evmIdleUsdc; uint256 pendingFromCoreUsdc; uint256 lateFromCoreUsdc; uint256 bridgeInFlightToCoreUsdc; uint256 bridgeInFlightFromCoreUsdc; }",
  "function state() view returns (EngineState)",
  "function isBridging() view returns (bool)",
  "function stepMarketTarget(uint32 assetId, int16 targetWeightBps)",
  "function heartbeat()",
  "error StepTooSoon()",
  "error DayStopped()",
  "error DrawdownStopped()",
  "error BridgeInFlight()",
  "error MarketNotActive(uint32 assetId)",
  "error MarketNotInTier(uint32 assetId, uint8 marketTier)",
  "error BadOraclePrice(uint32 assetId)",
  "error GrossLeverageExceeded(uint256 nextGrossBps, uint24 maxGrossBps)",
  "error NetExposureExceeded(int256 nextNetBps, uint16 maxNetBps)",
  "error MarginRatioTooLow(uint256 nextMarginRatioBps, uint16 minMarginRatioBps)",
  "error DailyTurnoverExceeded(uint256 nextTurnoverUsdc, uint256 maxTurnoverUsdc)",
  "error Unauthorized()",
  "error ZeroAmount()",
]);

// Your model: HyperCore perp asset id -> signed target weight in bps of equity.
async function modelTargets(): Promise<Map<number, number>> {
  return new Map([
    [0, 3_000],  // 30% long
    [1, -1_500], // 15% short
  ]);
}

function revertName(err: unknown): string | undefined {
  if (!(err instanceof BaseError)) return undefined;
  const reverted = err.walk((e) => e instanceof ContractFunctionRevertedError);
  return reverted instanceof ContractFunctionRevertedError ? reverted.data?.errorName : undefined;
}

async function roll() {
  const { request } = await publicClient.simulateContract({
    account: keeper, address: VAULT, abi: vaultAbi, functionName: "roll",
  });
  await publicClient.waitForTransactionReceipt({ hash: await wallet.writeContract(request) });
}

async function step(assetId: number, targetWeightBps: number) {
  const { request } = await publicClient.simulateContract({
    account: keeper, address: ENGINE, abi: engineAbi, functionName: "stepMarketTarget",
    args: [assetId, targetWeightBps],
  });
  await publicClient.waitForTransactionReceipt({ hash: await wallet.writeContract(request) });
}

async function heartbeat() {
  const { request } = await publicClient.simulateContract({
    account: keeper, address: ENGINE, abi: engineAbi, functionName: "heartbeat",
  });
  await publicClient.waitForTransactionReceipt({ hash: await wallet.writeContract(request) });
}

async function tick() {
  if (await publicClient.readContract({ address: ENGINE, abi: engineAbi, functionName: "isBridging" })) return;

  // 1. Roll once per UTC day, inside the keeper window (00:00-02:00 UTC).
  if (await publicClient.readContract({ address: VAULT, abi: vaultAbi, functionName: "rollDue" })) {
    await roll();
  }

  // 2. Stop if a latch, an emergency or a wind-down is set. The engine would revert anyway.
  const s = await publicClient.readContract({ address: ENGINE, abi: engineAbi, functionName: "state" });
  if (s.windingDown || s.emergencyFlattening || s.dayLossStopped || s.drawdownStopped) {
    console.warn("engine stopped", s);
    return;
  }

  // 3. Step each asset toward its target.
  let stepped = false;
  for (const [assetId, bps] of await modelTargets()) {
    try {
      await step(assetId, bps);
      stepped = true;
    } catch (err) {
      const name = revertName(err);
      if (name === "StepTooSoon") continue;               // 30 s settle window on this asset
      if (name === "DailyTurnoverExceeded") break;        // budget spent until 00:00 UTC
      if (name === "GrossLeverageExceeded" || name === "NetExposureExceeded" || name === "MarginRatioTooLow") {
        console.warn(`asset ${assetId}: ${name}, trim the target`);
        continue;
      }
      throw err;
    }
  }

  // 4. Keep the inactivity clock alive when nothing traded for a day.
  const idleFor = BigInt(Math.floor(Date.now() / 1000)) - s.lastActivityAt;
  if (!stepped && idleFor > 86_400n) await heartbeat();
}

setInterval(() => tick().catch(console.error), 60_000);

Monitoring views#

ViewReturns
state()EngineState: stops, flags, day-start equity, turnover, idle and pending USDC
totalEquityUsdc()Engine leg of NAV, USDC 1e6
portfolioExposureBps(uint256 equity)(uint256 grossBps, int256 netBps)
currentMarginRatioBps()Equity over notional, bps
openAssets()Assets with a position or a resting order
isBridging(), isInactive(), canFlatten(), isFlat()Status flags
riskParams(), pendingRiskParams(), vaultDna()Current limits

The read API mirrors these at GET /v1/vaults/{vault}/engine, /engine/orders, /engine/fills and /engine/events. See API.

These docs describe the architecture and smart contracts across Hyperliquid L1 (HyperEVM) (chain id 999) and Robinhood Chain (chain id 4663). Nothing here is investment advice or a promise of returns. DegenHive is not affiliated with, endorsed by, or sponsored by Hyperliquid, Robinhood Markets, Inc., Nasdaq, Inc., or their affiliates.