# DegenHive Docs (all pages)
> Build on DegenHive: run a fund on Hyperliquid, staff it with AI forecasters and paid data feeds, and integrate the Stock Token PropAMM pools on Robinhood Chain.
---
# Build on DegenHive
> Developer docs for DegenHive. Forecast for vaults, run a vault on Hyperliquid, sell data feeds, integrate the Robinhood Chain stock pools, and read the API.
Source: https://docs.degenhive.ai/
DegenHive is infrastructure for running a fund on chain. A vault on Hyperliquid holds the money. AI forecasters send predictions, a combiner turns them into target weights, and the vault's engine trades them on HyperCore. Data providers sell the feeds the models use. Each day the vault settles, takes its fees above a high-water mark, and pays everyone who helped. On Robinhood Chain, the same team runs Stock Token pools with a market maker built into the pool.
> [!IMPORTANT]
> The contracts behind these docs are not deployed yet and not externally audited. Addresses publish at launch on [Networks & status](https://docs.degenhive.ai/network.md). The product launches without a token. DGV comes later on Hyperliquid.
## Choose your path
- [Forecast for a vault](https://docs.degenhive.ai/forecasters.md) Bond 100 USDC, set a hot key, send predictions each round and get paid for accuracy and originality.
- [Run a vault](https://docs.degenhive.ai/vaults/create.md) Deploy a vault and its trading engine in one call, set your fees and risk limits, and trade HyperCore perps.
- [Sell a data feed](https://docs.degenhive.ai/data/publish-a-feed.md) List a feed, charge a daily USDC fee or a royalty on a vault's profit, and gate your API with one view call.
- [Integrate the Stock Token pools](https://docs.degenhive.ai/pools/swapping.md) Swap Stock Tokens against USDG on Robinhood Chain, or supply liquidity through a daily-settled book.
- [Read the data](https://docs.degenhive.ai/api.md) A public read-only REST API and a WebSocket feed for vaults, rounds, payouts and pools.
- [Revenue, NFTs & DGV](https://docs.degenhive.ai/revenue.md) Protocol fee splits, Stingvestors and Fangvestors burn-to-claim pots, and the token launch design.
## How it fits together
> **Figure: Where every fee goes.** Fees from both chains end in HyperRevenueRouter, which pays ops at once and holds the buyback and locker reserves until token launch.
>
> Two columns. Left, on HyperEVM (999): a HyperVault takes management and performance fees at roll() and sends them to HyperVaultFeeRouter. The fee router pays data royalties to DataProviderRegistry, the forecaster cut to HyperCrowdPay and the manager share to the manager, and sends the protocol take to HyperRevenueRouter. HyperVaultFactory sends its creation fee, and DataProviderRegistry sends its marketplace take, to HyperRevenueRouter. Right, on Robinhood Chain (4663): a BookVault takes its fees in USDG at roll(); nftBps of them go to the Stingvestors VestorPot and the rest go to the council's outbox Safe, which bridges them to HyperEVM by hand and calls notifyRevenue on HyperRevenueRouter. Bottom: HyperRevenueRouter splits every dollar into four lanes. Ops gets 31.67% and is paid out on arrival. The buyback reserve gets 31.67% and the locker reserve 31.66%; both are held until token launch. The NFT lane gets 5% and pays the Fangvestors VestorPot while that pot is live (otherwise the share goes to ops).
Every protocol dollar on Hyperliquid lands in one contract, the [revenue router](https://docs.degenhive.ai/revenue.md). It pays operations, sends a share to the Fangvestors NFT pot, and holds two reserves for the token launch: one for DGV buybacks and one for DGV lockers. Read [How DegenHive works](https://docs.degenhive.ai/how-it-works.md) for the full loop.
## Ways to integrate
| Method | Effort | Good for |
|---|---|---|
| [REST API](https://docs.degenhive.ai/api.md) and [WebSocket](https://docs.degenhive.ai/api/websocket.md) | Minutes | Dashboards, bots that read state, research |
| [Vault deposits & shares](https://docs.degenhive.ai/vaults/depositors.md) with viem or cast | An afternoon | Deposits, redemptions, wrappers around vault shares |
| [Forecaster quickstart](https://docs.degenhive.ai/forecasters.md) | An afternoon | Bonds, hot keys, eligibility checks, payouts |
| [Create and run a vault](https://docs.degenhive.ai/vaults/create.md) | A few days | Deploying a vault and running a trading keeper |
| [Stock Token swaps](https://docs.degenhive.ai/pools/swapping.md) and [liquidity books](https://docs.degenhive.ai/pools/liquidity.md) | A few days | Swaps, quotes, aggregators and LP products on Robinhood Chain |
## For AI agents
These docs are written to be read by agents as well as people.
- [/skill.md](https://docs.degenhive.ai/skill.md): one file with the ground rules, networks and the right page for each task.
- [/llms.txt](https://docs.degenhive.ai/llms.txt): every page with a one-line description. [/llms-full.txt](https://docs.degenhive.ai/llms-full.txt): every page in one file.
- Any page as Markdown: add `.md` to its URL, for example [/forecasters.md](https://docs.degenhive.ai/forecasters.md).
## Related
- [How DegenHive works](https://docs.degenhive.ai/how-it-works.md) The roles, the daily loop and where the money goes.
- [Glossary](https://docs.degenhive.ai/glossary.md) Every term these docs use, in one or two sentences.
---
# How DegenHive works
> Open fund infrastructure on Hyperliquid. Vaults trade HyperCore, AI forecasters and data feeds are paid from profit, and stock pools run on Robinhood Chain.
Source: https://docs.degenhive.ai/how-it-works
DegenHive is open fund infrastructure on Hyperliquid. Anyone can run a trading desk as an on-chain vault, staff it with AI forecasters and paid data feeds, and take deposits under limits the contract enforces. Agents forecast, contracts trade, and the market keeps score.
> [!IMPORTANT]
> The contracts are not deployed yet and not externally audited. Addresses publish at launch on [Networks & status](https://docs.degenhive.ai/network.md).
## The four roles
Four kinds of participant meet around each vault. None of them can move another's money.
| Role | Brings | Main calls | Gets |
|---|---|---|---|
| Depositor | USDC | `HyperVault.requestDeposit`, `deposit`, `requestRedeem`, `redeem` | Vault shares that rise and fall with the strategy |
| Vault manager | A strategy, run from its own servers | `HyperVaultFactory.deployStrategyVault`, `HyperPerpEngine.stepMarket` / `stepMarketTarget` | A management fee and a share of new profit |
| Forecaster | A model and a USDC bond | `HyperCrowdPay.stakeBond`, `setAgentKey` | Daily USDC from the profit of the vaults it steers |
| Data provider | A live feed | `DataProviderRegistry.registerProvider`, `claim` | Prepaid subscription fees and profit royalties |
A vault is a pair of contracts on HyperEVM (chain 999). `HyperVault` is an EIP-7540 async USDC vault that prices shares once a day. `HyperPerpEngine` trades the vault's own HyperCore account through CoreWriter, with no exchange account or API key.
Vault creation opens in stages: the council's Flagship vaults first, then invited managers, then anyone for a 10 USDC fee.
## The loop
> **Figure: The life of a forecast.** Forecasts stay off chain; HyperEVM sees the bond, the key, a committed round, the engine's trades and the scorer's paid chunks.
>
> Two lanes: off chain on top, HyperEVM (999) below. Step 1: the forecaster's owner wallet calls stakeBond on HyperCrowdPay with at least 100 USDC. Step 2: the owner calls setAgentKey(K), then the hot key K calls acceptAgentKey(owner). Step 3: K sends forecasts to the forecast intake service, which is off chain and opens with Season 0. The poster seals the round. Step 4: the poster calls postJobRound on HyperSignalBook with forecastsRoot and target weights. Step 5: HyperPerpEngine.stepMarket trades the vault on HyperCore toward the weights. After the horizon, the off-chain scorer scores the round. Step 6: the scorer calls commitDayChunks on HyperCrowdPay. Step 7: a 1-day challenge window, in which the council may veto. Step 8: distributeChunk pays the owner wallet 75% at once; the other 25% vests over 14 days as probation.
1. **Forecasters predict.** A forecaster bonds at least 100 USDC in `HyperCrowdPay` from a cold wallet and can bind a hot `agentKey`. Forecasts go to an off-chain intake service that opens with Season 0. Forecasts never go on-chain.
2. **Rounds are posted.** The forecasts are blended off-chain into one weighted median. The poster (or, on a manager's own job, the manager or its scorer) posts a round to `HyperSignalBook`: an opaque `forecastsRoot` plus sparse int16 target weights per market. A round expires after its TTL (at most 7 days).
3. **The engine trades.** A keeper calls `stepMarket(assetId)` on the vault's engine. The engine reads the latest fresh round, checks every limit in the vault's DNA, and places limit orders on HyperCore. Managers with a private model call `stepMarketTarget` with their own target instead.
4. **The vault rolls.** Once per UTC day, `roll()` prices shares, takes the management fee and the performance fee above the high-water mark, and settles queued deposits and redemptions.
5. **Fees flow down a waterfall.** `HyperVaultFeeRouter` pays data royalties, the forecaster cut and the manager. On a third-party vault the protocol takes its share first (20% by default). On a Flagship vault everything after royalties and forecasters goes to the protocol.
6. **Forecasters and data feeds are paid.** The forecaster cut funds that day's pot in `HyperCrowdPay`. The scorer commits payout chunks, a 1-day challenge window passes, and payouts are pushed: 75% at once and 25% vesting over 14 days as probation.
7. **Protocol revenue is split.** Every protocol dollar lands in `HyperRevenueRouter` and splits into four lanes.
> **Figure: Where every fee goes.** Fees from both chains end in HyperRevenueRouter, which pays ops at once and holds the buyback and locker reserves until token launch.
>
> Two columns. Left, on HyperEVM (999): a HyperVault takes management and performance fees at roll() and sends them to HyperVaultFeeRouter. The fee router pays data royalties to DataProviderRegistry, the forecaster cut to HyperCrowdPay and the manager share to the manager, and sends the protocol take to HyperRevenueRouter. HyperVaultFactory sends its creation fee, and DataProviderRegistry sends its marketplace take, to HyperRevenueRouter. Right, on Robinhood Chain (4663): a BookVault takes its fees in USDG at roll(); nftBps of them go to the Stingvestors VestorPot and the rest go to the council's outbox Safe, which bridges them to HyperEVM by hand and calls notifyRevenue on HyperRevenueRouter. Bottom: HyperRevenueRouter splits every dollar into four lanes. Ops gets 31.67% and is paid out on arrival. The buyback reserve gets 31.67% and the locker reserve 31.66%; both are held until token launch. The NFT lane gets 5% and pays the Fangvestors VestorPot while that pot is live (otherwise the share goes to ops).
## Where protocol revenue goes
| Lane | Share | Before the token | At token launch |
|---|---|---|---|
| Operations | 3,167 bps (31.67%) | Paid out | Paid out |
| Buyback reserve | 3,167 bps (31.67%) | Held in the router | Drips to the order-book buyback over 90 days |
| Locker reserve | 3,166 bps (31.66%) | Held in the router | Drips to DGV lockers over 30 days |
| NFT | 500 bps (5%) | Fangvestors pot, while it is live | Fangvestors pot, while it is live |
Revenue comes from vault fees, creation fees, the data marketplace take and the stock pools. Slashed forecaster bonds go to the buyback reserve and do not count as revenue.
## Stock pools on Robinhood Chain
The second product is a set of Stock Token pools on Robinhood Chain (4663), quoted against USDG. Each stock has one Uniswap v4 pool run by `MakerHook`, a PropAMM that prices around a posted fair tick. It charges more to trades that push the price away from fair value and less to trades that bring it back. `MakerPilot` sets fees and layout inside a guard policy.
Liquidity providers deposit into a `BookVault`, one per pool, which rolls daily and charges a performance fee only on gains over simply holding. `HiveFund` allocates protocol capital across the books.
There is no bridge contract. Book fees go to a council outbox Safe, which bridges them to HyperEVM by hand and calls `HyperRevenueRouter.notifyRevenue`.
## NFTs
Each chain has one collection of 5,100: Stingvestors on Robinhood Chain and Fangvestors on HyperEVM. A share of fees accrues to each NFT in a `VestorPot`. Stingvestors earn from `BookVault` fees in USDG and Fangvestors from the router's NFT lane in USDC. Burning an NFT pays out what it has accrued.
## The token comes later
DegenHive launches with no token. DGV launches later on Hyperliquid as a HIP-1 spot token with a linked ERC-20 on HyperEVM. Until then the buyback and locker reserves fill in USDC and nobody can withdraw them. At token launch the reserves start to drip, locks and emissions open, and forecaster bonds move to DGV over a 7 to 60 day window. DGV is not equity and never a share of a vault.
## Pick your role
- [Deposit into a vault](https://docs.degenhive.ai/vaults/depositors.md) Request a deposit, wait for the daily roll, and redeem in USDC.
- [Run a vault](https://docs.degenhive.ai/vaults.md) Choose a tier, set your DNA and fees, and trade HyperCore through the engine.
- [Forecast](https://docs.degenhive.ai/forecasters.md) Bond 100 USDC, bind an agent key, and earn daily from the vaults you steer.
- [Sell data](https://docs.degenhive.ai/data.md) List a feed, gate access with `verifyAccess`, and earn fees and royalties.
---
# Networks & status
> The two chains DegenHive runs on, their settlement assets and system addresses, and the deployment status of the main contracts.
Source: https://docs.degenhive.ai/network
DegenHive runs on two EVM chains. HyperEVM (chain 999) hosts the vaults, forecasting, the data marketplace, the revenue router and, at token launch, DGV. Robinhood Chain (chain 4663) hosts the PropAMM for Stock Tokens and the Stingvestors collection.
> [!IMPORTANT]
> Nothing on this page is deployed yet, and nothing is externally audited. Every address publishes here at launch.
## Chains
| | HyperEVM | Robinhood Chain |
|---|---|---|
| Chain id | `999` (testnet `998`) | `4663` (testnet `46630`) |
| Public RPC | `https://rpc.hyperliquid.xyz/evm` | `https://rpc.mainnet.chain.robinhood.com` |
| Explorer | [Purrsec](https://purrsec.com) | [Robinscan](https://robin.etherscan.io), [Blockscout](https://robinhoodchain.blockscout.com) |
| Gas token | HYPE (18 decimals) | ETH (18 decimals) |
| Settlement asset | USDC (6 decimals) | USDG (6 decimals) |
| What runs there | Vaults and engines, forecasting, data marketplace, revenue router, Fangvestors, DGV at token launch | MakerHook pools, MakerQuoter, BookVaults, HiveFund, MakerPilot, Stingvestors |
Robinhood Chain has no DGV, no bridge contract and no messaging layer. Stock-pool fees reach HyperEVM through a council outbox Safe that bridges USDG by hand and calls `HyperRevenueRouter.notifyRevenue`. See [Revenue router](https://docs.degenhive.ai/revenue.md).
## HyperCore system addresses
Vault engines talk to HyperCore directly from HyperEVM. Writes go through CoreWriter; reads go through the L1Read precompiles, called by `HyperL1ReadAdapter`. A failed read returns zeros.
| Interface | Address | Used for |
|---|---|---|
| CoreWriter | `0x3333333333333333333333333333333333333333` | Engine actions 1 (limit order), 11 (cancel by cloid), 13 (sendAsset). The buyback Comb also uses 6 (spotSend). |
| USDC system address | `0x2000000000000000000000000000000000000000` | Destination when the engine sends USDC from HyperCore back to HyperEVM |
| Spot balance | `0x0000000000000000000000000000000000000801` | Spot USDC held on HyperCore |
| Withdrawable | `0x0000000000000000000000000000000000000803` | Withdrawable perp margin |
| Oracle price | `0x0000000000000000000000000000000000000807` | Perp oracle prices |
| Spot price | `0x0000000000000000000000000000000000000808` | Spot prices (DGV reference at token launch) |
| Perp asset info | `0x000000000000000000000000000000000000080a` | Size decimals and asset metadata |
| Token info | `0x000000000000000000000000000000000000080C` | Spot token metadata and the linked EVM contract |
| Best bid and offer | `0x000000000000000000000000000000000000080e` | Top of book for order pricing |
| Margin summary | `0x000000000000000000000000000000000000080F` | Account value per perp dex, counted in NAV |
| Position | `0x0000000000000000000000000000000000000813` | Positions on native perps and HIP-3 dexes |
The engine never approves a HyperCore API wallet, so no off-chain key can trade a vault's Core account. USDC moves from HyperEVM to HyperCore through Circle's CoreDepositWallet. Its address is in the deployments response below.
## Deployment status
### HyperEVM (999)
| Contract | Role | Status |
|---|---|---|
| `HyperVaultFactory` | Deploys `HyperVault` and `HyperPerpEngine` pairs | Publishes at launch |
| `HyperVault` + `HyperPerpEngine` | ERC-7540 async USDC vault and HyperCore trading engine | Deployed per vault by the factory |
| `HyperVaultFeeRouter` | Splits vault management and performance fees across protocol, data providers, forecasters and managers | Publishes at launch |
| `HyperRevenueRouter` | Splits protocol revenue into ops, buyback reserve, locker reserve and Fangvestors pot | Publishes at launch |
| `HyperSignalBook` | Forecast jobs, listed markets and posted rounds | Publishes at launch |
| `HyperCrowdPay` | Forecaster USDC bonds, daily payout pots, probation and slashing | Publishes at launch |
| `DataProviderRegistry` | Paid data feeds, subscriptions, royalties and `verifyAccess` | Publishes at launch |
| `Fangvestors`, `VestorPot`, `VestorCurveMinter` | HyperEVM NFT collection, burn-to-claim USDC pot and curve sale | Publishes at launch |
| `DGV`, `DGVClaim`, `DGVSale`, `DGVEmissions` | Token, Merkle claims, fixed-price sale and revenue-paced emissions | At token launch |
| `OrderBookComb` | Buys DGV on the HyperCore order book with the buyback reserve and burns it | At token launch |
| `HyperBookRewards`, `HyperDGVLocks`, `HyperLockerPot` | Depositor DGV rewards, DGV locks, fee rebates and USDC lock yield | At token launch |
### Robinhood Chain (4663)
| Contract | Role | Status |
|---|---|---|
| `MakerHook` | Uniswap v4 PropAMM hook for Stock Token/USDG pools | Publishes at launch |
| `MakerQuoter` | Read-only (`eth_call`) swap quoter for `MakerHook` pools | Publishes at launch |
| `MakerPilot` | On-chain fee and layout engine for Stock Token pools | Publishes at launch |
| `BookVault` | Daily-settled LP book, one per Stock Token pool | Publishes at launch |
| `HiveFund` | Protocol liquidity allocator across books | Publishes at launch |
| `Stingvestors`, `VestorPot`, `VestorCurveMinter` | Robinhood Chain NFT collection (upgraded in place), burn-to-claim USDG pot and curve sale | Publishes at launch |
The contract source stays private until the external audits finish. Every upgrade is timelocked and public before it lands. On HyperEVM an upgrade waits at least 48 hours, 72 hours for vaults and engines and 7 days for lock contracts. On Robinhood Chain every upgrade waits at least 48 hours once the deploy bootstrap ends.
## Retired DGV on Robinhood Chain
This DGV contract on Robinhood Chain is retired. Do not buy it:
`Retired DGV (Robinhood Chain 4663)`
```text
0x420764EDba7c6D99FB5E14aCE9bdc1DCF4a26690
```
It is not upgraded and does not move to HyperEVM. At token launch, holders at the snapshot block claim the same amount of new DGV 1:1 through `DGVClaim` on HyperEVM. Each wallet can take its DGV liquid or lock it in the same step. See [DGV launch](https://docs.degenhive.ai/token.md).
> [!WARNING]
> Any other address offered as "DGV" before the token launch is not DegenHive's. Check this page before you approve a token.
## Read addresses programmatically
Once contracts deploy, the API serves every address from its deployment manifest. Contracts not yet deployed return `"address": null` and `"deployed": false`.
`GET https://api.degenhive.ai/v1/protocol/deployments`
**curl**
```bash
curl -s "https://api.degenhive.ai/v1/protocol/deployments?chain=hyperliquid"
```
**TypeScript**
```ts
const res = await fetch("https://api.degenhive.ai/v1/protocol/deployments?chain=hyperliquid");
const { items } = await res.json();
const book = Object.fromEntries(items[0].contracts.map((c) => [c.name, c.address]));
```
**Python**
```python
import requests
r = requests.get("https://api.degenhive.ai/v1/protocol/deployments", params={"chain": "hyperliquid"})
contracts = {c["name"]: c["address"] for c in r.json()["items"][0]["contracts"]}
```
`Response (before launch, trimmed)`
```json
{
"items": [
{
"chain": "hyperliquid",
"chain_id": 999,
"tokens": { "usdg": null, "usdc": "0x…", "weth": null, "dgv": null },
"pool_manager": null,
"position_manager": null,
"state_view": null,
"hyper_core": {
"core_writer": "0x3333333333333333333333333333333333333333",
"core_deposit_wallet": "0x…",
"usdc_system_address": "0x2000000000000000000000000000000000000000",
"precompiles": { "spotBalance": "0x…0801", "oraclePx": "0x…0807" }
},
"contracts": [
{ "name": "HyperVaultFactory", "address": null, "start_block": 0, "deployed": false },
{ "name": "HyperCrowdPay", "address": null, "start_block": 0, "deployed": false }
]
}
]
}
```
Omit `chain` to get both chains. Vaults, engines and books are created at runtime and are not in the manifest: list them with `GET /v1/protocol/contracts?chain=hyperliquid&role=HyperVault`.
## Related
- [How DegenHive works](https://docs.degenhive.ai/how-it-works.md) The four roles and the daily loop, end to end.
- [REST API](https://docs.degenhive.ai/api.md) Every read route, its parameters and its responses.
- [Vault risk rails](https://docs.degenhive.ai/vaults/risk.md) Loss stops, drawdown latches and withdrawal safeguards.
- [Stock Token pools](https://docs.degenhive.ai/pools.md) PropAMM pricing, liquidity books and fee rules.
---
# Glossary
> Plain definitions of the terms used across the DegenHive docs, each linked to the page that explains it.
Source: https://docs.degenhive.ai/glossary
Short definitions of the terms these docs use. Each entry links to the page with the full mechanism.
## A
**Accuracy**
The first part of a forecast's score: how much closer the forecast landed to the outcome than the market's own baseline, divided by a scale and clipped. See [Scoring](https://docs.degenhive.ai/forecasters/scoring.md).
**agentKey**
A hot key a forecaster binds to its bonded cold wallet with `setAgentKey` and `acceptAgentKey` in `HyperCrowdPay`. It is only an identity alias: it holds no bond, moves no funds and cannot redirect payouts. See [Bonds & pay](https://docs.degenhive.ai/forecasters/bonds-and-pay.md).
**Allocator**
A special depositor that places protocol capital. On a `HyperVault` the protocol allocator skips the minimum deposit, the caps and the management fee. On Robinhood Chain, `HiveFund` is the allocator of every `BookVault`. See [Provide liquidity](https://docs.degenhive.ai/pools/liquidity.md).
## B
**BookTerms**
The fee and roll settings shared across `BookVault` books: fees, slippage, settle delay, fee recipient, NFT pot and keeper. Caps are 300 bps management, 5,000 bps performance, 100 bps withdrawal and 2,000 bps to the NFT pot. See [Provide liquidity](https://docs.degenhive.ai/pools/liquidity.md).
**BookVault**
The liquidity book of one stock pool on Robinhood Chain. Deposits and withdrawals are in kind and settle at a daily roll. See [Provide liquidity](https://docs.degenhive.ai/pools/liquidity.md).
**Bond**
The USDC a forecaster stakes in `HyperCrowdPay` to take part, at least 100 USDC. It takes 14 days to unstake and stays slashable while it waits. At token launch new bonds move to DGV. See [Bonds & pay](https://docs.degenhive.ai/forecasters/bonds-and-pay.md).
**Buyback reserve**
The 3,167 bps (31.67%) revenue lane held in `HyperRevenueRouter` until token launch. It then drips over 90 days into automated DGV buybacks on HyperCore, burning every DGV purchased. Slashed USDC also lands here. See [Revenue router](https://docs.degenhive.ai/revenue.md).
## C
**CoreWriter**
The HyperEVM system contract at `0x3333333333333333333333333333333333333333` that sends actions to HyperCore. Vault engines use it to place orders, cancel them and move USDC. See [Trading engine](https://docs.degenhive.ai/vaults/trading.md).
**CreationMode**
The `HyperVaultConfig` switch that decides who can create a vault: `OFF` (the default, council only), `WHITELISTED` or `PERMISSIONLESS`. Flagship vaults are council-only in every mode. See [Create a vault](https://docs.degenhive.ai/vaults/create.md).
## D
**Daily loss stop**
A DNA limit between 50 and 1,000 bps. Once a vault loses that much in a UTC day, market steps revert until the next UTC day and anyone may flatten. See [Risk rails](https://docs.degenhive.ai/vaults/risk.md).
**Data key**
An address a vault manager sets with `setVaultDataKey`. A data provider's gateway accepts it, the keeper or the manager as the vault's signer in `verifyAccess`. See [Gate access to a feed](https://docs.degenhive.ai/data/access.md).
**DGV**
The DegenHive token. It launches later on Hyperliquid as a HIP-1 spot token linked to an ERC-20 on HyperEVM. DGV is not equity and never a share of a vault. See [DGV launch](https://docs.degenhive.ai/token.md).
**DNA**
A vault's fixed risk limits, set at creation: market tier, gross and net exposure caps, daily loss stop, drawdown stop and vault tier. Nothing can change them except an engine upgrade. See [Create a vault](https://docs.degenhive.ai/vaults/create.md).
**Drawdown latch**
A stop that trips when a vault's share price falls past its DNA drawdown limit from the high-water mark. It stays set until the council calls `clearDrawdownStop`. See [Risk rails](https://docs.degenhive.ai/vaults/risk.md).
**Drip**
How a revenue reserve pays out after token launch: at a constant rate up to an end date (`unlockEnd`), recalculated when new revenue arrives. The horizons are 90 days for buybacks and 30 days for lockers. See [Revenue router](https://docs.degenhive.ai/revenue.md).
## E
**Epoch**
A vault's batch of deposit and redemption requests for one UTC day. Requests made during the day settle at the next roll. See [Deposits & withdrawals](https://docs.degenhive.ai/vaults/depositors.md).
## F
**Fair tick**
The fair price of a stock pool, posted to `MakerHook` with `updateFairTick`. It stays fresh for at most an hour. Without a fresh tick the fair-value shield and router discounts switch off. See [PropAMM overview](https://docs.degenhive.ai/pools.md).
**Fangvestors**
The NFT collection on HyperEVM, capped at 5,100. Each NFT accrues USDC from the revenue router's NFT lane and pays it out when burned. See [Stingvestors & Fangvestors](https://docs.degenhive.ai/nfts.md).
**Flagship**
A vault run by DegenHive and created by the council. The Flagship runs 1% a year and 25% of new profit, and its forecasts come from job 1. See [Vaults overview](https://docs.degenhive.ai/vaults.md).
**Flatten**
`flatten(uint32[])` on the engine closes the listed positions with reduce-only orders. Anyone may call it once a stop has tripped, the vault is winding down or the manager has been idle too long. See [Risk rails](https://docs.degenhive.ai/vaults/risk.md).
**forecastsRoot**
The `bytes32` commitment a round carries to the forecasts behind it. The contract stores it and never reads the forecasts themselves. See [Jobs & rounds](https://docs.degenhive.ai/forecasters/jobs-and-rounds.md).
## G
**Gain over holding**
How a `BookVault` measures performance: its value against simply holding the deposited stock and USDG. The performance fee applies only above that line. See [Provide liquidity](https://docs.degenhive.ai/pools/liquidity.md).
**Guardian**
A cancel-only safety role. It can pause entry on Robinhood Chain, revoke pending changes and pause revenue lanes, but it can never move funds or weaken limits. See [Risk rails](https://docs.degenhive.ai/vaults/risk.md).
## H
**HiveFund**
The protocol allocator on Robinhood Chain. Once a day `allocate()` spreads protocol USDG across the books by council target weights. See [Provide liquidity](https://docs.degenhive.ai/pools/liquidity.md).
**HIP-1**
Hyperliquid's native spot token standard on HyperCore. DGV launches as a HIP-1 token with a linked ERC-20 on HyperEVM. See [DGV launch](https://docs.degenhive.ai/token.md).
**HWM (high-water mark)**
A vault's highest share price after fees. The performance fee is charged only on gains above it, and it is never reset. See [Fees & high-water mark](https://docs.degenhive.ai/vaults/fees.md).
## J
**Job (Mode 1 / Mode 2)**
A forecasting task in `HyperSignalBook` tied to a vault, with its horizon, cadence and entry filter. Mode 1 jobs are verified: the council creates them and the protocol poster and scorer run them. Mode 2 jobs belong to a vault manager, who posts rounds and pays forecasters in USDC. See [Jobs & rounds](https://docs.degenhive.ai/forecasters/jobs-and-rounds.md).
## K
**Keeper**
An address that runs routine calls: rolling vaults, stepping markets, moving USDC between HyperEVM and HyperCore. Rolls open to anyone after a grace period, and many upkeep calls are permissionless. See [Trading engine](https://docs.degenhive.ai/vaults/trading.md).
## L
**L1Read**
The HyperEVM precompiles at `0x0801` to `0x0813` that read HyperCore state: balances, prices, margin and positions. Engines call them through `HyperL1ReadAdapter`. See [Networks & status](https://docs.degenhive.ai/network.md).
**Lock power**
The weight of a DGV lock: 25% plus 75% scaled by the weeks left out of 52. A permanent lock counts 100%; an expired lock counts nothing. Locks open at token launch. See [DGV launch](https://docs.degenhive.ai/token.md).
**Locker reserve**
The 3,166 bps (31.66%) revenue lane held in `HyperRevenueRouter` until token launch. It then drips over 30 days to the locker pot, which pays DGV lockers in USDC. See [Revenue router](https://docs.degenhive.ai/revenue.md).
## M
**MakerHook**
The Uniswap v4 hook behind every stock/USDG pool on Robinhood Chain. It holds all the liquidity, sets a dynamic fee on each swap and offers its own `swap` function. See [PropAMM overview](https://docs.degenhive.ai/pools.md).
**MakerPilot**
The on-chain engine for the stock pools. Anyone can call `step(poolId)` to update fees and liquidity layout inside the guard policy. See [PropAMM overview](https://docs.degenhive.ai/pools.md).
**MMC (meta-model contribution)**
The second part of a forecast's score: how much the forecast adds beyond the weighted median of all forecasts. It counts four times as much as accuracy, so copying the consensus scores zero. See [Scoring](https://docs.degenhive.ai/forecasters/scoring.md).
## O
**OrderBookComb**
The automated buyback mechanism that starts at token launch. It spends the 90-day buyback reserve drip on the HyperCore DGV/USDC book and burns every DGV it buys. See [DGV launch](https://docs.degenhive.ai/token.md).
**Outbox Safe**
The council Safe on Robinhood Chain that receives stock-pool fees. It bridges them to HyperEVM by hand and calls `HyperRevenueRouter.notifyRevenue` as an allowlisted revenue source. See [Revenue router](https://docs.degenhive.ai/revenue.md).
## P
**Poster**
The address that posts Mode 1 rounds to `HyperSignalBook`. Mode 2 rounds come from the vault manager or its scorer. See [Jobs & rounds](https://docs.degenhive.ai/forecasters/jobs-and-rounds.md).
**Probation**
The 25% of every forecaster payout that vests over 14 days. Slashes take unvested probation pay first, before the bond. See [Bonds & pay](https://docs.degenhive.ai/forecasters/bonds-and-pay.md).
**PropAMM**
A pool that sets its own quotes around a fair price instead of waiting passively. It charges more to trades that push the price away from fair value and less to trades that bring it back. See [PropAMM overview](https://docs.degenhive.ai/pools.md).
## R
**Revenue lanes**
The four ways `HyperRevenueRouter` splits each protocol dollar: operations 3,167 bps, buyback reserve 3,167 bps, locker reserve 3,166 bps and NFT 500 bps. See [Revenue router](https://docs.degenhive.ai/revenue.md).
**Roll**
The once-a-day settlement of a vault or book. It prices shares, takes fees and settles queued deposits and redemptions. The keeper or manager can roll a vault from 00:00 UTC and anyone from 02:00. See [Deposits & withdrawals](https://docs.degenhive.ai/vaults/depositors.md).
**Round**
One posting of a job's output: a `forecastsRoot`, sparse target weights per market, a horizon and a TTL of at most 7 days. Engines trade only on fresh rounds. See [Jobs & rounds](https://docs.degenhive.ai/forecasters/jobs-and-rounds.md).
**Royalty feed**
A data subscription paid as a share of a vault's performance fee: at most 500 bps per feed, 5,000 bps combined and 20 feeds per vault. See [Data marketplace](https://docs.degenhive.ai/data.md).
## S
**Scorer**
The address that commits a job's daily payout chunks to `HyperCrowdPay` and distributes them after the challenge window. The protocol scorer runs Mode 1 jobs; a Mode 2 job may set its own. See [Scoring](https://docs.degenhive.ai/forecasters/scoring.md).
**Season 0**
Everything before the token. There are no points or farming: depositors' and forecasters' on-chain records count toward the DGV claim at token launch. See [DGV launch](https://docs.degenhive.ai/token.md).
**Slashing**
Taking part of a forecaster's probation pay or bond for spam or for manipulating scores. Routine slashes are capped at 5% of the bond a day and council slashes at 25%. Slashed USDC goes to the buyback reserve. See [Slashing](https://docs.degenhive.ai/forecasters/slashing.md).
**Stingvestors**
The NFT collection on Robinhood Chain, capped at 5,100. Each NFT accrues USDG from stock-pool fees and pays it out when burned. See [Stingvestors & Fangvestors](https://docs.degenhive.ai/nfts.md).
## T
**Target weight**
A signed int16 position size in basis points of vault equity that a round sets for one market. Positive is long, negative is short, and it reads as zero once the round expires. See [Jobs & rounds](https://docs.degenhive.ai/forecasters/jobs-and-rounds.md).
**Tier**
A vault's type, fixed in its DNA: `FLAGSHIP`, `INSTITUTIONAL` or `COMMUNITY_ARENA`. Each tier has hard ceilings on exposure and drawdown. See [Vaults overview](https://docs.degenhive.ai/vaults.md).
## V
**VestorPot**
The pot behind each NFT collection. Fees arrive by plain transfer, each NFT accrues an equal share, and burning the NFT pays its share out. See [Stingvestors & Fangvestors](https://docs.degenhive.ai/nfts.md).
## W
**Weighted median**
How a round blends forecasts into one answer. Each forecaster's weight is the square root of its bond times its track record, and no one carries more than 20% of a round. See [Scoring](https://docs.degenhive.ai/forecasters/scoring.md).
**Wind-down**
The irreversible close of a vault with `initiateWindDown`. New deposits stop, pending deposits are refunded at the next roll and the engine can only reduce positions. See [Risk rails](https://docs.degenhive.ai/vaults/risk.md).
## Related
- [How DegenHive works](https://docs.degenhive.ai/how-it-works.md) The four roles and the daily loop on one page.
- [REST API](https://docs.degenhive.ai/api.md) Public read-only endpoints for vaults, rounds, payouts and pools.
- [Networks & status](https://docs.degenhive.ai/network.md) Chains, system addresses and deployment status.
---
# Forecaster quickstart
> Bond 100 USDC on HyperEVM, bind a hot key to your cold wallet, check a job's entry rules, and follow your record and pay through the API.
Source: https://docs.degenhive.ai/forecasters
A forecaster is any address with a USDC bond in `HyperCrowdPay`. It predicts markets for a forecast job, the protocol scores every prediction off-chain, and each UTC day the best and most original forecasters share that job's pot. There is no registration call: the bond is your identity, and a hot key signs on its behalf.
Forecasts themselves never go on-chain. Each round, the poster pins one opaque commitment (`forecastsRoot`) and the combined target weights in `HyperSignalBook`. Your edge stays private.
> [!IMPORTANT]
> The forecasting contracts are not deployed yet and not externally audited. Addresses publish at launch on [Networks & status](https://docs.degenhive.ai/network.md). The forecast intake service and the forecasting MCP open with Season 0. Until then you can prepare your keys, your model and your scripts with the calls below.
**You need:**
- A cold wallet for the bond: a hardware wallet or a Safe on HyperEVM (chain `999`).
- A fresh hot key that has never held a bond.
- At least 100 USDC and a little HYPE for gas, on HyperEVM.
- Node 18+ with [viem](https://viem.sh), or Foundry's `cast`.
The snippets use placeholders: `CROWD_PAY`, `SIGNAL_BOOK` and `USDC` for contract addresses, `COLD` and `HOT` for your two addresses.
## Step 1: Get USDC and HYPE on HyperEVM
Bonds are USDC, which has 6 decimals: 100 USDC is `100000000`. Move USDC to HyperEVM from your HyperCore spot balance in the Hyperliquid app, or bridge it from another chain with Circle's CCTP. Gas on HyperEVM is paid in HYPE. Both wallets need a little: the hot key sends one transaction in step 3.
**viem**
```ts
import { createPublicClient, createWalletClient, defineChain, http, parseAbi } from "viem";
import { privateKeyToAccount } from "viem/accounts";
export const hyperevm = defineChain({
id: 999,
name: "HyperEVM",
nativeCurrency: { name: "HYPE", symbol: "HYPE", decimals: 18 },
rpcUrls: { default: { http: ["https://rpc.hyperliquid.xyz/evm"] } },
});
export const pub = createPublicClient({ chain: hyperevm, transport: http() });
export const cold = createWalletClient({
account: privateKeyToAccount(process.env.COLD_KEY as `0x${string}`), // or a hardware-wallet account
chain: hyperevm,
transport: http(),
});
const erc20 = parseAbi(["function balanceOf(address) view returns (uint256)"]);
const usdc = await pub.readContract({
address: USDC, abi: erc20, functionName: "balanceOf", args: [cold.account.address],
});
const hype = await pub.getBalance({ address: cold.account.address });
console.log({ usdc: Number(usdc) / 1e6, hype: Number(hype) / 1e18 });
```
**cast**
```bash
export ETH_RPC_URL=https://rpc.hyperliquid.xyz/evm
cast call $USDC "balanceOf(address)(uint256)" $COLD # 6 decimals
cast balance $COLD --ether # HYPE for gas
```
## Step 2: Stake a bond
Approve `HyperCrowdPay` for the amount, then call `stakeBond` from the cold wallet. The global minimum is `config().minBondUsdc`, 100 USDC by default. A job can ask for more through its entry filter (step 4).
A bond below the minimum is accepted but does not count. Your bond age starts when the active bond first reaches the global minimum (event `BondAgeSet`), and some jobs require a minimum bond age. Bonding more later never resets it.
**viem**
```ts
const crowdPayAbi = parseAbi([
"function stakeBond(uint256 amount)",
"function config() view returns ((address scorer, address signalBook, address revenueRouter, address dgv, address dgvEmissions, address dgvPriceSource, uint32 challengeSecs, uint32 probationSecs, uint16 probationBps, uint8 bondAsset, uint64 usdcBondsCountUntil, uint32 priceBandLowBps, uint32 priceBandHighBps, uint128 minBondUsdc, uint128 minBondDgvFloor))",
]);
const cfg = await pub.readContract({ address: CROWD_PAY, abi: crowdPayAbi, functionName: "config" });
const amount = 250_000_000n; // 250 USDC
if (amount < cfg.minBondUsdc) throw new Error("bond would not count");
await cold.writeContract({
address: USDC,
abi: parseAbi(["function approve(address, uint256) returns (bool)"]),
functionName: "approve",
args: [CROWD_PAY, amount],
});
await cold.writeContract({ address: CROWD_PAY, abi: crowdPayAbi, functionName: "stakeBond", args: [amount] });
```
**cast**
```bash
# config() ends with (..., minBondUsdc, minBondDgvFloor)
cast call $CROWD_PAY "config()((address,address,address,address,address,address,uint32,uint32,uint16,uint8,uint64,uint32,uint32,uint128,uint128))"
cast send $USDC "approve(address,uint256)" $CROWD_PAY 250000000 --private-key $COLD_KEY
cast send $CROWD_PAY "stakeBond(uint256)" 250000000 --private-key $COLD_KEY
```
Reverts with `ZeroAmount` for a zero amount, `TransferFailed` if the allowance or balance is short, and `BondAssetClosed` once bonds have moved to DGV at token launch (see [Bonds & pay](https://docs.degenhive.ai/forecasters/bonds-and-pay.md)).
## Step 3: Bind a hot key
Your agent signs with a hot key. The cold wallet proposes it with `setAgentKey`, and the hot key confirms with `acceptAgentKey`. The key is an identity alias and nothing more: it cannot unstake, withdraw, or redirect pay. Payouts always go to the bond owner.
> **Figure: Agent keys and data keys.** Both keys are identity aliases: they tell a reader which owner or vault stands behind a request, and neither can move funds.
>
> Two flows side by side. Forecaster key, left: the owner wallet holds the bond and gets paid; the hot key K holds no bond and no funds. The owner calls setAgentKey(K) on HyperCrowdPay, then K calls acceptAgentKey(owner). HyperCrowdPay stores K as an alias of the owner. The forecast intake reads isForecasterEligible(job, K), which resolves to the owner and its bond. Data key, right: the vault manager, who pays for the feed, calls setVaultDataKey(vault, key) on DataProviderRegistry, which stores the key. The agent holding the data key sends a signed request to the provider's API, which checks the signature off chain and then calls verifyAccess(vault, providerId, signer) on DataProviderRegistry; it returns (active, paidUntil). The data key, the vault's keeper and its manager all pass. A note: neither key can move funds.
**viem**
```ts
import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";
const hotPk = generatePrivateKey(); // store it where your agent runs, never next to the cold key
const hot = createWalletClient({ account: privateKeyToAccount(hotPk), chain: hyperevm, transport: http() });
const keyAbi = parseAbi([
"function setAgentKey(address agentKey)",
"function acceptAgentKey(address owner)",
]);
// 1. Cold wallet proposes the key.
await cold.writeContract({ address: CROWD_PAY, abi: keyAbi, functionName: "setAgentKey", args: [hot.account.address] });
// 2. The hot key accepts (it needs a little HYPE for this one transaction).
await hot.writeContract({ address: CROWD_PAY, abi: keyAbi, functionName: "acceptAgentKey", args: [cold.account.address] });
```
**cast**
```bash
cast wallet new # save the key as HOT_KEY, its address as HOT
cast send $CROWD_PAY "setAgentKey(address)" $HOT --private-key $COLD_KEY
cast send $CROWD_PAY "acceptAgentKey(address)" $COLD --private-key $HOT_KEY
```
`setAgentKey` reverts with `InvalidPolicy` if you pass your own address. `acceptAgentKey` reverts with `Unauthorized` if this owner did not propose the key, `InvalidPolicy` if the key holds any bond, and `AgentKeyTaken(existingOwner)` if another owner already uses it. To rotate, repeat both calls with a different key; the old one unbinds. To revoke, call `setAgentKey(address(0))` from the cold wallet.
> [!WARNING]
> If the hot key ever stakes a bond of its own, the binding drops. Keep the hot key free of bonds and the cold key offline.
## Step 4: Pick a job and check eligibility
A job is a stream of rounds that one vault (or the Flagship) trades. Job `1` is the Flagship job. Each job has an entry filter: a higher minimum bond, a maximum recent slash rate, a minimum count of paid days, a minimum bond age, or a private whitelist. Read the filter, then ask `isForecasterEligible` with your hot key: it resolves the key to your cold wallet and checks every rule.
**viem**
```ts
const bookAbi = parseAbi([
"function jobFilter(uint64 jobId) view returns ((uint128 minBondUsdc, uint16 maxRecentSlashBps, uint32 minPaidDays, uint32 minBondAgeSecs, bool whitelistOnly))",
]);
const eligAbi = parseAbi([
"function requiredBond(uint256 requiredUsd) view returns (uint256)",
"function isForecasterEligible(uint64 jobId, address signer) view returns (bool eligible, uint8 failReason, address owner, uint256 activeBond, uint32 curSlashBps)",
]);
const jobId = 1n;
const filter = await pub.readContract({ address: SIGNAL_BOOK, abi: bookAbi, functionName: "jobFilter", args: [jobId] });
const usd = filter.minBondUsdc > cfg.minBondUsdc ? filter.minBondUsdc : cfg.minBondUsdc;
const need = await pub.readContract({ address: CROWD_PAY, abi: eligAbi, functionName: "requiredBond", args: [usd] });
const [eligible, failReason, owner, activeBond] = await pub.readContract({
address: CROWD_PAY, abi: eligAbi, functionName: "isForecasterEligible", args: [jobId, hot.account.address],
});
console.log({ eligible, failReason, owner, activeBond, need });
```
**cast**
```bash
cast call $SIGNAL_BOOK "jobFilter(uint64)((uint128,uint16,uint32,uint32,bool))" 1
cast call $CROWD_PAY "isForecasterEligible(uint64,address)(bool,uint8,address,uint256,uint32)" 1 $HOT
```
| `failReason` | Meaning | Fix |
|---|---|---|
| `0` | Eligible | |
| `1` | Counted bond below `max(config().minBondUsdc, filter.minBondUsdc)` | Stake more, or cancel an unstake |
| `2` | Recent slash rate above `maxRecentSlashBps` | Wait: the rate decays with a 30-day time constant |
| `3` | Fewer paid days than `minPaidDays` | Earn paid days on the Flagship or other verified jobs first |
| `4` | Bond younger than `minBondAgeSecs` | Wait; bond age counts from when you first met the global minimum |
| `5` | Job is `whitelistOnly` and you are not listed | Ask the job's manager |
| `6` | Job unknown or inactive | Pick an active job |
List open jobs with `GET /v1/forecasting/jobs?active=true`. [Jobs & rounds](https://docs.degenhive.ai/forecasters/jobs-and-rounds.md) explains verified and manager jobs, `specUri`, and the markets each job may trade.
## Step 5: Send forecasts
> [!NOTE]
> The forecast intake service opens with Season 0. Its endpoint, message format and the forecasting MCP publish then, on this page and in [Agents, MCP & llms.txt](https://docs.degenhive.ai/agents.md).
What is fixed already: your hot key signs each submission, and the intake checks `isForecasterEligible(jobId, hotKey)` before it accepts one. Forecasts stay off-chain. When a round closes, the poster aggregates the forecasts and calls `postJobRound` with the round's `forecastsRoot` and the combined target weights. You can watch rounds land on-chain today, and build and backtest your model with [Writing a model](https://docs.degenhive.ai/forecasters/writing-a-model.md).
**cast**
```bash
# Latest round of the Flagship job:
# (roundId, postedAt, expiresAt, horizonSecs, regimeStormBps, forecasterCount, forecastsRoot)
cast call $SIGNAL_BOOK "jobLatestRound(uint64)(uint64,uint64,uint64,uint32,uint16,uint32,bytes32)" 1
```
**REST**
```bash
curl -s "https://api.degenhive.ai/v1/forecasting/jobs/1/rounds?limit=5" | jq
```
## Step 6: Watch your record and pay
Scoring runs off-chain in the protocol scorer. Pay lands on-chain once a day per job: after the day ends, the scorer commits the day's payout lists, a challenge window passes, and `distributeChunk` pushes USDC to your cold wallet. 75% arrives at once and 25% vests over 14 days as probation. [Scoring](https://docs.degenhive.ai/forecasters/scoring.md) and [Bonds & pay](https://docs.degenhive.ai/forecasters/bonds-and-pay.md) cover the details.
The read-only REST API indexes all of it. No key is needed; the limit is 300 requests per 60 seconds per IP. Query by your cold wallet, since payouts name the bond owner.
**REST**
```bash
API=https://api.degenhive.ai/v1
curl -s "$API/forecasting/forecasters/$COLD" | jq # bonds, probation, agent keys, payouts, slashes
curl -s "$API/forecasting/payouts?forecaster=$COLD&job_id=1" | jq
curl -s "$API/forecasting/forecasters/$COLD/events" | jq # bond, probation and agent key activity
curl -s "$API/forecasting/leaderboard?job_id=1&days=30" | jq
```
**WebSocket**
```ts
const ws = new WebSocket("wss://api.degenhive.ai/v1/ws");
ws.onopen = () =>
ws.send(JSON.stringify({ op: "subscribe", channels: ["forecasting:job:1", `account:${COLD.toLowerCase()}`] }));
ws.onmessage = (m) => console.log(JSON.parse(m.data));
```
The API returns empty lists until the contracts deploy. Amounts are integer strings in base units (USDC has 6 decimals). See [REST API](https://docs.degenhive.ai/api.md) and [WebSocket](https://docs.degenhive.ai/api/websocket.md) for paging and message shapes.
## Step 7: Where to go next
- [Jobs & rounds](https://docs.degenhive.ai/forecasters/jobs-and-rounds.md) How jobs are made, what a round carries, and how engines trade it.
- [Scoring](https://docs.degenhive.ai/forecasters/scoring.md) Accuracy plus four times originality, the weighted median, and the 20% weight cap.
- [Bonds & pay](https://docs.degenhive.ai/forecasters/bonds-and-pay.md) Daily pots, the challenge window, probation and unstaking.
- [Writing a model](https://docs.degenhive.ai/forecasters/writing-a-model.md) Turn data into a sparse weight vector that scores well.
---
# Jobs & rounds
> How forecast jobs are created and gated, which markets they may trade, what a round carries on-chain, and how a vault's engine reads it.
Source: https://docs.degenhive.ai/forecasters/jobs-and-rounds
A **forecast job** is a stream of rounds that one vault trades. A **round** is an on-chain attestation in `HyperSignalBook`: a sealed commitment to the round's forecasts (`forecastsRoot`) plus sparse target weights, in basis points, for the markets the job covers. Individual forecasts and forecaster identities never go on-chain.
## Two kinds of job
| | Verified job (Mode 1) | Manager job (Mode 2) |
|---|---|---|
| Created by | The council | The vault's live manager, or the council |
| Rounds posted by | The protocol poster (or the council) | The manager, its custom scorer, or the council |
| Scored and paid by | The protocol scorer | The manager or its custom scorer |
| Pots | USDC; DGV too at token launch | USDC only |
| Slashing | Protocol scorer and council | Manager can only propose; the protocol executes |
| Paid days counted | Yes (`paidDaysCount`) | No |
**Job 1 is the Flagship job.** It exists from deployment, has no vault, and runs a 24-hour horizon on a 4-hour cadence. Every other job is bound to one vault. A vault's manager is resolved live: the vault's `strategyManager()`, else its `admin()`. If a vault changes manager, a custom scorer set by the previous manager stops counting.
## Create a job
```solidity
function createJob(
address vault,
bool verified,
address customScorer,
uint32 horizonSecs,
uint32 cadenceSecs,
string calldata specUri,
JobEntryFilter calldata filter
) external returns (uint64 jobId);
struct JobEntryFilter {
uint128 minBondUsdc; // raises the global minimum; 0 = global only
uint16 maxRecentSlashBps; // 0 = no limit
uint32 minPaidDays; // paid days on verified jobs
uint32 minBondAgeSecs; // since the bond first met the global minimum
bool whitelistOnly; // only addresses set with setJobWhitelist
}
```
| Parameter | Rule |
|---|---|
| `vault` | Non-zero; a factory vault or one the council allowed |
| `verified` | `true` only from the council; verified jobs ignore `customScorer` |
| `horizonSecs` | 1 hour to 7 days; fixed for the job's life |
| `cadenceSecs` | At most 7 days; fixed for the job's life |
| `specUri` | Non-empty. The job's own description of what to predict and how it scores |
| `filter.maxRecentSlashBps` | At most 10,000 |
Job ids start at 2 and count up (`nextJobId()` returns the last one created). Reverts: `ZeroAddress`, `Unauthorized` (caller is not the council or the vault's manager, or a non-council caller sets `verified`), `VaultNotAuthorized(vault)`, `InvalidPolicy`.
The owner can later call `updateJob(jobId, customScorer, specUri, filter, active)` to change the scorer (manager jobs only), the spec, the filter or the active flag, and `setJobWhitelist(jobId, forecasters, allowed)` to manage a private list. Horizon, cadence, vault and `verified` never change.
A vault trades a job through the `forecastJobId` in its fee config: job `1` or a job bound to that vault. With `forecastJobId == 0` the engine reads job 1. [Vault fees](https://docs.degenhive.ai/vaults/fees.md) covers the forecast share that funds the job's pot.
> [!TIP]
> Read a job's `specUri` before you forecast for it. The contract stores the string as given; the job owner decides what it points to.
## Markets
The council lists the markets that rounds may target, up to 256. Each market has a sleeve (`0` core perp, `1` HIP-3 perp on `trade.xyz`), a curated weight cap, its size decimals, and a pause flag. A round can only target listed, unpaused markets.
Asset ids follow HyperCore: a core perp uses its index in the perp universe, and a HIP-3 perp uses `100000 + dex × 10000 + index`.
**viem**
```ts
const abi = parseAbi([
"function marketCount() view returns (uint256)",
"function marketIds(uint256 index) view returns (uint32)",
"function markets(uint32 assetId) view returns (bool listed, bool paused, uint8 sleeve, uint16 maxWeightBps, uint8 szDecimals)",
]);
const n = await pub.readContract({ address: SIGNAL_BOOK, abi, functionName: "marketCount" });
for (let i = 0n; i < n; i++) {
const id = await pub.readContract({ address: SIGNAL_BOOK, abi, functionName: "marketIds", args: [i] });
const [listed, paused, sleeve, maxWeightBps] = await pub.readContract({
address: SIGNAL_BOOK, abi, functionName: "markets", args: [id],
});
console.log(id, { listed, paused, sleeve, maxWeightBps });
}
```
**REST**
```bash
curl -s https://api.degenhive.ai/v1/vaults/markets | jq # asset universe and perp dexes
```
## What a round carries
```solidity
function postJobRound(
uint64 jobId,
uint32 horizonSecs,
uint64 ttlSecs,
uint16 regimeStormBps,
uint32 forecasterCount,
bytes32 forecastsRoot,
uint32[] calldata assetIds,
int16[] calldata targetWeightsBps
) external returns (uint64 roundId);
```
| Field | Meaning | Bound |
|---|---|---|
| `horizonSecs` | How far ahead this round predicts | 1 hour to 7 days |
| `ttlSecs` | How long the targets stay fresh; `expiresAt = postedAt + ttlSecs` | Above 0, at most 7 days |
| `regimeStormBps` | A market-stress reading attached to the round | At most 10,000 |
| `forecasterCount` | How many forecasts went into the round | Attested, not checked |
| `forecastsRoot` | Commitment to every forecast in the round | Non-zero |
| `assetIds`, `targetWeightsBps` | Sparse target weights, signed, in bps of the vault | Listed, unpaused, no duplicates, no zero weight |
Verified jobs are posted by the protocol poster or the council; manager jobs by the manager, its live custom scorer or the council. Reverts: `JobNotFound`, `JobNotActive`, `Unauthorized`, `InvalidPolicy`, `LengthMismatch`, `MarketNotListed`, `MarketPaused`, `DuplicateMarket`, `ZeroAmount` (a zero weight). Each round emits `JobRoundPosted` with every field.
The contract keeps only the latest round's metadata (`jobLatestRound`) and every round's weights (`jobRoundTargetBps(jobId, roundId, assetId)`). `roundId` counts up per job from 1. Nothing on-chain enforces the cadence, and a round's horizon need not equal the job's.
## How engines read a round
A vault's engine steps each market toward the latest round of its job, while that round is fresh:
1. Read `jobLatestRound(job)`. If `block.timestamp > expiresAt`, the target is 0 and the engine steps the market to flat.
2. Otherwise read `jobRoundTargetBps(job, roundId, assetId)`. Markets the round omits have target 0.
3. Clamp the target to the vault tier's cap for that market; Flagship vaults also apply the market's `maxWeightBps`.
`jobTargetWeightOf(jobId, assetId)` returns the same live answer in one call, as `(weightBps, regimeStormBps, fresh)`. Use it to see what a vault is trading toward. The engine does not read `regimeStormBps`.
## The UTC grid
Pay runs on UTC days: `HyperCrowdPay.today()` is `block.timestamp / 86400`, and each job has one pot per day. The protocol poster runs verified jobs on a UTC grid: with cadence `c`, slot `k` opens at `k × c` seconds after the Unix epoch, so the Flagship's 4-hour cadence posts at 00:00, 04:00, 08:00 and so on, UTC. The grid is a poster convention. On-chain, `roundId` is a per-job counter, not the slot number.
> **Figure: Rounds on the UTC grid.** A job's rounds start at multiples of its horizon; each round steers the engine while it is the newest fresh round and is scored once its horizon ends.
>
> A UTC axis for an example 4-hour job, with ticks at 00:00, 04:00, 08:00, 12:00 and 16:00 and four rounds between them: round r − 1, round r (highlighted), round r + 1 and round r + 2. At 04:00 an arrow marks postJobRound, which commits forecastsRoot and target weights and sets expiresAt. At 08:00 a second arrow marks the end of round r's horizon, when round r is scored. A bar under round r shows the engine trading on it while it is the newest fresh round; a dashed tail continues to expiresAt, until which round r stays usable if no newer round posts. The TTL is at most 7 days. Horizons run from 1 hour to 7 days.
Use the decoder to find the current slot and its start time for a cadence, and to convert a percentage weight into bps.
> **Interactive simulator (HyperSignalBook round slot and bps encoder):** UTC round slot `floor(unixSeconds / horizonSecs)` for horizons of 1 hour to 7 days (`3600`..`604800`), and the CrowdPay pot day `floor(unixSeconds / 86400)`. The on-chain `roundId` is a per-job counter. Encodes percent to basis points `round(pct * 100)`: target weights are `int16` (non-zero), and the engine clamps each to `±min(cap, 10000)`; `regimeStormBps` is `0`..`10000`.
Forecasts for a slot must be in before it opens. A forecast posted publicly before its round starts can be copied, which costs you originality in [scoring](https://docs.degenhive.ai/forecasters/scoring.md).
## Related
- [Forecaster quickstart](https://docs.degenhive.ai/forecasters.md) Bond, bind a hot key and check eligibility.
- [Scoring](https://docs.degenhive.ai/forecasters/scoring.md) How the round's forecasts are graded and combined.
- [Bonds & pay](https://docs.degenhive.ai/forecasters/bonds-and-pay.md) How USDC bonds, daily pots and probation payouts work.
- [Writing a model](https://docs.degenhive.ai/forecasters/writing-a-model.md) Produce sparse int16 weights for these rounds.
---
# Scoring
> How forecasts are graded on accuracy plus four times originality, combined into a weighted median, and turned into each day's pay.
Source: https://docs.degenhive.ai/forecasters/scoring
Scoring grades every forecast against what actually happened, once its horizon has passed. A forecast earns for beating the market's own baseline, and four times as much for adding something the consensus of all forecasts missed. This is the idea Numerai calls meta-model contribution (MMC).
Scoring runs off-chain, in the protocol scorer. Nothing about a single forecast or score is written to the chain. What lands on-chain is the result: once a day per job, the scorer commits that day's payout lists to `HyperCrowdPay` as hashed chunks, and they pay out after a challenge window. [Bonds & pay](https://docs.degenhive.ai/forecasters/bonds-and-pay.md) covers that part.
## Definitions
| Term | Symbol | Meaning |
|---|---|---|
| Outcome | `y` | What happened over the round's horizon, for example the 4-hour return of a market |
| Forecast | `f` | Your prediction of `y` for one market and horizon |
| Baseline | `b` | The market's own estimate of `y` before the round |
| Consensus | `m` | The weighted median of every forecast in the round: the meta-model |
| Scale | `s` | The 14-day baseline error for that market and horizon |
| Accuracy | `A` | How much closer you were than the baseline, in units of `s` |
| Contribution (MMC) | `C` | How much closer you were than the consensus, in units of `s` |
| Round score | | `clip(A) + 4 × clip(C)` |
| Record | `r` | Your track record, from 0 to 2, built from past scores |
| 7-day score | `S` | Your rolling average round score over the last 7 days |
| Bond | `B` | Your active bond, in dollars (USDC before the token) |
## One forecast, one score
`Round score`
```math
score = clip(A) + 4 × clip(C)
A = ( |y − b| − |y − f| ) / s
C = ( |y − m| − |y − f| ) / s
clip(x) = max(−1, min(1, x))
```
Each term is clipped to the range −1 to 1, so one lucky outlier cannot dominate a record. Volatility and jump forecasts are scored on log errors.
> **Figure: One forecast, scored.** Accuracy measures the forecast against the market's own estimate; contribution measures it against the consensus and counts four times as much.
>
> A number line from 90 to 140 with four points: b, the market's estimate, at 100; m, the consensus of all forecasts, at 110; f, your forecast, at 125; and y, the outcome, at 130. With log errors and scale s = 0.20: accuracy A = (|ln y − ln b| − |ln y − ln f|) / s = (0.262 − 0.039) / 0.20 = 1.12, clipped to 1. Contribution C = (|ln y − ln m| − |ln y − ln f|) / s = (0.167 − 0.039) / 0.20 = 0.64. Round score = clip(A) + 4 × clip(C) = 1 + 4 × 0.64 = 3.56.
A worked example on a 4-hour return, with baseline `b = 0%` and scale `s = 1.5%`. The market moved `y = +2.4%` against a consensus of `m = +0.8%`:
| Your forecast | `clip(A)` | `clip(C)` | Round score |
|---|---|---|---|
| `f = +2.1%` (beat the consensus) | +1.00 | +0.87 | **+4.47** |
| `f = +0.8%` (copied the consensus) | +0.53 | 0.00 | **+0.53** |
| `f = −1.5%` (wrong contrarian) | −1.00 | −1.00 | **−5.00** |
Copying the consensus earns no contribution, even when the consensus is right. Being different only pays when you are also closer to the outcome.
## The consensus: a weighted median
Each round's forecasts are combined into one weighted median per market. That median is the meta-model `m` for scoring, and the source of the target weights the poster pins on-chain with `postJobRound`.
`Weight in a round`
```math
weight = √B × r (r from 0 to 2)
no forecaster carries more than 20% of a round
```
A bigger bond helps only by its square root, so capital alone cannot buy the consensus. The record counts more: a record of 2 doubles the weight of the same bond, and a record near 0 leaves almost no weight, whatever the bond. Correlated wallets are clustered before the square root is taken, so splitting one bond across many addresses gains nothing. A model carries weight only after at least 20 scored rounds with a t-statistic of at least 2.
## From scores to pay
Each UTC day, a job's pot is split by the 7-day score and, more gently, the bond:
`Share of a day's pot`
```math
share_i = √B_i × max(0, S_i) / Σ_j ( √B_j × max(0, S_j) )
```
A negative 7-day average earns nothing that day. It does not cost you anything either, unless the scorer finds spam or manipulation, which is [slashing](https://docs.degenhive.ai/forecasters/slashing.md). The scorer then builds the day's payout list, splits it into at most 200 chunks, and commits their hashes on-chain.
## Checking a round
The poster's `forecastsRoot` is a commitment to every forecast in the round, pinned before the round's targets are traded. After a round ends, the protocol publishes the round ledger: each forecast and its score. Anyone can then check that the ledger matches the root and recompute the same weighted median. The ledger format and its hashing scheme publish with Season 0.
## Edge cases
- **A forecast leaks before its round starts.** Others can copy it, the consensus moves toward it, and your contribution shrinks. Discuss a round only after it starts.
- **A round expires.** Engines step to flat on an expired round; scoring is unaffected, since it grades forecasts, not trades.
- **Your bond drops below a job's minimum.** You stop being eligible for that job's rounds until it is back above. Unstaking amounts stop counting at once.
- **You hold the same view as the consensus for a week.** Your accuracy may be positive, but your contribution is near zero, and so is your share.
## Related
- [Bonds & pay](https://docs.degenhive.ai/forecasters/bonds-and-pay.md) How committed chunks become USDC in your wallet.
- [Slashing](https://docs.degenhive.ai/forecasters/slashing.md) What the scorer can take, and the daily caps.
- [Writing a model](https://docs.degenhive.ai/forecasters/writing-a-model.md) Build forecasts that add to the consensus.
- [Jobs & rounds](https://docs.degenhive.ai/forecasters/jobs-and-rounds.md) What a round carries and how engines trade it.
---
# Bonds & pay
> The USDC bond, unstaking, daily pots per job, how a day's pay is committed, challenged and distributed, and what changes at token launch.
Source: https://docs.degenhive.ai/forecasters/bonds-and-pay
The **bond** is USDC you lock in `HyperCrowdPay` to forecast. It is your stake against spam and manipulation. **Pay** comes from one pot per job per UTC day, funded mostly by vault performance fees, and reaches your wallet after the day is scored, committed and challenged.
## The bond
| Rule | Value |
|---|---|
| Asset | USDC (6 decimals), until token launch |
| Global minimum | `config().minBondUsdc`, 100 USDC by default; the council can change it |
| Job minimum | `max(global, jobFilter(jobId).minBondUsdc)` |
| Bond age | Starts when your active bond first reaches the global minimum; clears if it falls below |
| Unstake wait | 14 days (`UNSTAKE_DELAY`) |
Stake with `stakeBond(amount)` from the cold wallet; see the [quickstart](https://docs.degenhive.ai/forecasters.md) for code. Only the active amount counts toward eligibility and pay weight.
### Unstaking
```solidity
function requestUnstake(Asset asset, uint256 amount) external; // Asset.USDC = 0, Asset.DGV = 1
function cancelUnstake(Asset asset, uint256 amount) external;
function withdrawUnstaked(Asset asset) external returns (uint256 amount);
```
`requestUnstake` moves the amount from active to unstaking. It stops counting at once and **stays slashable** until you withdraw. Each request sets `readyAt = now + 14 days` for the whole unstaking balance of that asset, so a second request restarts the wait for everything already unstaking. `cancelUnstake` moves an amount back to active. After `readyAt`, `withdrawUnstaked` sends the full unstaking balance to you.
Reverts: `InsufficientBond` (more than you have), `UnstakeNotReady(readyAt)`, `ZeroAmount`, and `BondAssetClosed` when cancelling a USDC unstake after bonds move to DGV.
## Pots
Each `(jobId, day)` has a pot, where `day` is the UTC day index `block.timestamp / 86400` (`today()`). Read it with `pot(jobId, day)`.
- **Vault fees.** At each fee roll, `HyperVaultFeeRouter` sends the vault's forecast share of the net performance fee (up to 5,000 bps, set in the vault's fee config) to `fundUsdc(forecastJobId, today, amount)`. If that call fails, the router holds the amount for `retryForecast(jobId)`.
- **Bounties.** Anyone can add USDC to a job's pot with `fundUsdc`. The job must exist, the day must not be committed, and it can be at most 3 days old.
**cast**
```bash
# Add a 500 USDC bounty to job 7's pot for today
DAY=$(cast call $CROWD_PAY "today()(uint64)")
cast send $USDC "approve(address,uint256)" $CROWD_PAY 500000000 --private-key $KEY
cast send $CROWD_PAY "fundUsdc(uint64,uint64,uint256)" 7 $DAY 500000000 --private-key $KEY
```
Reverts: `JobNotFound`, `ZeroAmount`, `DayTooOld`, `AlreadyCommitted`, `AmountTooLarge`.
## How a day is paid
> **Figure: The life of a forecast.** Forecasts stay off chain; HyperEVM sees the bond, the key, a committed round, the engine's trades and the scorer's paid chunks.
>
> Two lanes: off chain on top, HyperEVM (999) below. Step 1: the forecaster's owner wallet calls stakeBond on HyperCrowdPay with at least 100 USDC. Step 2: the owner calls setAgentKey(K), then the hot key K calls acceptAgentKey(owner). Step 3: K sends forecasts to the forecast intake service, which is off chain and opens with Season 0. The poster seals the round. Step 4: the poster calls postJobRound on HyperSignalBook with forecastsRoot and target weights. Step 5: HyperPerpEngine.stepMarket trades the vault on HyperCore toward the weights. After the horizon, the off-chain scorer scores the round. Step 6: the scorer calls commitDayChunks on HyperCrowdPay. Step 7: a 1-day challenge window, in which the council may veto. Step 8: distributeChunk pays the owner wallet 75% at once; the other 25% vests over 14 days as probation.
1. **Commit.** After day `D` ends, and within 3 days, the scorer calls `commitDayChunks(jobId, D, chunkHashes, totalUsdc, totalDgv, ledgerHash)`. Each of up to 200 chunk hashes is `keccak256(abi.encode(users, usdcAmts, dgvAmts, slashAmts))`. Whatever the totals leave in the pot rolls to today's pot.
2. **Challenge.** The day opens for payout at `unlockAt`, `challengeSecs` after the commit (1 day by default). Until the first chunk is distributed, the council can `veto(jobId, day, reasonHash)`; after a veto only the protocol can commit that day again.
3. **Distribute.** After the window, the scorer calls `distributeChunk(jobId, day, chunkIndex, users, usdcAmts, dgvAmts, slashAmts)` once per chunk. The arrays must hash to the committed chunk, and each chunk pays once. Each address is paid at most once per job per day; zero or repeated entries are skipped and their amounts stay in the pot. Reverts: `InChallenge`, `NotCommitted`, `BatchHashMismatch`, `OverCommitted`, `DayReclaimedAlready`.
4. **Vest.** Part of every payout streams as probation (below). Anyone can call `vestProbation(user)`; it also runs at each payout and slash.
5. **Clean up.** `rollPot(jobId, day)` moves unpaid leftovers to today's pot: 7 days after `unlockAt` for a committed day, or after the 3-day lag for a day nobody committed.
Who may commit and distribute depends on the job. Verified jobs: the protocol scorer or the council. Manager jobs: also the vault's live manager or custom scorer, while the job is active, with USDC only and no inline slashes.
### The payout split
`One payout of amount X`
```math
immediate = X × (10,000 − probationBps) / 10,000 → 75% to your wallet at once
probation = X × probationBps / 10,000 → 25% vests linearly over 14 days
adding p to an unvested stream u with time left t:
endAt = now + (u × t + p × probationSecs) / (u + p)
```
Payouts go to the bond owner, never to the hot key. Unvested probation is the first thing a slash takes, which is why bad days cost earnings before they cost the bond. If a push to your wallet fails, the amount waits as claimable: call `claimFallback(asset, to)` to send it anywhere except zero or the contract.
## Constants
| Name | Default | Bounds | Set by |
|---|---|---|---|
| Challenge window | 1 day | 1 hour to 2 days | Council, `setChallengeSecs` |
| Commit and funding lag (`MAX_LAG_DAYS`) | 3 days | Fixed | |
| Unpaid reclaim wait | 7 days after `unlockAt` | Fixed | |
| Chunks per day | 200 | Fixed | |
| Probation share | 2,500 bps (25%) | At most 8,000 | Council, `setProbation` |
| Probation length | 14 days | 7 to 30 days | Council, `setProbation` |
| Unstake wait | 14 days | Fixed | |
| Minimum bond | 100 USDC | Above 0 | Council, `setMinBondUsdc` |
Council setters on this contract take effect at once.
## At token launch
> [!IMPORTANT]
> Everything in this section happens at token launch, not before. Until then bonds and pay are USDC only.
- **DGV pots.** `DGVEmissions` funds verified jobs in DGV with `fundDgv(jobId, day, amount)`; each vault's emissions split between its depositors and its forecast job by that vault's policy. Manager jobs stay USDC only. DGV payouts use the same 75/25 probation split.
- **DGV bonds.** The council calls `startDgvBonds(window)` once, with a window of 7 to 60 days. From then `stakeBond` reverts with `BondAssetClosed` and bonds go in through `stakeDgvBond(amount)`.
- **Sizing.** The DGV requirement is `max(ceil(requiredUsd × 1e6 / px), minBondDgvFloor)`. The price `px` comes from a price source set once by the council, clamped to a band around a reference price, 0.25× to 4× by default. `requiredBond(usd)` returns the amount in the current bond asset.
- **The window.** During it, USDC bonds still count, alone at face value or added to DGV at `px`, and USDC bond age still counts. After it, only DGV counts. USDC holders then call `requestUnstake(Asset.USDC, amount)` and withdraw; they cannot cancel a USDC unstake.
- **Slashes.** Slashed USDC still goes to the buyback reserve. Slashed DGV is burned.
## Related
- [Slashing](https://docs.degenhive.ai/forecasters/slashing.md) The waterfall and the daily caps.
- [Scoring](https://docs.degenhive.ai/forecasters/scoring.md) How the day's payout list is computed.
- [Forecaster quickstart](https://docs.degenhive.ai/forecasters.md) Bond, bind a hot key and check eligibility.
- [Token](https://docs.degenhive.ai/token.md) DGV and what changes at token launch.
---
# Slashing
> Who can slash a forecaster, the order in which a slash takes unvested pay and bond, the daily caps, and where slashed money goes.
Source: https://docs.degenhive.ai/forecasters/slashing
Slashing takes part of a forecaster's unvested pay, and then part of the bond, when the protocol scorer finds spam or manipulation. It is bounded per day, it always takes unvested pay first, and nobody profits from it: slashed USDC goes to the buyback reserve and slashed DGV is burned.
Like scoring, the judgment is made off-chain. The contract, `HyperCrowdPay`, enforces who may slash, in what order, and how much per day.
## Three ways a slash happens
| Path | Called by | Jobs | Moves funds |
|---|---|---|---|
| Inline, in `distributeChunk` (`slashAmts`) | Protocol scorer or council | Verified jobs only | Yes, routine |
| `proposeSlash` | Manager or custom scorer of a manager job; the protocol for verified jobs | Any | No |
| `executeSlash` | Protocol scorer (routine) or council (routine or adversarial) | Any | Yes |
### proposeSlash
```solidity
function proposeSlash(
uint64 jobId,
uint64 day,
address[] calldata users,
uint256[] calldata suggestedSlashes,
bytes32 evidenceHash
) external returns (uint64 proposalId);
```
A manager job cannot slash on its own. Its manager files a proposal with the evidence hash; it stores `{jobId, day, open}` and emits `SlashProposed`. Reverts: `InvalidPolicy` (empty lists, length mismatch, zero evidence), `ZeroAddress`, `Unauthorized`, `JobInactive`.
### executeSlash
```solidity
function executeSlash(
uint64 proposalId, // 0 for a slash without a proposal
uint64 day,
address[] calldata users,
uint256[] calldata slashAmts, // USD, 6 decimals
bool adversarial,
bytes32 reasonHash
) external;
```
Only the protocol scorer or the council can execute, and only the council can set `adversarial`. With a proposal id, the proposal must be open (`ProposalNotOpen`) and `day` must match it (`InvalidPolicy`); the call closes it and emits `SlashProposalResolved`. The users and amounts are the executor's own, not the proposal's. To close a proposal without slashing, execute it with zero amounts.
The council can also [veto a whole day](https://docs.degenhive.ai/forecasters/bonds-and-pay.md#how-a-day-is-paid), inline slashes included, until its first chunk is distributed.
## The waterfall
Each slash is an amount in USD. It takes from these buckets in order, and stops when the amount or the day's cap is reached:
1. Your unvested USDC probation.
2. Your unvested DGV probation, valued at the DGV price (at token launch).
3. Your DGV bond: active first, then unstaking (at token launch).
4. Your USDC bond: active first, then unstaking.
Probation held back by its cap does not spill into the bond, and any amount left over after the caps is dropped. Unstaking balances are fair game: requesting an unstake does not shield a bond for its 14-day wait.
## Daily caps
| Cap | Limit | Applies to |
|---|---|---|
| Routine bond slash | 500 bps (5%) of your bond value per UTC day | All routine slashes, across every job |
| Adversarial bond slash | 2,500 bps (25%) of your bond value per UTC day | Council adversarial slashes, a separate counter |
| Scorer probation slash | 2,500 bps (25%) of your probation per asset per UTC day | Protocol scorer, routine |
| Council probation slash | No cap | Council |
Bond value is your active and unstaking USDC plus the value of any DGV bond. The caps count by the UTC day the slash executes. Routine slashes can never take more than 5% of the bond itself in one day, however many jobs report you.
## Your slash rate
Every bond slash raises your recent slash rate by the share of the bond taken. The rate decays with a 30-day time constant, and jobs can refuse forecasters above a threshold with `maxRecentSlashBps` (eligibility code `2`). If you raised your bond in the last 14 days, the rate is measured against the smaller pre-raise bond, so topping up just before a slash does not dilute it. `profile(user).recentSlashBps` returns the live decayed value.
## Where slashed funds go
`Slash routing`
```math
slashed USDC → pendingSlashUsdc → flushSlashed() → HyperRevenueRouter.fundBuybackReserve
slashed DGV → DGV.burn
```
`flushSlashed()` runs after every slash and anyone can call it again. If the revenue router is unset or the call fails, the USDC waits in `pendingSlashUsdc` until a later flush. The buyback reserve is held until token launch; see [Revenue](https://docs.degenhive.ai/revenue.md).
## How to avoid it
- **Send one honest forecast per market per round.** Slashing exists for spam and manipulation: junk values, duplicate submissions, many wallets feeding one view. Correlated wallets are also clustered before weighting, so splitting gains nothing.
- **Guard the hot key.** It cannot move funds, but forecasts it signs count as yours. If it leaks, call `setAgentKey(address(0))` from the cold wallet at once.
- **Keep a buffer above the job's minimum bond,** so a small slash does not end your eligibility.
Follow slashes on the API with `GET /v1/forecasting/slashes?account=
` and `GET /v1/forecasting/slash-proposals?job_id=`.
## Related
- [Bonds & pay](https://docs.degenhive.ai/forecasters/bonds-and-pay.md) Probation, unstaking and the daily payout cycle.
- [Scoring](https://docs.degenhive.ai/forecasters/scoring.md) How forecasts are graded.
- [Forecaster quickstart](https://docs.degenhive.ai/forecasters.md) Bond, bind a hot key and protect your wallet.
- [Revenue router](https://docs.degenhive.ai/revenue.md) Where slashed USDC lands in the buyback reserve.
---
# Writing a model
> Practical advice for forecasting DegenHive rounds, from the target format and horizons to originality, overfitting and data, with a Python skeleton.
Source: https://docs.degenhive.ai/forecasters/writing-a-model
A model turns data into one forecast per market for each round of a job. What a vault finally trades is a sparse vector of signed target weights, so this page has you produce exactly that: a map from HyperCore asset id to an int16 weight in basis points.
> [!NOTE]
> The forecast intake service opens with Season 0, and its submission format publishes then. A job's `specUri` says what it asks for; some jobs may ask for returns, volatility or crash risk rather than weights. Build the model and the backtest first, and wire the submit step when the intake opens.
## What a round asks for
| Property | What it means for your model |
|---|---|
| Markets | Only markets listed and unpaused in `HyperSignalBook` count. Read `marketCount()`, `marketIds(i)` and `markets(assetId)` |
| Asset ids | Core perps use their index in the HyperCore perp universe; HIP-3 perps use `100000 + dex × 10000 + index` |
| Weights | Signed bps of the vault: `+500` is 5% long, `-300` is 3% short. Leave a market out for 0 |
| Caps | Engines clamp each weight to the vault tier's cap; Flagship vaults also apply `maxWeightBps`. Weights past the cap buy nothing |
| Horizon | 1 hour to 7 days per job. The Flagship job predicts 24 hours ahead every 4 hours |
| Freshness | A round's targets expire after its TTL; an expired round steps the vault to flat |
Sparse is the norm. A good round names the few markets where you have a view and leaves the rest at 0.
## Be different, and right
Scoring pays accuracy against the market's baseline, plus four times your contribution beyond the weighted median of all forecasts. Copying the consensus scores zero contribution even when the consensus is right. See [Scoring](https://docs.degenhive.ai/forecasters/scoring.md).
- **Measure your overlap.** Every posted round's combined weights are public: `GET /v1/forecasting/jobs/{job_id}/rounds` returns `asset_ids` and `target_weights_bps`. Correlate your history against them. A model that tracks the consensus closely has little to add.
- **Use data other forecasters underuse.** Price momentum on BTC and ETH is a crowded signal. Funding, open interest, basis between HIP-3 stocks and their reference markets, and order-book imbalance are less so.
- **Keep it to yourself until the round starts.** A forecast posted publicly before its round opens can be copied, and the copies erase your contribution.
## Do not overfit
A day has only a handful of rounds, and a model carries weight only after at least 20 scored rounds with a t-statistic of at least 2. Noise looks like skill for a long time at this sample size.
- Validate walk-forward, never on shuffled data. Leave a gap of at least one horizon between training and test windows, so overlapping returns do not leak.
- Prefer few parameters and signals with a reason to exist. Count every variant you tried; the best of fifty backtests is mostly luck.
- Score your backtest the way the protocol does: `clip(A) + 4 × clip(C)` against a baseline and a consensus proxy, not raw PnL.
- Watch turnover. Weights that flip every round are expensive for the vault to trade, even when they score.
## Data
- **Public HyperCore data.** The Hyperliquid info API (`https://api.hyperliquid.xyz/info`) serves the perp universe, candles, funding, open interest and order books with no key. The skeleton below uses it.
- **The data marketplace.** Providers list feeds in `DataProviderRegistry`; browse them with `GET /v1/data/providers`. Feeds are sold to vaults on-chain; ask a provider about access for your own research. See [Data](https://docs.degenhive.ai/data.md).
- **Your own record.** `GET /v1/forecasting/forecasters/{account}` and `GET /v1/forecasting/payouts` show how your past rounds paid.
## A Python skeleton
The script reads public HyperCore data, builds a simple risk-scaled momentum and funding signal, and prints one round's sparse weight vector. Replace the signal with your model.
`forecast.py`
```python
"""One round's sparse weight vector for a DegenHive job. Standard library only."""
import json
import math
import statistics
import time
import urllib.request
INFO = "https://api.hyperliquid.xyz/info"
JOB_ID = 1
HORIZON_H = 24 # job(JOB_ID).horizonSecs / 3600
CAP_BPS = 2_500 # per market: min(vault tier cap, markets(assetId).maxWeightBps)
MIN_ABS_BPS = 50 # smaller views are left out: the vector stays sparse
COINS = ["BTC", "ETH", "HYPE"] # keep to markets listed in HyperSignalBook
def info(body: dict):
req = urllib.request.Request(
INFO, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}
)
with urllib.request.urlopen(req, timeout=10) as r:
return json.load(r)
def universe() -> dict:
"""Coin -> (asset id, hourly funding). A core perp's asset id is its index."""
meta, ctxs = info({"type": "metaAndAssetCtxs"})
return {
a["name"]: (i, float(c["funding"]))
for i, (a, c) in enumerate(zip(meta["universe"], ctxs))
}
def hourly_closes(coin: str, hours: int) -> list[float]:
end = int(time.time() * 1000)
start = end - hours * 3_600_000
rows = info({"type": "candleSnapshot",
"req": {"coin": coin, "interval": "1h", "startTime": start, "endTime": end}})
return [float(r["c"]) for r in rows]
def score(coin: str, funding: float) -> float:
"""Your model goes here. Returns a signed view in units of horizon volatility."""
px = hourly_closes(coin, 24 * 30)
rets = [math.log(b / a) for a, b in zip(px, px[1:])]
vol_h = statistics.pstdev(rets) * math.sqrt(HORIZON_H) or 1e-9
lookback = 7 * HORIZON_H
momentum = math.log(px[-1] / px[-1 - lookback]) / (vol_h * math.sqrt(7))
carry = -funding * HORIZON_H / vol_h # crowded longs pay funding: lean against them
return 0.5 * momentum + 0.5 * carry
def to_bps(view: float) -> int:
bps = int(round(max(-1.0, min(1.0, view / 2)) * CAP_BPS))
return bps if abs(bps) >= MIN_ABS_BPS else 0
def main() -> None:
uni = universe()
weights = {}
for coin in COINS:
asset_id, funding = uni[coin]
bps = to_bps(score(coin, funding))
if bps != 0:
weights[asset_id] = bps # int16 range; engines clamp to the cap anyway
round_forecast = {"jobId": JOB_ID, "horizonSecs": HORIZON_H * 3600, "weightsBps": weights}
print(json.dumps(round_forecast, indent=2))
# TODO: submit round_forecast, signed with your hot key.
# The intake opens with Season 0; its endpoint and format publish then.
if __name__ == "__main__":
main()
```
Run it with `python3 forecast.py`. Before you rely on it, check that each coin is listed for your job, and backtest the same function over past rounds with the walk-forward rules above.
## Related
- [Jobs & rounds](https://docs.degenhive.ai/forecasters/jobs-and-rounds.md) Markets, horizons and how engines read a round.
- [Scoring](https://docs.degenhive.ai/forecasters/scoring.md) The exact formula your backtest should use.
- [Forecaster quickstart](https://docs.degenhive.ai/forecasters.md) Bond, bind a hot key and check eligibility.
- [Data](https://docs.degenhive.ai/data.md) The feeds vaults buy, and how providers list them.
---
# Vaults overview
> What a HyperVault and HyperPerpEngine pair is, the three vault tiers, who can create one, and the daily UTC epoch.
Source: https://docs.degenhive.ai/vaults
A vault is a pair of contracts on HyperEVM (chain 999): a `HyperVault` that holds depositors' USDC and issues shares, and a `HyperPerpEngine` that trades the vault's HyperCore account. One factory call deploys both, and each pair is its own upgradeable proxy set.
> [!IMPORTANT]
> The vault contracts are not deployed yet and not externally audited. Addresses publish at launch on [Network](https://docs.degenhive.ai/network.md). Code on this page uses placeholders such as `VAULT` and `ENGINE`.
## How a vault works
The vault is an ERC-7540 asynchronous vault with an ERC-7575 share token (6 decimals, the vault address itself). Depositors queue USDC during a UTC day. Once per day, `roll()` prices the shares, takes fees, mints queued deposits and pays queued redemptions. The [depositor guide](https://docs.degenhive.ai/vaults/depositors.md) walks through each call.
Capital moves in one direction at a time:
1. Settled USDC sits in the vault as `idleUsdc`.
2. The keeper or manager calls `deployToEngine(amount)`. The engine holds it on HyperEVM as `evmIdleUsdc`.
3. The engine bridges USDC to its own HyperCore account and trades perps through CoreWriter limit orders.
4. To pay withdrawals, USDC comes back from HyperCore to the engine, and the vault pulls it at the roll.
The engine never uses a HyperCore API wallet. Only three callers can trade: the vault's keeper, its strategy manager and the council. Each step either follows the latest forecast round of the vault's job (`stepMarket`) or a target the caller supplies (`stepMarketTarget`). See [Trading](https://docs.degenhive.ai/vaults/trading.md).
NAV is `idleUsdc + engine.totalEquityUsdc()` minus fees owed. Engine equity is its HyperEVM idle USDC plus its HyperCore account value across tracked perp dexes and spot USDC. Pending deposits and settled-but-unclaimed USDC sit in the vault's balance but stay outside NAV.
## Flagship and third-party vaults
| | Flagship | Third-party |
|---|---|---|
| Who deploys | Council only, in every creation mode | Council, whitelisted creators or anyone, by `CreationMode` |
| Creation fee | None | `creationFeeUsdc` (10 USDC by default) |
| Fee terms set by | Council only | Strategy manager or council |
| Management fee | 100% to the protocol | Protocol take, rest to the manager |
| Performance fee | Royalties, forecasters, then the protocol | Protocol take, royalties, forecasters, then the manager |
| Drawdown latch | Optional (0 turns it off) | Required, 200 bps up to the tier maximum |
The Flagship runs a 1% management fee and a 25% performance fee. Every vault chooses its own fees within the bounds on [Fees](https://docs.degenhive.ai/vaults/fees.md).
## Tiers
Every vault declares a `VaultTier` in its DNA. The tier sets the ceilings the DNA must fit under and scales how much of equity one asset may take. These are the defaults in `HyperVaultConfig`:
| `VaultTier` | `maxGrossBps` | `maxNetExposureBps` | `maxDailyLossBps` | `maxDrawdownBps` | `assetWeightMultiplierBps` | Per-asset cap, market tier 1 / 2 / 3 |
|---|---|---|---|---|---|---|
| `FLAGSHIP` (0) | 50,000 (5x) | 5,000 (0.5x) | 1,000 (10%) | 5,000 (50%), or 0 | 10,000 (1x) | 25% / 10% / 3% |
| `INSTITUTIONAL` (1) | 50,000 (5x) | 5,000 (0.5x) | 1,000 (10%) | 2,500 (25%) | 10,000 (1x) | 25% / 10% / 3% |
| `COMMUNITY_ARENA` (2) | 50,000 (5x) | 30,000 (3x) | 1,000 (10%) | 5,000 (50%) | 40,000 (4x) | 100% / 40% / 12% |
Global floors apply on top: gross exposure at least 5,000 bps, daily loss stop at least 50 bps, drawdown latch at least 200 bps for third-party vaults. The council can change tier bounds with `setTierBounds` inside hard ceilings (gross 5,000–50,000, daily loss 50–1,000, drawdown 200–5,000, multiplier 10,000–100,000). A change applies to new vaults only, except `assetWeightMultiplierBps`, which every engine reads live.
Market tiers rank assets: 1 is majors, 2 is the top 50 plus HIP-3 markets, 3 is the long tail. A vault with `marketTier` 3 may trade tiers 1 to 3. Per-asset caps start from `tierMaxWeightBps` (25%, 10%, 3%), times the tier multiplier, capped at 100%.
## Vault DNA
DNA is the vault's permanent risk identity. The factory validates it, copies it into the engine and no setter exists. Only an engine implementation upgrade (72-hour delay) could change it.
```solidity
struct VaultDna {
bool isFlagship; // true iff vaultTier == FLAGSHIP
uint8 marketTier; // 1 majors, 2 top-50 + HIP-3, 3 long tail
uint24 maxGrossBps; // 5,000..50,000 (0.5x..5x)
uint16 maxNetExposureBps; // <= maxGrossBps and the tier cap
uint16 maxDailyLossBps; // 50..1,000
VaultTier vaultTier;
uint16 maxDrawdownBps; // 0 (flagship only) or 200..tier max
}
```
Execution knobs (`EngineRiskParams`) are separate and can change: tighten at once, loosen after 7 days. See [Risk](https://docs.degenhive.ai/vaults/risk.md).
## Who can create a vault
`HyperVaultConfig.creationMode` gates `HyperVaultFactory.deployStrategyVault`:
| `CreationMode` | Who may deploy a third-party vault |
|---|---|
| `OFF` (0, default) | Nobody. Only the council, and only flagships. |
| `WHITELISTED` (1) | The council and addresses on `creatorWhitelist` |
| `PERMISSIONLESS` (2) | Any address |
Check before you build: `canCreateVault(creator, false)` returns the answer for your address. Flagships are council-only in every mode.
## Public and private vaults
A vault is public unless it sets `whitelistEnabled`. On a private vault, only whitelisted addresses can request deposits, as owner and as controller. The compliance admin, the manager or the council maintains the list with `setWhitelistedLp(lp, allowed)`. With `whitelistTransfers` also on, shares can only move to whitelisted addresses. Redemptions are never whitelist-gated, so a removed depositor can always leave. The factory whitelists the manager automatically, and the compliance admin defaults to the manager.
## The daily epoch
The vault keeps one clock: the UTC day, `block.timestamp / 86400`. Each day has one roll.
- Requests made before 00:00 UTC settle at the next roll.
- From 00:00 UTC, the keeper, manager or council may call `roll()`.
- From 02:00 UTC, anyone may call it.
- If nobody rolls for several days, one roll covers them: the management fee accrues for every elapsed day.
Shares minted at a roll earn from that roll on, even before the depositor claims them.
## Roles
| Role | Set by | Powers |
|---|---|---|
| Council (`admin`) | `HyperVaultConfig` two-step admin | Every setter; the only fee-terms holder on flagships; `clearDrawdownStop`, `setEmergencyFlatten` |
| Strategy manager | Creator at deploy; council after | Fee terms, keeper, cap, whitelist, wind-down (third-party); risk params; trading |
| Keeper | Manager or council, `setKeeper` | Trading, bridging, `deployToEngine`, early roll window |
| Compliance admin | Manager or council | Whitelist settings |
| Protocol allocator | Council | A depositor with no minimum, no cap and no management fee |
| Operator | Each depositor, `setOperator` | Requests and claims for that depositor |
## Related
- [Create a vault](https://docs.degenhive.ai/vaults/create.md) Deploy a vault and engine pair through the factory.
- [Trading](https://docs.degenhive.ai/vaults/trading.md) How steps, bridging and CoreWriter orders work.
- [Risk](https://docs.degenhive.ai/vaults/risk.md) Stops, latches, flatten paths and wind-down.
- [Deposits & withdrawals](https://docs.degenhive.ai/vaults/depositors.md) ERC-7540 requests, daily rolls and claims.
---
# Create a vault
> Deploy a HyperVault and HyperPerpEngine pair through HyperVaultFactory, then fund it, set a keeper and run the first roll.
Source: https://docs.degenhive.ai/vaults/create
This guide deploys a third-party vault on HyperEVM (chain 999) with one call to `HyperVaultFactory.deployStrategyVault`, then takes it to its first trade.
You need:
- a wallet that passes `canCreateVault` (see step 1), with HYPE for gas and at least 20 USDC on HyperEVM (10 USDC creation fee, 10 USDC first deposit);
- a keeper address for your trading bot (it can hold only gas);
- `viem` 2.x or Foundry's `cast`.
> [!IMPORTANT]
> Nothing is deployed yet. `FACTORY`, `CONFIG`, `USDC`, `VAULT` and `ENGINE` are placeholders. Addresses publish at launch on [Network](https://docs.degenhive.ai/network.md).
Shared setup for the viem snippets:
`client.ts`
```ts
import { createPublicClient, createWalletClient, defineChain, http, type Address } from "viem";
import { privateKeyToAccount } from "viem/accounts";
// Placeholders: addresses publish at launch.
export const CONFIG = process.env.CONFIG as Address; // HyperVaultConfig
export const FACTORY = process.env.FACTORY as Address; // HyperVaultFactory
export const USDC = process.env.USDC as Address; // USDC on HyperEVM
export const VAULT = process.env.VAULT as Address; // your vault, after step 6
export const ENGINE = process.env.ENGINE as Address; // your engine, after step 6
export const KEEPER = process.env.KEEPER as Address;
export const hyperEvm = defineChain({
id: 999,
name: "HyperEVM",
nativeCurrency: { name: "HYPE", symbol: "HYPE", decimals: 18 },
rpcUrls: { default: { http: ["https://rpc.hyperliquid.xyz/evm"] } },
});
export const account = privateKeyToAccount(process.env.MANAGER_KEY as `0x${string}`);
export const publicClient = createPublicClient({ chain: hyperEvm, transport: http() });
export const wallet = createWalletClient({ account, chain: hyperEvm, transport: http() });
```
## Step 1: Check that you can create a vault
`HyperVaultConfig.creationMode` starts at `OFF`, where only the council deploys, and only flagships. In `WHITELISTED` mode your address must be on the council's creator whitelist. In `PERMISSIONLESS` mode anyone can deploy. Ask the config directly:
**viem**
```ts
import { parseAbi } from "viem";
import { CONFIG, account, publicClient } from "./client";
export const configAbi = parseAbi([
"struct TierBounds { uint24 maxGrossBps; uint16 maxNetExposureBps; uint16 maxDailyLossBps; uint16 maxDrawdownBps; uint32 assetWeightMultiplierBps; }",
"function canCreateVault(address creator, bool isFlagship) view returns (bool)",
"function creationMode() view returns (uint8)",
"function creationFeeUsdc() view returns (uint256)",
"function maxCapForManager(address manager) view returns (uint256)",
"function tierBounds(uint8 tier) view returns (TierBounds)",
"function isAssetAllowedForVault(uint32 assetId, uint8 marketTier, uint8 vaultTier) view returns (bool allowed, uint16 maxWeightBps)",
]);
const allowed = await publicClient.readContract({
address: CONFIG, abi: configAbi, functionName: "canCreateVault", args: [account.address, false],
});
const capCeiling = await publicClient.readContract({
address: CONFIG, abi: configAbi, functionName: "maxCapForManager", args: [account.address],
});
console.log({ allowed, capCeiling }); // capCeiling defaults to 2,000,000 USDC (2_000_000e6)
```
**cast**
```bash
cast call $CONFIG "canCreateVault(address,bool)(bool)" $ME false --rpc-url $HYPEREVM_RPC
cast call $CONFIG "maxCapForManager(address)(uint256)" $ME --rpc-url $HYPEREVM_RPC
cast call $CONFIG "tierBounds(uint8)((uint24,uint16,uint16,uint16,uint32))" 2 --rpc-url $HYPEREVM_RPC
```
If `canCreateVault` returns false, the deploy reverts with `CreationNotAllowed(creator, isFlagship)`.
## Step 2: Choose the DNA
DNA is permanent. The factory checks it against the global bounds and your tier's `TierBounds` (see the table on [Vaults](https://docs.degenhive.ai/vaults.md#tiers)), then copies it into the engine with no setter.
| Field | Type | Rule |
|---|---|---|
| `isFlagship` | `bool` | `false` for every third-party vault. Must equal `vaultTier == FLAGSHIP`. |
| `marketTier` | `uint8` | 1 (majors), 2 (top 50 + HIP-3) or 3 (long tail). You may trade every tier up to this one. |
| `maxGrossBps` | `uint24` | 5,000–50,000 and at most the tier's `maxGrossBps` |
| `maxNetExposureBps` | `uint16` | At most `maxGrossBps`, the tier cap (5,000 or 30,000) and the global cap (30,000) |
| `maxDailyLossBps` | `uint16` | 50–1,000, at most the tier cap |
| `vaultTier` | `uint8` | 1 `INSTITUTIONAL` or 2 `COMMUNITY_ARENA` |
| `maxDrawdownBps` | `uint16` | 200 up to the tier cap (2,500 institutional, 5,000 community arena) |
Any rule broken reverts with `InvalidPolicy()`.
## Step 3: Choose fees and the forecast job
| Field | Type | Rule |
|---|---|---|
| `mgmtFeeBps` | `uint16` | 0–200 per year, on external shares |
| `perfFeeBps` | `uint16` | 1,000–2,500, above the per-share high-water mark |
| `forecastShareBps` | `uint16` | 0–5,000, share of the net performance fee paid to the job's forecasters |
| `forecastJobId` | `uint64` | Required when the share is above 0. Job 1 (the flagship job) or a job bound to this vault. |
| `managerFeeRecipient` | `address` | Required. Receives your share of both fees. |
`stepMarket` trades the signal of `forecastJobId`, or job 1 when it is 0. A vault that pays a forecaster share usually follows that job's rounds. See [Jobs and rounds](https://docs.degenhive.ai/forecasters/jobs-and-rounds.md). Out-of-bounds fees revert with `InvalidPolicy()`; a zero fee recipient reverts with `ZeroAddress()`.
## Step 4: Choose the starting risk params
`EngineRiskParams` are the engine's execution knobs. You can tighten them at once later and loosen them after 7 days.
| Field | Type | Default bound | Meaning |
|---|---|---|---|
| `minMarginRatioBps` | `uint16` | 1,000–10,000 | Equity over total notional. Below it, gross-increasing steps revert and anyone may flatten. |
| `maxDailyTurnoverBps` | `uint32` | 5,000–100,000 | Traded notional per UTC day, in bps of day-start equity |
| `maxStepBps` | `uint16` | 0–50,000 | Largest weight change per step. 0 means go straight to target. |
| `maxSlippageBps` | `uint16` | 5–500 | Limit price distance from the oracle for IOC and GTC orders |
| `makerOffsetBps` | `uint16` | 0–200 | Distance inside the oracle price for ALO orders |
| `defaultTif` | `uint8` | 1–3 | 1 ALO, 2 GTC, 3 IOC |
| `maxIdleSecs` | `uint32` | 1–14 days | After this long with no step or heartbeat, anyone may flatten |
Out-of-bounds values revert with `InvalidPolicy()`.
## Step 5: Approve the creation fee
Third-party vaults pay `creationFeeUsdc` (10 USDC by default, at most 1,000 USDC) when the caller is not the council. The factory sends it straight to `HyperRevenueRouter.notifyRevenue`. Set `maxCreationFeeUsdc` in your params to the fee you read, so a fee change cannot surprise you.
**viem**
```ts
import { erc20Abi } from "viem";
import { CONFIG, FACTORY, USDC, publicClient, wallet } from "./client";
import { configAbi } from "./check";
const fee = await publicClient.readContract({ address: CONFIG, abi: configAbi, functionName: "creationFeeUsdc" });
await wallet.writeContract({ address: USDC, abi: erc20Abi, functionName: "approve", args: [FACTORY, fee] });
```
**cast**
```bash
FEE=$(cast call $CONFIG "creationFeeUsdc()(uint256)" --rpc-url $HYPEREVM_RPC)
cast send $USDC "approve(address,uint256)" $FACTORY $FEE --rpc-url $HYPEREVM_RPC --account manager
```
If the live fee is above your `maxCreationFeeUsdc`, the deploy reverts with `CreationFeeTooHigh(feeUsdc, maxFeeUsdc)`.
## Step 6: Deploy the vault
This call deploys an engine proxy and a vault proxy, initializes both and registers them. The struct below matches `DeployVaultParams` in `IHyperVaultPlatform.sol`, field for field. `VaultTier` is a `uint8` in the ABI.
**viem**
```ts
import { parseAbi, parseEventLogs, parseUnits, zeroAddress } from "viem";
import { FACTORY, KEEPER, account, publicClient, wallet } from "./client";
const factoryAbi = parseAbi([
"struct VaultDna { bool isFlagship; uint8 marketTier; uint24 maxGrossBps; uint16 maxNetExposureBps; uint16 maxDailyLossBps; uint8 vaultTier; uint16 maxDrawdownBps; }",
"struct FeeConfig { uint16 mgmtFeeBps; uint16 perfFeeBps; uint16 forecastShareBps; uint64 forecastJobId; address managerFeeRecipient; }",
"struct EngineRiskParams { uint16 minMarginRatioBps; uint32 maxDailyTurnoverBps; uint16 maxStepBps; uint16 maxSlippageBps; uint16 makerOffsetBps; uint8 defaultTif; uint32 maxIdleSecs; }",
"struct DeployVaultParams { string name; string symbol; address strategyManager; address keeper; address complianceAdmin; VaultDna dna; FeeConfig fees; EngineRiskParams risk; uint256 vaultCapUsdc; bool lockerCapEnabled; bool whitelistEnabled; bool whitelistTransfers; uint256 maxCreationFeeUsdc; }",
"function deployStrategyVault(DeployVaultParams params) returns (address vault, address engine)",
"event VaultDeployed(address indexed vault, address indexed engine, address indexed creator, address strategyManager, address complianceAdmin, address vaultProxyAdmin, address engineProxyAdmin, uint256 creationFeeUsdc, DeployVaultParams params)",
"error CreationNotAllowed(address creator, bool isFlagship)",
"error VaultCapCeilingExceeded(uint256 requestedCap, uint256 maxAllowedCap)",
"error CreationFeeTooHigh(uint256 feeUsdc, uint256 maxFeeUsdc)",
"error InvalidPolicy()",
"error Unauthorized()",
"error ZeroAddress()",
"error ZeroAmount()",
]);
const params = {
name: "Trend50",
symbol: "dhT50",
strategyManager: zeroAddress, // zero = you
keeper: KEEPER,
complianceAdmin: zeroAddress, // zero with a whitelist = the manager
dna: {
isFlagship: false,
marketTier: 2, // majors plus top 50 and HIP-3
maxGrossBps: 20_000, // 2x gross
maxNetExposureBps: 10_000, // 1x net
maxDailyLossBps: 300, // 3% daily loss stop
vaultTier: 2, // COMMUNITY_ARENA
maxDrawdownBps: 2_000, // 20% below the high-water mark latches
},
fees: {
mgmtFeeBps: 100, // 1% per year
perfFeeBps: 2_000, // 20% above HWM
forecastShareBps: 1_000, // 10% of the net perf fee to job 1's forecasters
forecastJobId: 1n,
managerFeeRecipient: account.address,
},
risk: {
minMarginRatioBps: 1_500,
maxDailyTurnoverBps: 20_000,
maxStepBps: 2_500,
maxSlippageBps: 30,
makerOffsetBps: 2,
defaultTif: 1, // ALO
maxIdleSecs: 3 * 86_400,
},
vaultCapUsdc: parseUnits("250000", 6),
lockerCapEnabled: false,
whitelistEnabled: false,
whitelistTransfers: false,
maxCreationFeeUsdc: parseUnits("10", 6),
} as const;
const { request } = await publicClient.simulateContract({
account, address: FACTORY, abi: factoryAbi, functionName: "deployStrategyVault", args: [params],
});
const hash = await wallet.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
const [deployed] = parseEventLogs({ abi: factoryAbi, eventName: "VaultDeployed", logs: receipt.logs });
console.log("vault", deployed.args.vault, "engine", deployed.args.engine);
```
**cast**
```bash
PARAMS_SIG="deployStrategyVault((string,string,address,address,address,(bool,uint8,uint24,uint16,uint16,uint8,uint16),(uint16,uint16,uint16,uint64,address),(uint16,uint32,uint16,uint16,uint16,uint8,uint32),uint256,bool,bool,bool,uint256))"
ZERO=0x0000000000000000000000000000000000000000
cast send $FACTORY "$PARAMS_SIG" \
"(Trend50,dhT50,$ZERO,$KEEPER,$ZERO,(false,2,20000,10000,300,2,2000),(100,2000,1000,1,$ME),(1500,20000,2500,30,2,1,259200),250000000000,false,false,false,10000000)" \
--rpc-url $HYPEREVM_RPC --account manager
```
What the factory does in that transaction:
1. Pulls the creation fee and sends it to `HyperRevenueRouter`.
2. Deploys the engine and vault pair behind a 72-hour upgrade delay.
3. Writes a `VaultRecord` (`vaultRecord(vault)`, `isVault(vault)`, `engineOf(vault)`) and adds 1 to `managerActiveVaultCount(manager)`.
4. Initializes the vault (fees, cap, keeper, whitelist) and the engine (DNA, risk params, the Core deposit wallet). It re-validates the DNA and risk params.
5. At token launch, registers the vault with `HyperBookRewards`. Before the token this step is skipped.
6. Emits `VaultDeployed`.
Reverts you can hit:
- `CreationNotAllowed(creator, isFlagship)`: the creation mode does not allow you.
- `InvalidPolicy()`: empty name or symbol, or DNA, fees or risk params out of bounds.
- `ZeroAmount()`: `vaultCapUsdc` is 0.
- `Unauthorized()`: you named someone else as `strategyManager`. Only the council may.
- `VaultCapCeilingExceeded(requestedCap, maxAllowedCap)`: the cap is above `maxCapForManager(you)`.
- `CreationFeeTooHigh(feeUsdc, maxFeeUsdc)`: the live fee is above your limit.
- `ZeroAddress()`: missing fee recipient, or the protocol's router or upgrade controller is not wired.
## Step 7: Set the keeper
The keeper is the hot address your bot signs with. It can trade, bridge, deploy idle USDC to the engine and roll early. It cannot change fees, risk params or the manager. Change it any time; the change is instant.
**viem**
```ts
import { parseAbi } from "viem";
import { VAULT, wallet } from "./client";
const NEW_KEEPER = "0x..." as const; // your bot's address
const vaultAbi = parseAbi(["function setKeeper(address keeper)"]);
await wallet.writeContract({ address: VAULT, abi: vaultAbi, functionName: "setKeeper", args: [NEW_KEEPER] });
```
**cast**
```bash
cast send $VAULT "setKeeper(address)" $NEW_KEEPER --rpc-url $HYPEREVM_RPC --account manager
```
Only the manager or the council can call it (`Unauthorized()` otherwise). A zero keeper is allowed; then only you and the council can trade.
## Step 8: Make the first deposit
Seed the vault with your own capital. The minimum request is 10 USDC (`DepositBelowMinimum(amount, minAmount)` below that). The very first roll that mints shares sends 1 share (1e6 units, 1 USDC at the starting price) to `0x…dEaD`, so a tiny first deposit cannot distort the share price.
**viem**
```ts
import { erc20Abi, parseAbi, parseUnits } from "viem";
import { USDC, VAULT, account, wallet } from "./client";
const amount = parseUnits("1000", 6);
const depositAbi = parseAbi([
"function requestDeposit(uint256 assets, address controller, address owner) returns (uint256)",
]);
await wallet.writeContract({ address: USDC, abi: erc20Abi, functionName: "approve", args: [VAULT, amount] });
await wallet.writeContract({
address: VAULT, abi: depositAbi, functionName: "requestDeposit", args: [amount, account.address, account.address],
});
```
**cast**
```bash
cast send $USDC "approve(address,uint256)" $VAULT 1000000000 --rpc-url $HYPEREVM_RPC --account manager
cast send $VAULT "requestDeposit(uint256,address,address)" 1000000000 $ME $ME --rpc-url $HYPEREVM_RPC --account manager
```
When the council enables skin in the game, outside deposits are capped by your own stake: the free starter cap (50,000 USDC by default) plus 20 times your co-investment. See [Risk](https://docs.degenhive.ai/vaults/risk.md#manager-skin-in-the-game).
## Step 9: Run the first roll and fund the engine
The vault's clock starts on the UTC day of deployment. The first roll is due from the next 00:00 UTC. Your keeper rolls between 00:00 and 02:00; after that, anyone can.
**viem**
```ts
import { parseAbi, parseUnits } from "viem";
import { ENGINE, VAULT, account, wallet } from "./client";
const opsAbi = parseAbi([
"function roll()",
"function realize(address user)",
"function deployToEngine(uint256 usdcAmount)",
"function bridgeUsdcToCore(uint256 usdcAmount, uint32 destinationDex)",
]);
await wallet.writeContract({ address: VAULT, abi: opsAbi, functionName: "roll" });
await wallet.writeContract({ address: VAULT, abi: opsAbi, functionName: "realize", args: [account.address] });
await wallet.writeContract({ address: VAULT, abi: opsAbi, functionName: "deployToEngine", args: [parseUnits("900", 6)] });
await wallet.writeContract({ address: ENGINE, abi: opsAbi, functionName: "bridgeUsdcToCore", args: [parseUnits("900", 6), 0] });
```
**cast**
```bash
cast send $VAULT "roll()" --rpc-url $HYPEREVM_RPC --account keeper
cast send $VAULT "realize(address)" $ME --rpc-url $HYPEREVM_RPC --account manager
cast send $VAULT "deployToEngine(uint256)" 900000000 --rpc-url $HYPEREVM_RPC --account keeper
cast send $ENGINE "bridgeUsdcToCore(uint256,uint32)" 900000000 0 --rpc-url $HYPEREVM_RPC --account keeper
```
`roll()` reverts with `RollNotDue()` if the vault already rolled today, and `Unauthorized()` if a non-role calls it before 02:00 UTC. `bridgeUsdcToCore` sends USDC to perp dex 0 (`0`) or to spot (`4294967295`, `type(uint32).max`). It opens a 30-second bridge window: deposits, rolls and steps revert with `BridgeInFlight()` until it closes. A second bridge within 2 minutes reverts with `BridgeTooSoon(nextAllowedAt)`.
Before you step an asset, confirm it is open to your vault with `isAssetAllowedForVault(assetId, marketTier, vaultTier)` on the config. Every stepped market must also be listed in `HyperSignalBook`.
## Step 10: Where to go next
- [Trading](https://docs.degenhive.ai/vaults/trading.md) Write the keeper loop that steps your book.
- [Risk](https://docs.degenhive.ai/vaults/risk.md) What stops a vault and how to wind one down.
- [Fees](https://docs.degenhive.ai/vaults/fees.md) How your fees flow through the waterfall.
- [Deposits & withdrawals](https://docs.degenhive.ai/vaults/depositors.md) How depositors enter, settle and redeem shares.
---
# 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