# Trading engine

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

Source: https://docs.degenhive.ai/vaults/trading

`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.

> [!IMPORTANT]
> The engine is not deployed yet and not externally audited. `VAULT` and `ENGINE` in the code below are placeholders; addresses publish at launch on [Network](https://docs.degenhive.ai/network.md).

## 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;
```

| | `stepMarket` | `stepMarketTarget` |
|---|---|---|
| Target | The latest round of `vault.forecastJobId()` in `HyperSignalBook`, or job 1 when that is 0 | The caller's `targetWeightBps` |
| Stale signal | An expired or missing round steps toward 0 | Not applicable |
| Guardrails | Same | Same |

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](https://docs.degenhive.ai/forecasters/jobs-and-rounds.md) 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](https://docs.degenhive.ai/vaults/risk.md).
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

| Guardrail | Source | Rule | Revert |
|---|---|---|---|
| Per-asset cap | `HyperVaultConfig.isAssetAllowedForVault` | Market-tier weight times the vault-tier multiplier, at most 100%. Flagships also take the signal book's `maxWeightBps`. | Clamped, no revert |
| Step size | `maxStepBps` | Weight change per step | Clamped, no revert |
| Gross | DNA `maxGrossBps` | Gross may not grow above it | `GrossLeverageExceeded(nextGrossBps, maxGrossBps)` |
| Net | DNA `maxNetExposureBps` | Absolute net may not grow above it | `NetExposureExceeded(nextNetBps, maxNetBps)` |
| Margin floor | `minMarginRatioBps` | Equity over notional, when the asset's gross grows | `MarginRatioTooLow(nextMarginRatioBps, minMarginRatioBps)` |
| Turnover | `maxDailyTurnoverBps` | Day turnover plus this order, at most that share of day-start equity. Reducing orders count. | `DailyTurnoverExceeded(nextTurnoverUsdc, maxTurnoverUsdc)` |
| Minimum order | `MIN_ORDER_NOTIONAL_USDC` | Orders below 10 USDC notional are skipped, except a close to 0 | Skipped |
| Settle window | `ORDER_SETTLE_SECS` | 30 seconds per asset between orders | `StepTooSoon()` |

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

| `defaultTif` | Code | Limit price |
|---|---|---|
| ALO (post-only) | 1 | Buy at oracle × (1 − `makerOffsetBps`), sell at oracle × (1 + `makerOffsetBps`) |
| GTC | 2 | Buy at oracle × (1 + `maxSlippageBps`), sell at oracle × (1 − `maxSlippageBps`) |
| IOC | 3 | Same 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:

| Action | Id | Payload | Used by |
|---|---|---|---|
| Limit order | 1 | `(uint32 assetId, bool isBuy, uint64 limitPx, uint64 sz, bool reduceOnly, uint8 tif, uint128 cloid)`, price and size 1e8-scaled | Steps, `flatten`, deleverage trims |
| Cancel by cloid | 11 | `(uint32 assetId, uint128 cloid)` | Before each new order on an asset; at target; in `flatten` |
| Send asset | 13 | `(address destination, address subAccount, uint32 sourceDex, uint32 destinationDex, uint64 token, uint64 wei)`, token 0 (USDC), `wei = usdc × 100` | HyperCore 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](https://docs.degenhive.ai/vaults/risk.md#inactivity-flatten).

## HyperCore reads

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

| Precompile | Read | Engine use |
|---|---|---|
| `0x0801` | `spotBalance` | Spot USDC in equity; spot withdrawable |
| `0x0803` | `withdrawable` | Releasable USDC on dex 0 |
| `0x0807` | `oraclePx` | Order pricing and position notional |
| `0x0808` | `spotPx` | Token-launch contracts only |
| `0x080a` | `perpAssetInfo` | Checking `szDecimals` and isolated-only flags when an asset is configured |
| `0x080C` | `tokenInfo` | Token-launch contracts only |
| `0x080e` | `bbo` | Token-launch contracts only |
| `0x080F` | `accountMarginSummary` | Equity and margin per dex |
| `0x0813` | `position2` | Position 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`

```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

| View | Returns |
|---|---|
| `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](https://docs.degenhive.ai/api.md).

## Related

- [Risk](https://docs.degenhive.ai/vaults/risk.md) Stops, latches and who may flatten.
- [Create a vault](https://docs.degenhive.ai/vaults/create.md) Set the DNA and risk params the engine enforces.
- [Deposits & withdrawals](https://docs.degenhive.ai/vaults/depositors.md) Daily rolls and settling queued redemptions.
- [REST API](https://docs.degenhive.ai/api.md) Read engine state, orders, fills and events.
