# 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> { return new Map([ [0, 3_000], // 30% long [1, -1_500], // 15% short ]); } function revertName(err: unknown): string | undefined { if (!(err instanceof BaseError)) return undefined; const reverted = err.walk((e) => e instanceof ContractFunctionRevertedError); return reverted instanceof ContractFunctionRevertedError ? reverted.data?.errorName : undefined; } async function roll() { const { request } = await publicClient.simulateContract({ account: keeper, address: VAULT, abi: vaultAbi, functionName: "roll", }); await publicClient.waitForTransactionReceipt({ hash: await wallet.writeContract(request) }); } async function step(assetId: number, targetWeightBps: number) { const { request } = await publicClient.simulateContract({ account: keeper, address: ENGINE, abi: engineAbi, functionName: "stepMarketTarget", args: [assetId, targetWeightBps], }); await publicClient.waitForTransactionReceipt({ hash: await wallet.writeContract(request) }); } async function heartbeat() { const { request } = await publicClient.simulateContract({ account: keeper, address: ENGINE, abi: engineAbi, functionName: "heartbeat", }); await publicClient.waitForTransactionReceipt({ hash: await wallet.writeContract(request) }); } async function tick() { if (await publicClient.readContract({ address: ENGINE, abi: engineAbi, functionName: "isBridging" })) return; // 1. Roll once per UTC day, inside the keeper window (00:00-02:00 UTC). if (await publicClient.readContract({ address: VAULT, abi: vaultAbi, functionName: "rollDue" })) { await roll(); } // 2. Stop if a latch, an emergency or a wind-down is set. The engine would revert anyway. const s = await publicClient.readContract({ address: ENGINE, abi: engineAbi, functionName: "state" }); if (s.windingDown || s.emergencyFlattening || s.dayLossStopped || s.drawdownStopped) { console.warn("engine stopped", s); return; } // 3. Step each asset toward its target. let stepped = false; for (const [assetId, bps] of await modelTargets()) { try { await step(assetId, bps); stepped = true; } catch (err) { const name = revertName(err); if (name === "StepTooSoon") continue; // 30 s settle window on this asset if (name === "DailyTurnoverExceeded") break; // budget spent until 00:00 UTC if (name === "GrossLeverageExceeded" || name === "NetExposureExceeded" || name === "MarginRatioTooLow") { console.warn(`asset ${assetId}: ${name}, trim the target`); continue; } throw err; } } // 4. Keep the inactivity clock alive when nothing traded for a day. const idleFor = BigInt(Math.floor(Date.now() / 1000)) - s.lastActivityAt; if (!stepped && idleFor > 86_400n) await heartbeat(); } setInterval(() => tick().catch(console.error), 60_000); ``` ## Monitoring views | View | Returns | |---|---| | `state()` | `EngineState`: stops, flags, day-start equity, turnover, idle and pending USDC | | `totalEquityUsdc()` | Engine leg of NAV, USDC 1e6 | | `portfolioExposureBps(uint256 equity)` | `(uint256 grossBps, int256 netBps)` | | `currentMarginRatioBps()` | Equity over notional, bps | | `openAssets()` | Assets with a position or a resting order | | `isBridging()`, `isInactive()`, `canFlatten()`, `isFlat()` | Status flags | | `riskParams()`, `pendingRiskParams()`, `vaultDna()` | Current limits | The read API mirrors these at `GET /v1/vaults/{vault}/engine`, `/engine/orders`, `/engine/fills` and `/engine/events`. See [API](https://docs.degenhive.ai/api.md). ## Related - [Risk](https://docs.degenhive.ai/vaults/risk.md) Stops, latches and who may flatten. - [Create a vault](https://docs.degenhive.ai/vaults/create.md) Set the DNA and risk params the engine enforces. - [Deposits & withdrawals](https://docs.degenhive.ai/vaults/depositors.md) Daily rolls and settling queued redemptions. - [REST API](https://docs.degenhive.ai/api.md) Read engine state, orders, fills and events. --- # Risk rails > The risk rails on every vault, from DNA limits, the daily loss stop and the drawdown latch to flatten, wind-down and skin in the game. Source: https://docs.degenhive.ai/vaults/risk Every vault trades inside three layers of limits. DNA is permanent and set at creation. Risk params are the manager's execution knobs, which tighten at once and loosen only after 7 days. Platform caps come from the council through `HyperVaultConfig`. > [!IMPORTANT] > These contracts are not deployed yet and not externally audited. Addresses publish at launch on [Network](https://docs.degenhive.ai/network.md). ## The rails at a glance | Rail | Trigger | Effect | Cleared by | |---|---|---|---| | Daily loss stop | Equity falls `maxDailyLossBps` below the UTC day's start | Steps revert; anyone may flatten | The next UTC day, automatically | | Drawdown latch | Live share price falls `maxDrawdownBps` below the high-water mark | Steps, new deposits and `deployToEngine` revert; anyone may flatten | Council `clearDrawdownStop()` only | | Emergency flatten | Council `setEmergencyFlatten(true)` | Steps revert; anyone may flatten | Council `setEmergencyFlatten(false)` | | Inactivity | No step or heartbeat for `maxIdleSecs` | Anyone may flatten | The next step or `heartbeat()` | | Margin floor | Equity over notional below `minMarginRatioBps` | Gross-increasing steps revert; anyone may flatten | Margin back above the floor | | Wind-down | Manager or council `initiateWindDown()` | Reduce-only, no deposits; anyone may flatten | Never. It is permanent. | ## DNA limits DNA is copied into the engine at creation and has no setter. | Field | Bound | Enforced as | |---|---|---| | `maxGrossBps` | 5,000–50,000 (0.5x–5x), at most the tier cap | A step may not raise gross above it (`GrossLeverageExceeded`) | | `maxNetExposureBps` | At most `maxGrossBps` and the tier cap | A step may not raise absolute net above it (`NetExposureExceeded`) | | `maxDailyLossBps` | 50–1,000 (0.5%–10%) | Daily loss stop | | `maxDrawdownBps` | 200 to the tier cap; 0 (off) for flagships only | Drawdown latch | | `marketTier` | 1–3 | Which assets the vault may trade | | `vaultTier` | `FLAGSHIP`, `INSTITUTIONAL`, `COMMUNITY_ARENA` | Tier ceilings and the per-asset weight multiplier | Tier ceilings are on [Vaults](https://docs.degenhive.ai/vaults.md#tiers). ## Daily loss stop At the first engine call of each UTC day, the engine records day-start equity and clears the day's turnover. Every later step or flatten compares live equity with it: `Daily loss` ```math lossBps = (dayStartEquity - equity) * 10,000 / dayStartEquity ``` When `lossBps >= maxDailyLossBps`, the engine latches `dayLossStopped` for the rest of the UTC day and emits `DailyLossStopTriggered(day, startEquity, currentEquity)`. Steps then revert with `DayStopped()` and anyone may flatten. The stop clears at the first call of the next UTC day. Moving USDC between vault and engine rescales day-start equity, so deposits and withdrawals do not count as gains or losses. ## Drawdown latch The latch compares the vault's live share price (`livePricePerShare()`) with its high-water mark, the highest post-fee price any roll has set: `Drawdown` ```math drawdownBps = (peak - livePps) * 10,000 / peak ``` When `drawdownBps >= maxDrawdownBps`, the engine latches `drawdownStopped` and emits `DrawdownStopTriggered(highWaterMark, livePricePerShare, maxDrawdownBps)`. While latched: - steps revert with `DrawdownStopped()`; - `requestDeposit` and `deployToEngine` revert with `EngineDrawdownStopped()`; - anyone may flatten; - redemptions and claims continue. Only the council can clear it, with `clearDrawdownStop()`. Clearing re-anchors the peak at today's live price, so the vault can trade again without first recovering to the old high-water mark. The stored peak then rises with later rolls and returns to the high-water mark once a roll settles at or above it. USDC in flight between HyperEVM and HyperCore is added back to the live price, so a bridge does not trip the latch. > [!WARNING] > Both stops read one instant. `flatten` runs the day and drawdown checks before it checks whether flattening is allowed, so any caller can trip a stop from a single low reading and then close the book. Size `maxDailyLossBps` and `maxDrawdownBps` with intraday noise in mind. ## Emergency flatten `setEmergencyFlatten(bool active)` is a council switch on each engine. While it is on, steps revert with `DayStopped()` and anyone may flatten. It is reversible and has no delay. ## Inactivity flatten Every successful step records activity, and so does `heartbeat()`. `maxIdleSecs` (1 to 14 days by default bounds; never 0) sets how long a vault may sit with neither. After that, `isInactive()` is true and anyone may flatten. Nothing closes on its own: a keeper or any outside caller has to send the `flatten` transaction. A manager whose model intentionally holds positions should heartbeat at least once per `maxIdleSecs`. ## Margin floor `currentMarginRatioBps()` is equity over total notional, in bps. Below `minMarginRatioBps`: - a step that grows an asset's gross reverts with `MarginRatioTooLow(nextMarginRatioBps, minMarginRatioBps)`; - anyone may flatten. The council's floor on `minMarginRatioBps` is 1,000 bps by default (hard minimum 100). ## Flatten ```solidity function flatten(uint32[] calldata assetIds) external returns (uint256 ordersSent); function canFlatten() external view returns (bool); ``` `flatten` closes each listed asset in full with a reduce-only IOC order at `maxSlippageBps` and cancels its resting order. It is open to anyone while any of these holds: the daily loss stop, the drawdown latch (or a live breach), emergency flatten, wind-down, inactivity, or the margin floor. Otherwise it reverts with `Unauthorized()`. - Assets that are flat, have no price, are not listed in the signal book or already received an order this block are skipped, not reverted. - If closing the batch would raise absolute net above both its prior value and the DNA net cap, the call reverts with `NetExposureExceeded`. Pass hedged legs in the same call. - IOC orders at a slippage limit may fill partly. Call again until `isFlat()` is true. When withdrawals are unfunded, depositors have a second permissionless path, `forceDeleveraging` on the vault. See [Depositors](https://docs.degenhive.ai/vaults/depositors.md#unfunded-withdrawals). ## Wind-down `initiateWindDown()` on the vault closes it for good. On a third-party vault the manager or the council may call it; on a flagship, only the council. > [!WARNING] > Wind-down cannot be undone. The vault never accepts deposits or trades toward new positions again. From that moment: - `requestDeposit` and `deployToEngine` revert with `VaultWindingDown()`. Pending deposits are refunded at the next roll; depositors collect them with `claimWithdraw()` or cancel before it. - The engine sets `windingDown`. Every step targets 0, skips the turnover cap, and anyone may flatten. `bridgeUsdcToCore` reverts. - Rolls, fees, redemptions and claims continue as normal. - The factory lowers the manager's active vault count. The manager's own stake stays locked under the skin-in-the-game floor until 14 days after the wind-down, and then only once the withdrawal queue is empty, nothing is unfunded and the engine is flat. ## Markets and asset caps An asset is tradable for a vault when the council has listed it in `HyperVaultConfig` at a market tier no higher than the vault's `marketTier`, and it is listed in `HyperSignalBook`. Each asset's cap is a share of equity: 1. Start from the asset's override, or the tier default: 25% for tier 1, 10% for tier 2, 3% for tier 3. 2. Multiply by the vault tier's `assetWeightMultiplierBps` (1x, or 4x for `COMMUNITY_ARENA`) and cap at 100%. 3. On flagships, take the lower of that and the signal book market's `maxWeightBps`. 4. On assets HyperCore marks isolated-only, take the lower of that and the adapter's `isolatedCapBps`. CoreWriter cannot set margin mode, so a cap of 0 forces the asset flat. Targets are clamped to the cap. Portfolio limits come from DNA gross and net. If the council delists or downgrades an asset, existing positions can only be stepped to 0. A market paused in the signal book steps to 0 on its next step. ## Manager skin in the game When the council turns it on, a third-party manager must keep their own capital in the vault in proportion to outside money. The defaults in `SkinInGameConfig`: | Field | Default | |---|---| | `enabled` | `false` | | `coInvestMultiplier` | 20 (bounds 1–100) | | `freeStarterCapUsdc` | 50,000 USDC | | `dgvBondCreditBps`, `maxDgvShareOfBondBps` | 0. Locked DGV can count toward the stake at token launch. | `Outside capital limit` ```math maxExternalTvl = freeStarterCapUsdc + coInvestUsdc * coInvestMultiplier ``` `Manager stake floor` ```math minCoInvest = ceil((externalTvl - freeStarterCapUsdc) / coInvestMultiplier) ``` Example: a manager with 10,000 USDC in the vault may take up to 50,000 + 10,000 × 20 = 250,000 USDC from others. With 200,000 USDC of outside money, the floor is (200,000 − 50,000) / 20 = 7,500 USDC. - A deposit that would push outside money past the limit reverts with `VaultCapExceeded(afterTvl, cap)`. The manager's own deposits are exempt. - A manager redemption, share transfer or claim to another address that would leave less than the floor reverts with `ManagerCoInvestLocked(coInvestUsdc, minRequiredUsdc)`. - The council can exempt a vault with `setVaultCoInvestExempt`. ## Vault caps `setVaultCap(capUsdc)` limits NAV plus pending deposits. A manager may set up to `maxCapForManager(manager)` (2,000,000 USDC by default, or a council override); the council has no ceiling. `effectiveVaultCapUsdc()` returns the binding cap after skin in the game. A deposit over it reverts with `VaultCapExceeded(afterTvl, cap)`. Lowering the cap below current TVL only blocks new deposits. ## Changing risk params ```solidity function updateRiskParams(EngineRiskParams calldata next) external; // tighten now function scheduleRiskParams(EngineRiskParams calldata next) external; // any change, ready in 7 days function executeRiskParams() external; function cancelRiskParams() external; ``` The manager or the council may call these; the keeper may not. `updateRiskParams` reverts with `RiskLooseningRequiresTimelock()` if any field loosens. A change loosens when it: - lowers `minMarginRatioBps`; - raises or removes the turnover cap or the step cap; - raises `maxSlippageBps` or `makerOffsetBps`; - changes `defaultTif` to anything but IOC; - lengthens `maxIdleSecs`. `scheduleRiskParams` stores the change with `readyAt = now + 7 days` and replaces any pending one, which restarts the clock. `executeRiskParams` reverts with `TimelockNotReady(readyAt)` before then and `NoPendingPolicy()` with nothing pending, and it re-checks the params against the council's current bounds. Depositors can watch `pendingRiskParams()` and the `RiskParamsScheduled` event, and leave before a change they dislike takes effect. ## Related - [Trading](https://docs.degenhive.ai/vaults/trading.md) The guardrails each step runs. - [Depositors](https://docs.degenhive.ai/vaults/depositors.md) Withdrawals, unfunded epochs and wind-down refunds. - [Fees & high-water mark](https://docs.degenhive.ai/vaults/fees.md) How vault fees and high-water marks work. - [Networks & status](https://docs.degenhive.ai/network.md) Chains, deployment status and API discovery. --- # Fees & high-water mark > Management and performance fees on a vault, the waterfall that splits them, the locker rebate at token launch, and how fee terms change. Source: https://docs.degenhive.ai/vaults/fees A vault charges two fees, both in USDC and both at the daily roll: a yearly management fee on outside capital, and a performance fee on gains above the per-share high-water mark. `HyperVaultFeeRouter` splits each fee between the protocol, data providers, forecasters and the manager. There is no deposit or withdrawal fee. > [!IMPORTANT] > These contracts are not deployed yet and not externally audited. Addresses publish at launch on [Network](https://docs.degenhive.ai/network.md). > **Figure: Performance fee waterfall.** A third-party vault pays the protocol take first and its manager last; the Flagship pays royalties and forecasters first and the protocol last. > > At the top, the gross performance fee: perfFeeBps of the gain above the high-water mark. A dashed side branch marks the locker rebate, which starts at token launch and sends 20% of the gross fee to lockers first. The net fee then splits into two columns. Third-party vault, in order: 1. protocol take, default 20% of the fee, to HyperRevenueRouter; 2. data royalties on the rest, per feed, to DataProviderRegistry; 3. forecaster share, min(net × forecastShareBps, what is left), to HyperCrowdPay; 4. everything left to the manager's managerFeeRecipient. Flagship, in order: 1. data royalties to DataProviderRegistry; 2. forecaster share to HyperCrowdPay; 3. everything left to HyperRevenueRouter. A note below: the management fee skips the waterfall; the Flagship sends all of it to HyperRevenueRouter, and a third-party vault splits it into the protocol take and the manager's share. ## The numbers | Parameter | Bound | Set by | |---|---|---| | `mgmtFeeBps` | 0–200 per year | Manager or council at deploy; changes below | | `perfFeeBps` | 1,000–2,500 | Same | | `forecastShareBps` | 0–5,000 of the net performance fee | Same | | Protocol take (`protocolTakeBps`) | 2,000 by default, at most 5,000 | Council, `HyperVaultConfig.setProtocolTakeBps` | | Data royalty per feed | At most 500 bps of the royalty base | Provider terms, locked at subscribe | | Data royalties combined | At most 5,000 bps, at most 20 royalty feeds | `DataProviderRegistry` | | Locker rebate | 2,000 bps (20%) of the gross performance fee, at token launch | Constant `LP_REBATE_SHARE_OF_PERF_BPS` | Each vault picks its own fees inside these bounds. The Flagship runs 1% and 25%. ## Management fee The management fee accrues at each roll for every day since the last roll, on the share of NAV held by outside depositors: `Management fee per roll` ```math mgmtUsdc = extNav * mgmtFeeBps * daysElapsed / (10,000 * 365) ``` `extNav` is NAV times external shares over total supply. External shares exclude the protocol allocator's shares and the 1 dead share. Everyone else pays it, including the manager's own shares and shares waiting to redeem. ## Performance fee After the management fee, the roll prices a share. If that price is above the high-water mark, the vault charges `perfFeeBps` on the gain of every share: `Performance fee per roll` ```math perfUsdc = (ppsBeforePerf - highWaterMark) * totalSupply * perfFeeBps / 10,000 ``` The high-water mark is the highest post-fee share price any roll has set. It is never reset, so a vault that falls must recover all of it before it charges again. The fee is measured once per roll, at the NAV that roll reads. ## The waterfall The vault sends the management fee and the net performance fee to `HyperVaultFeeRouter`. Third-party and flagship vaults split them differently. | Leg | Third-party vault | Flagship vault | |---|---|---| | Management fee | `protocolTakeBps` to the protocol, the rest to the manager | 100% to the protocol | | Performance fee, step 1 | Protocol take: `net × protocolTakeBps` | No take | | Step 2 | Data royalties on what remains | Data royalties on the full net fee | | Step 3 | Forecasters: `min(net × forecastShareBps, remainder)` | Same | | Step 4 | The manager gets the rest | The protocol gets the rest | "Net" is the performance fee after the locker rebate; before the token there is no rebate, so net equals gross. The forecaster cut is a share of the whole net fee, capped by what royalties leave. Where each leg goes: - **Protocol** legs go to `HyperRevenueRouter.notifyRevenue`, which splits them across its lanes. See [Revenue](https://docs.degenhive.ai/revenue.md). - **Royalties** go to `DataProviderRegistry.settleVaultRoyalties`, credited to each royalty feed. See [Data](https://docs.degenhive.ai/data.md). - **Forecasters** receive theirs through `HyperCrowdPay.fundUsdc(jobId, today, amount)`, into the pot of the vault's `forecastJobId` for the day the fee is paid. See [Bonds and pay](https://docs.degenhive.ai/forecasters/bonds-and-pay.md). - **Manager** fees go to `managerFeeRecipient`. ## Worked example A third-party vault runs a 20% performance fee with the default 20% protocol take. It subscribes to one data feed with a 300 bps royalty and pays forecasters 10% (`forecastShareBps` 1,000). One roll finds 50,000 USDC of gain above the high-water mark, after the day's management fee. Before the token: | Leg | Calculation | USDC | |---|---|---| | Gross performance fee | 50,000 × 20% | 10,000 | | Protocol take | 10,000 × 20% | 2,000 | | Royalty base | 10,000 − 2,000 | 8,000 | | Data royalty | 8,000 × 3% | 240 | | Forecasters | min(10,000 × 10%, 7,760) | 1,000 | | Manager | 7,760 − 1,000 | 6,760 | Depositors keep 40,000 of the 50,000 gain. At token launch, if every share in the vault qualifies for the full rebate: | Leg | Calculation | USDC | |---|---|---| | Locker rebate to depositors | 10,000 × 20% | 2,000 | | Net performance fee | 10,000 − 2,000 | 8,000 | | Protocol take | 8,000 × 20% | 1,600 | | Data royalty | (8,000 − 1,600) × 3% | 192 | | Forecasters | min(8,000 × 10%, 6,208) | 800 | | Manager | 6,208 − 800 | 5,408 | The management fee on the same vault, with 1,000,000 USDC of outside NAV at 1% a year, is 1,000,000 × 100 / 3,650,000 = 27.40 USDC per day: 5.48 to the protocol and 21.92 to the manager. Try your own terms: > **Interactive simulator (HyperVaultFeeRouter fee waterfall):** Management fee `extNav * mgmtBps * days / (10000 * 365)` (mgmt 0..200 bps): Flagship 100% protocol; third-party `protocolTakeBps` (default 2000, max 5000) to protocol, rest to the manager. Performance fee `gain * perfBps / 10000` (1000..2500 bps); at token launch the vault offers 20% of it as an LP rebate and HyperBookRewards takes `offer * rebateShares / totalShares`, the rest is net. Net perf, third-party: take `net * protocolTakeBps`, then data royalties on the rest (max 5000 bps combined), then forecasters `min(net * forecastShareBps, rest)` (max 5000), then the manager gets the rest. Flagship: royalties on net, then forecasters, then the protocol gets the rest. Each protocol payment splits in HyperRevenueRouter: buyback 3167, locker 3166, NFT 500 bps (only while the NFT pot is live), ops the remainder. All steps floor in 6-decimal USDC. ## Locker rebate at token launch Once `HyperBookRewards` is live, each roll offers 20% of the gross performance fee back to depositors as USDC. `HyperBookRewards` takes the part that belongs to rebate-eligible shares. By default, a depositor whose locked DGV is worth at least 10% of their deposits earns the full rebate on their shares, and at least 5% earns half. Whatever it does not take joins the net performance fee and runs through the waterfall. Depositors claim with `claimUsdcRebate(vault)`. See [Token](https://docs.degenhive.ai/token.md). Before the token, `HyperBookRewards` is not set and no rebate is offered. ## Changing fee terms The fee gate is the manager or the council on a third-party vault, and the council alone on a flagship. Cuts are instant. Raises wait 7 days, so depositors can leave first. ```solidity function setFeePolicy(uint16 mgmtFeeBps, uint16 perfFeeBps) external; // cuts only, instant function submitFeePolicy(uint16 mgmtFeeBps, uint16 perfFeeBps, uint16 forecastShareBps, uint64 forecastJobId) external; function acceptFeePolicy() external; function revokePendingFeePolicy() external; function setForecastConfig(uint16 forecastShareBps, uint64 forecastJobId) external; ``` | Change | Path | |---|---| | Lower management or performance fee | `setFeePolicy`, instant. Also deletes any pending policy. | | Raise either fee | `submitFeePolicy`, then `acceptFeePolicy` between 7 and 10 days later | | Raise the forecaster share, same job | `setForecastConfig`, instant | | Lower the forecaster share, or switch job while the share is above 0 | `submitFeePolicy` with the 7-day wait | - `setFeePolicy` with a higher value reverts with `FeeRaiseRequiresTimelock()`. - `setForecastConfig` with a cut or a job switch reverts with `ForecastCutRequiresTimelock()`. The job must be 1 or bound to this vault (`InvalidForecastJob(jobId)`). - `acceptFeePolicy` reverts with `TimelockNotReady(validAt)` before day 7, `PolicyExpired(expiredAt)` after the 3-day window, and `NoPendingPolicy()` if nothing is queued. - A new `submitFeePolicy` replaces the pending one and restarts the clock. Watch `FeePolicySubmitted(mgmtFeeBps, perfFeeBps, forecastShareBps, forecastJobId, validAt)` to see a raise coming. The read API serves the current and pending policy at `GET /v1/vaults/{vault}/fee-policy`. ## When a fee cannot be paid Fees are liabilities outside NAV from the moment they accrue. The roll pays them from idle USDC, topped up from the engine's HyperEVM balance. A leg that cannot be paid stays owed and is retried. - **Retry.** Anyone can call `flushAccruedFees()` on the vault. The next roll also retries. - **Manager push failed.** The router holds the amount in `pendingManagerFees(recipient)`. The recipient collects it with `claimManagerFees(to)`. - **Forecaster pot refused.** The router holds it in `heldForecastUsdc(jobId)`. Anyone can call `retryForecast(jobId)` to fund that day's pot. If several performance fees are owed at once, they are paid under the oldest unpaid epoch and forecast terms. ## Events ```solidity // HyperVault event FeesFlushed(uint256 mgmtPaidUsdc, uint256 rebatePaidUsdc, uint256 perfPaidUsdc, uint256 mgmtOwedUsdc, uint256 rebateOwedUsdc, uint256 perfOwedUsdc); // HyperVaultFeeRouter event ManagementFeeRouted(address indexed vault, bool isFlagship, uint256 totalUsdc, uint256 protocolUsdc, uint256 managerUsdc); event NetPerfFeeRouted(address indexed vault, uint64 indexed epoch, uint64 feeDay, bool isFlagship, uint256 totalUsdc, uint256 protocolUsdc, uint256 royaltiesUsdc, uint256 forecastUsdc, uint64 forecastJobId, uint256 managerNetUsdc); event ManagerFeeDeferred(address indexed vault, address indexed recipient, uint256 amount, uint256 pendingUsdc); event ManagerFeesClaimed(address indexed owner, address indexed to, uint256 amount); event ForecastHeld(address indexed vault, uint64 indexed jobId, uint256 amount, uint256 heldUsdc); ``` ## Related - [Deposits & withdrawals](https://docs.degenhive.ai/vaults/depositors.md) How fees apply during each daily roll. - [Revenue](https://docs.degenhive.ai/revenue.md) Where the protocol's share goes. - [Data](https://docs.degenhive.ai/data.md) How royalty feeds are priced. - [Bonds and pay](https://docs.degenhive.ai/forecasters/bonds-and-pay.md) How forecasters are paid from the pot. --- # Deposits & withdrawals > The ERC-7540 request, roll and claim flow for depositing into and redeeming from a vault, with viem code and the read API. Source: https://docs.degenhive.ai/vaults/depositors A vault takes deposits and pays redemptions once a day. You request, the daily roll settles every request at one share price, and you claim. This page covers each call for depositors, wallets and integrators. > [!IMPORTANT] > Vaults are not deployed yet and not externally audited. `VAULT` and `USDC` in the code below are placeholders; addresses publish at launch on [Network](https://docs.degenhive.ai/network.md). > **Figure: A UTC day in a HyperVault.** Requests wait for the day's roll; the roll takes fees, prices shares and settles the queue, and the depositor claims afterwards. > > Left, during UTC day D: requestDeposit pulls USDC at once and can be cancelled until 00:00 UTC; requestRedeem moves shares to escrow and cannot be cancelled. Above them: the keeper or manager may roll from 00:00 UTC, anyone from 02:00 UTC. Middle: roll(), once per UTC day, in four steps: 1. take fees, management and performance above the high-water mark; 2. set pricePerShare and raise the high-water mark; 3. mint deposit shares into escrow for each controller; 4. settle withdrawals, up to 16 epochs per roll. Deposits feed step 3 and redemptions feed step 4. A dashed branch from step 4: if idle USDC is short, anyone may call forceDeleveraging, which bridges USDC from Core, trims positions and settles. Right: settled shares earn from the roll, before any claim. Then claim shares with deposit, mint or realize, and USDC with redeem, withdraw or claimWithdraw. ## The day | Time (UTC) | What happens | |---|---| | Day D | You call `requestDeposit` or `requestRedeem`. A deposit can still be cancelled. | | D+1, 00:00 | The roll is due. The cancel window for deposits queued on day D closes. | | D+1, 00:00 to 02:00 | The keeper, manager or council may roll. | | D+1, from 02:00 | Anyone may roll. | | After the roll | Your shares or USDC are claimable. | A request made after 00:00 but before that day's roll joins the next epoch and settles at the following roll. If nobody rolls for several days, the next roll settles everything queued. ## Request a deposit ```solidity function requestDeposit(uint256 assets, address controller, address owner) external returns (uint256 requestId); ``` The vault pulls `assets` USDC from `owner` at once, so approve the vault first. `controller` is the address that later claims the shares. Pending USDC sits outside NAV: it earns nothing and pays no fee. `requestId` is always 0, because requests are fungible per controller. Reverts: - `DepositBelowMinimum(amount, minAmount)`: below 10 USDC. - `VaultCapExceeded(afterTvl, cap)`: over the vault cap or the manager's skin-in-the-game limit. - `NotWhitelisted(account)`: a private vault, and the owner or controller is not on its list. - `VaultWindingDown()` or `EngineDrawdownStopped()`: the vault is closing, or its drawdown latch is set. - `BridgeInFlight()`: inside a 30-second bridge window. Retry shortly. - `RollPending()`: you already have a deposit pending in a different epoch. This happens when you request again after 00:00 before the roll. Wait for the roll. - `Unauthorized()`: the caller is neither `owner` nor an operator of `owner`. ### Cancel a pending deposit ```solidity function cancelDeposit() external returns (uint256 refunded); ``` Only the controller can cancel, and the refund goes to the controller. It works until 00:00 UTC of the day the deposit settles. After that it reverts with `RollPending()`; with nothing pending it reverts with `NothingPending()`. ## Claim your shares The roll mints your shares into the vault's escrow at the new share price. They are in the supply and earn from that moment, claimed or not. ```solidity function deposit(uint256 assets, address receiver, address controller) external returns (uint256 shares); function mint(uint256 shares, address receiver, address controller) external returns (uint256 assets); function realize(address user) external; ``` - `maxDeposit(controller)` returns the claimable USDC amount and `maxMint(controller)` the claimable shares. Pass either to `deposit` or `mint`. Partial claims work. - Two-argument `deposit(assets, receiver)` and `mint(shares, receiver)` use the caller as controller. - `realize(user)` called by the user or an operator delivers every claimable share to `user`. Anyone else calling it only moves settled epochs into the claimable state. - `previewDeposit` and the other `preview*` functions revert with `AsyncFlowOnly()`. Read `maxDeposit` and `position` instead. The ERC-4626 `Deposit` event fires at claim time, not at request time. ## Request a redemption ```solidity function requestRedeem(uint256 shares, address controller, address owner) external returns (uint256 requestId); ``` The owner, an operator of the owner, or a spender with a share allowance may call it. Shares move into escrow at once. They stay in the supply, so they keep gaining or losing and keep paying fees until the roll settles them. Redemptions are never paused and never whitelist-gated. > [!WARNING] > A redemption request cannot be cancelled. Once shares are in escrow, they leave the vault at the next roll price that can be paid. Reverts: `InsufficientShares()`, `InsufficientAllowance(allowed, needed)`, `RollPending()` or `WithdrawEpochPending()` (you already have a redemption pending in another epoch), and for the manager, `ManagerCoInvestLocked(coInvestUsdc, minRequiredUsdc)`. ## Settlement At the roll, the vault prices each pending redemption epoch at the new share price: `USDC owed for an epoch` ```math owed = shares * pricePerShare / 1e18 ``` It pays from idle USDC and pulls the rest from the engine's HyperEVM balance. Epochs settle in order, oldest first, up to 16 per call. The first epoch idle USDC cannot cover stops the line, and so does every later one. ## Unfunded withdrawals If the engine's capital is on HyperCore, a roll can leave redemptions unpaid. `unfundedWithdrawUsdc()` then returns the shortfall. Anyone can push it through: ```solidity function forceDeleveraging(uint32[] calldata assetIds, uint32 sourceDex) external returns (uint256 settledEpochs, uint256 ordersSent, bool bridgeTriggered); function settlePendingWithdrawals(uint256 maxEpochs) external returns (uint256 settled); ``` 1. Call `forceDeleveraging(assetIds, 4294967295)`. It settles what idle USDC covers, then asks the engine to send its HyperEVM idle, bridge what HyperCore can release, and trim the listed positions with reduce-only orders. Non-role callers always use `ANY_SOURCE` (`4294967295`), so the engine draws from spot, dex 0, then other dexes. 2. Wait for the bridged USDC to land. The bridge window is 30 seconds, and the engine allows one bridge and one trim every 2 minutes. 3. Call `settlePendingWithdrawals(0)` (0 means up to 16 epochs). Anyone may call it when it settles at least one epoch. Repeat both calls until `unfundedWithdrawUsdc()` is 0. Backlog epochs settle at the lower of the live share price and the last roll price. A redemption that waits through a backlog takes any loss in that time but no gain. `forceDeleveraging` reverts with `NothingUnfunded()` when there is nothing to fund and `BridgeInFlight()` inside a bridge window. ## Claim your USDC ```solidity function redeem(uint256 shares, address receiver, address controller) external returns (uint256 assets); function withdraw(uint256 assets, address receiver, address controller) external returns (uint256 shares); function claimWithdraw() external returns (uint256 paid); ``` - `maxRedeem(controller)` returns settled shares and `maxWithdraw(controller)` settled USDC. `redeem` and `withdraw` pay by share or by USDC amount, in part or in full. - `claimWithdraw()` pays the caller everything settled, plus any refunded deposits. Only the controller itself can call it. - With nothing claimable, they revert with `InsufficientClaimable()` or `NothingPending()`. There is no withdrawal fee. ## Code: deposit, then claim **viem** ```ts import { createPublicClient, createWalletClient, defineChain, erc20Abi, http, parseAbi, parseUnits, 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 USDC = process.env.USDC as Address; // placeholder, published at launch const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`); const publicClient = createPublicClient({ chain: hyperEvm, transport: http() }); const wallet = createWalletClient({ account, chain: hyperEvm, transport: http() }); export const vaultAbi = parseAbi([ "struct VaultPosition { uint256 shares; uint256 pendingDepositUsdc; uint64 pendingDepositEpoch; uint256 pendingRedeemShares; uint64 pendingRedeemEpoch; uint256 claimableDepositAssets; uint256 claimableDepositShares; uint256 claimableRedeemShares; uint256 claimableRedeemAssets; uint256 claimableRefundUsdc; bool whitelisted; }", "function requestDeposit(uint256 assets, address controller, address owner) returns (uint256)", "function cancelDeposit() returns (uint256)", "function maxDeposit(address controller) view returns (uint256)", "function deposit(uint256 assets, address receiver) returns (uint256)", "function requestRedeem(uint256 shares, address controller, address owner) returns (uint256)", "function maxRedeem(address controller) view returns (uint256)", "function redeem(uint256 shares, address receiver, address controller) returns (uint256)", "function claimWithdraw() returns (uint256)", "function position(address user) view returns (VaultPosition)", "function balanceOf(address account) view returns (uint256)", "function pricePerShareUsdc() view returns (uint256)", "function unfundedWithdrawUsdc() view returns (uint256)", "error DepositBelowMinimum(uint256 amount, uint256 minAmount)", "error VaultCapExceeded(uint256 afterTvl, uint256 cap)", "error NotWhitelisted(address account)", "error RollPending()", "error BridgeInFlight()", "error InsufficientClaimable()", ]); // 1. Approve and request. const assets = parseUnits("5000", 6); await publicClient.waitForTransactionReceipt({ hash: await wallet.writeContract({ address: USDC, abi: erc20Abi, functionName: "approve", args: [VAULT, assets] }), }); const { request } = await publicClient.simulateContract({ account, address: VAULT, abi: vaultAbi, functionName: "requestDeposit", args: [assets, account.address, account.address], }); await publicClient.waitForTransactionReceipt({ hash: await wallet.writeContract(request) }); // 2. After the next roll (from 00:00 UTC), claim everything that settled. const claimable = await publicClient.readContract({ address: VAULT, abi: vaultAbi, functionName: "maxDeposit", args: [account.address], }); if (claimable > 0n) { await wallet.writeContract({ address: VAULT, abi: vaultAbi, functionName: "deposit", args: [claimable, account.address] }); } ``` **cast** ```bash cast send $USDC "approve(address,uint256)" $VAULT 5000000000 --rpc-url $HYPEREVM_RPC --account me cast send $VAULT "requestDeposit(uint256,address,address)" 5000000000 $ME $ME --rpc-url $HYPEREVM_RPC --account me # after the roll CLAIMABLE=$(cast call $VAULT "maxDeposit(address)(uint256)" $ME --rpc-url $HYPEREVM_RPC) cast send $VAULT "deposit(uint256,address)" $CLAIMABLE $ME --rpc-url $HYPEREVM_RPC --account me ``` ## Code: redeem, then claim **viem** ```ts // Same clients and vaultAbi as deposit.ts. const shares = await publicClient.readContract({ address: VAULT, abi: vaultAbi, functionName: "balanceOf", args: [account.address], }); await wallet.writeContract({ address: VAULT, abi: vaultAbi, functionName: "requestRedeem", args: [shares, account.address, account.address], }); // After the roll. If the vault is short, anyone can call forceDeleveraging first. const unfunded = await publicClient.readContract({ address: VAULT, abi: vaultAbi, functionName: "unfundedWithdrawUsdc" }); const settled = await publicClient.readContract({ address: VAULT, abi: vaultAbi, functionName: "maxRedeem", args: [account.address], }); if (settled > 0n) { await wallet.writeContract({ address: VAULT, abi: vaultAbi, functionName: "redeem", args: [settled, account.address, account.address], }); } else if (unfunded > 0n) { console.log(`redemptions short by ${unfunded} (USDC 1e6); see Unfunded withdrawals`); } ``` **cast** ```bash SHARES=$(cast call $VAULT "balanceOf(address)(uint256)" $ME --rpc-url $HYPEREVM_RPC) cast send $VAULT "requestRedeem(uint256,address,address)" $SHARES $ME $ME --rpc-url $HYPEREVM_RPC --account me # after the roll: pay out everything settled for you cast send $VAULT "claimWithdraw()" --rpc-url $HYPEREVM_RPC --account me ``` ## Operators ```solidity function setOperator(address operator, bool approved) external returns (bool); function isOperator(address controller, address operator) external view returns (bool); ``` An operator acts for you: it can request deposits from your USDC, request redemptions of your shares, and claim to any receiver. Approval is a transaction; the vault has no signature-based operator approval. `cancelDeposit` and `claimWithdraw` stay with you alone. Setting yourself or the zero address reverts with `InvalidPolicy()`. ## Private vaults A vault with `whitelistEnabled` accepts deposit requests only when both owner and controller are on its list. Claiming shares to a different receiver needs that receiver listed too. With `whitelistTransfers` also on, shares can only be sent to listed addresses. Redemptions and redemption claims are never gated. The compliance admin, the manager or the council edits the list with `setWhitelistedLp(lp, allowed)`. Check your status in `position(user).whitelisted`. ## Share transfers Shares are an ERC-20 with 6 decimals; the token address is the vault. `transfer` and `transferFrom` work as usual, with these limits: - On a private vault with `whitelistTransfers`, the receiver must be listed (`NotWhitelisted`). - The protocol allocator cannot send or receive shares. - A third-party manager cannot transfer below their skin-in-the-game floor (`ManagerCoInvestLocked`). At token launch, deposits, claims and transfers also notify `HyperBookRewards`. These calls revert with `HookGasTooLow()` unless at least 530,000 gas is left for the hook. Estimate gas rather than setting a tight limit. ## Wind-down refunds If the manager or council winds a vault down, pending deposits are not converted. The next roll refunds them in full, and you collect the USDC with `claimWithdraw()`. You can also cancel before that roll. Redemptions, claims and rolls carry on as usual until the vault is empty. See [Risk](https://docs.degenhive.ai/vaults/risk.md#wind-down). ## Reading state On-chain, `position(user)` returns everything about one account: ```solidity struct VaultPosition { uint256 shares; // in your wallet uint256 pendingDepositUsdc; uint64 pendingDepositEpoch; uint256 pendingRedeemShares; uint64 pendingRedeemEpoch; uint256 claimableDepositAssets; uint256 claimableDepositShares; uint256 claimableRedeemShares; uint256 claimableRedeemAssets; uint256 claimableRefundUsdc; bool whitelisted; } ``` Other views: `pricePerShare()` (1e18 = 1 USDC per share), `pricePerShareUsdc()`, `highWaterMark()`, `totalAssets()`, `rollDue()`, `currentEpoch()`, `lastRollDay()`, `unfundedWithdrawUsdc()`. The read API at `https://api.degenhive.ai/v1` serves the same data without a node. No key is needed; the limit is 300 requests per 60 seconds per IP. Amounts are base-unit integer strings. `GET https://api.degenhive.ai/v1/vaults/{vault}/positions/{account}` Shares, value at the last share price, pending deposit and redemption with their epochs, and claimable USDC for one account. `GET https://api.degenhive.ai/v1/vaults/{vault}` Vault detail: tier, TVL, share price, high-water mark, fees, engine, last roll and forecast job. `GET https://api.degenhive.ai/v1/vaults/{vault}/withdraw-epochs` Settled redemption epochs with their shares, USDC and price. ```bash curl -s https://api.degenhive.ai/v1/vaults/$VAULT/positions/$ME curl -s "https://api.degenhive.ai/v1/vaults/$VAULT/rolls?limit=7" ``` ## Related - [Vaults](https://docs.degenhive.ai/vaults.md) Tiers, roles and the daily epoch. - [Fees](https://docs.degenhive.ai/vaults/fees.md) What the roll charges and where it goes. - [Risk rails](https://docs.degenhive.ai/vaults/risk.md) Stops, drawdown latches and wind-down protections. - [API](https://docs.degenhive.ai/api.md) The full read API. --- # Data marketplace > How data providers sell feeds to vaults through DataProviderRegistry, with prepaid daily fees, performance royalties and on-chain access checks. Source: https://docs.degenhive.ai/data The data marketplace lets anyone sell a data feed to vault managers. `DataProviderRegistry` on HyperEVM (chain 999) records each feed's terms, holds prepaid USDC in escrow, collects royalties from vault fees and answers one question for the provider's API: does this vault have access right now? > [!IMPORTANT] > The registry is not deployed yet and not externally audited. Addresses publish at launch on [Network](https://docs.degenhive.ai/network.md). ## How it works 1. A provider calls `registerProvider` with a payout address, a daily price, a royalty share and a metadata URI. It receives a `providerId`. 2. A vault's manager subscribes for a number of days, paying the prepaid fee from their own wallet into escrow. Terms lock at that moment. 3. The vault names a data key. The provider's API asks the registry whether a signer may read the feed with `verifyAccess`. See [Gating access](https://docs.degenhive.ai/data/access.md). 4. Prepaid USDC streams to the provider every second of the subscription. Royalties arrive each time the vault pays a performance fee. 5. Anyone calls `claim` to send what the provider earned to its payout address. Only vaults deployed by `HyperVaultFactory`, or vaults the council allowlists, can subscribe. The data never touches the chain: the registry handles terms, money and access, and the provider serves the data from its own API. ## Two ways to charge A feed can use either model or both. | | Prepaid daily fee | Performance royalty | |---|---|---| | Term | `dailyUsdcFee` | `managerShareBps` | | Who pays | The subscriber's wallet, into escrow | The vault's performance fee, at each fee flush | | When the provider earns | Linearly, second by second, while access is live | Only when the vault earns a performance fee | | Bound | Any amount, 0 allowed. Up to `maxPrepaidDays` (default 90, at most 365) ahead. | At most 500 bps (5%) of the royalty base | | Marketplace take | Up to 1,000 bps, locked at subscribe | None | The royalty base is the vault's net performance fee after the protocol take on a third-party vault, or the full net performance fee on a flagship. A feed with a 300 bps royalty on a vault whose base is 8,000 USDC earns 240 USDC that roll. See the [fee waterfall](https://docs.degenhive.ai/vaults/fees.md#the-waterfall). Per-vault limits on royalties: | Limit | Value | |---|---| | Royalty per feed | 500 bps (`MAX_PROVIDER_SHARE_BPS`) | | Royalty feeds per vault | 20 (`MAX_ROYALTY_FEEDS_PER_VAULT`). Prepaid-only feeds are unlimited. | | Royalties combined per vault | 5,000 bps (`MAX_COMBINED_ROYALTY_BPS`) | ## Marketplace take The council sets `marketplaceTakeBps`, from 0 (the default) to 1,000 bps (10%). It applies to prepaid fees only. Each subscription locks the take that applied when it started; renewals blend the old and new take by escrow. The take collects in `claimableMarketplaceFees`, and anyone can send it to `HyperRevenueRouter.notifyRevenue` with `claimMarketplaceFees()`. Royalties carry no take. ## Approval-required feeds A provider that registers with `approvalRequired = true` chooses its subscribers. A vault must be approved with `setProviderApproval(providerId, vault, true)` before it subscribes, or `subscribe` reverts with `VaultNotApproved(vault, providerId)`. Use it for feeds with licensing limits or capacity caps. ## Badges The council can mark a feed `VERIFIED` or `FLAGSHIP_BOOTSTRAP` with `setProviderBadge`. Every feed starts `UNVERIFIED`. `VERIFIED` means the council checked that the provider controls the actual data source. A badge is display only: no contract logic reads it, and it changes no terms. ## Suspension The council can suspend a provider with `setProviderActive(providerId, false)`. While suspended: - `verifyAccess` returns false for every subscriber; - prepaid streams pause and no royalties accrue; - managers can cancel for a full refund of their remaining escrow. When the council lifts the suspension, the suspended time is added to every subscription, so subscribers lose no paid days. A provider deactivating its own feed is different: it only blocks new subscriptions, and live ones keep access and billing. ## Reading the marketplace The read API at `https://api.degenhive.ai/v1` lists providers, subscriptions and royalty payments under `/v1/data/*`. See [API](https://docs.degenhive.ai/api.md). ## Related - [Publish a feed](https://docs.degenhive.ai/data/publish-a-feed.md) Register a provider, get subscribers and get paid. - [Gating access](https://docs.degenhive.ai/data/access.md) Check subscribers in your API with `verifyAccess`. - [REST API](https://docs.degenhive.ai/api.md) Read providers, subscriptions and royalty payouts. - [Fees](https://docs.degenhive.ai/vaults/fees.md) Where royalties sit in the vault fee waterfall. --- # Publish a feed > Register a data feed in DataProviderRegistry, describe it with a manifest, approve vaults, take subscriptions, claim earnings and end subscriptions. Source: https://docs.degenhive.ai/data/publish-a-feed This guide lists a data feed in the marketplace, takes a vault's subscription and collects the USDC it earns. You need a HyperEVM (chain 999) wallet with HYPE for gas, a payout address, and an API that serves your data. Registering is free and open to any address. > [!IMPORTANT] > The registry is not deployed yet. `REGISTRY`, `USDC` and `VAULT` below are placeholders; addresses publish at launch on [Network](https://docs.degenhive.ai/network.md). ## Step 1: Write a manifest `registerProvider` stores one free-form string, `metadataUri`. The registry pins no hash and never reads the content. Managers and the app read it to learn what you sell and how to connect. The shape below is a recommended convention, not a rule the contracts enforce. Host it at a content-addressed URI (IPFS or Arweave) so subscribers can trust it has not changed under them. `manifest.json (recommended convention)` ```json { "name": "Funding Skew 1m", "description": "One-minute funding-rate skew and open-interest deltas for HyperCore perps.", "provider": { "name": "Example Data Co", "url": "https://example.com", "contact": "data@example.com" }, "api": { "baseUrl": "https://api.example.com/v1", "auth": "verifyAccess-challenge", "challengeUrl": "https://api.example.com/v1/auth/challenge", "docsUrl": "https://example.com/docs" }, "datasets": [ { "id": "funding-skew", "assets": "all HyperCore perps on dex 0", "frequency": "60s", "history": "2023-06-01 onward", "format": "json" } ], "terms": "https://example.com/terms", "sample": "https://example.com/sample.json" } ``` On-chain terms (price, royalty, approvals) always come from the registry, never from the manifest. Keep prices out of it, or mark them as informational. ## Step 2: Register the provider ```solidity struct ProviderParams { address payoutRecipient; // receives every payout; not zero uint256 dailyUsdcFee; // prepaid price per day, USDC 1e6; 0 for royalty-only uint16 managerShareBps; // royalty on the vault's royalty base, at most 500 uint32 maxPrepaidDays; // 0 means 90; at most 365 bool approvalRequired; // vaults need your approval to subscribe string metadataUri; } function registerProvider(ProviderParams calldata p) external returns (uint64 providerId); ``` **viem** ```ts import { createPublicClient, createWalletClient, defineChain, http, parseAbi, parseEventLogs, parseUnits, 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 REGISTRY = process.env.REGISTRY as Address; // DataProviderRegistry, published at launch const PAYOUT = process.env.PAYOUT as Address; const account = privateKeyToAccount(process.env.PROVIDER_KEY as `0x${string}`); const publicClient = createPublicClient({ chain: hyperEvm, transport: http() }); const wallet = createWalletClient({ account, chain: hyperEvm, transport: http() }); export const registryAbi = parseAbi([ "struct ProviderParams { address payoutRecipient; uint256 dailyUsdcFee; uint16 managerShareBps; uint32 maxPrepaidDays; bool approvalRequired; string metadataUri; }", "function registerProvider(ProviderParams p) returns (uint64 providerId)", "function updateProvider(uint64 providerId, ProviderParams p)", "function setProviderApproval(uint64 providerId, address vault, bool approved)", "function claim(uint64 providerId, address[] vaults) returns (uint256 totalPaid)", "function cancel(address vault, uint64 providerId) returns (uint256 refundedUsdc)", "function finalize(address vault, uint64 providerId) returns (uint256 refundedUsdc)", "event ProviderRegistered(uint64 indexed providerId, address indexed owner, address indexed payoutRecipient, uint256 dailyUsdcFee, uint16 managerShareBps, uint32 maxPrepaidDays, bool approvalRequired, string metadataUri)", "error InvalidPolicy()", "error ZeroAddress()", ]); const { request } = await publicClient.simulateContract({ account, address: REGISTRY, abi: registryAbi, functionName: "registerProvider", args: [{ payoutRecipient: PAYOUT, dailyUsdcFee: parseUnits("20", 6), // 20 USDC per day managerShareBps: 200, // plus 2% of the vault's royalty base maxPrepaidDays: 0, // default: 90 days approvalRequired: false, metadataUri: "ipfs://bafy.../manifest.json", }], }); const receipt = await publicClient.waitForTransactionReceipt({ hash: await wallet.writeContract(request) }); const [registered] = parseEventLogs({ abi: registryAbi, eventName: "ProviderRegistered", logs: receipt.logs }); console.log("providerId", registered.args.providerId); ``` **cast** ```bash cast send $REGISTRY "registerProvider((address,uint256,uint16,uint32,bool,string))" \ "($PAYOUT,20000000,200,0,false,ipfs://bafy.../manifest.json)" \ --rpc-url $HYPEREVM_RPC --account provider ``` The caller becomes the provider's owner. The feed starts active with the `UNVERIFIED` badge. Provider ids count from 1. Reverts: `ZeroAddress()` for a zero payout address; `InvalidPolicy()` for a royalty above 500 bps or `maxPrepaidDays` above 365. ## Step 3: Approve vaults Skip this step if `approvalRequired` is false. Otherwise approve each vault before it subscribes: **viem** ```ts await wallet.writeContract({ address: REGISTRY, abi: registryAbi, functionName: "setProviderApproval", args: [providerId, VAULT, true], }); ``` **cast** ```bash cast send $REGISTRY "setProviderApproval(uint64,address,bool)" $PROVIDER_ID $VAULT true --rpc-url $HYPEREVM_RPC --account provider ``` Revoking an approval stops new subscriptions and renewals from that vault; it does not end a live one. To end one, use `cancel` (last step). ## Step 4: Let vaults subscribe The vault side calls `subscribe`. On a third-party vault, the strategy manager or the council may call it; on a flagship, only the council. The prepaid fee comes from the caller's wallet, not from vault assets. ```solidity function subscribe(address vault, uint64 providerId, uint32 numDays, uint256 maxDailyUsdcFee, uint16 maxShareBps) external; ``` **cast** ```bash # manager: approve numDays * dailyUsdcFee, then subscribe for 30 days cast send $USDC "approve(address,uint256)" $REGISTRY 600000000 --rpc-url $HYPEREVM_RPC --account manager cast send $REGISTRY "subscribe(address,uint64,uint32,uint256,uint16)" $VAULT $PROVIDER_ID 30 20000000 200 \ --rpc-url $HYPEREVM_RPC --account manager ``` `maxDailyUsdcFee` and `maxShareBps` protect the subscriber: if your live terms exceed them, `subscribe` reverts with `TermsExceeded()`. Terms lock when the subscription starts. Other reverts a manager can hit: | Revert | Cause | |---|---| | `UnauthorizedVault(vault)` | Not a factory vault and not allowlisted | | `ProviderInactive(providerId)` | You deactivated the feed, or the council suspended it | | `VaultNotApproved(vault, providerId)` | Approval required and not given | | `InvalidPolicy()` | `numDays` is 0, or the paid time would run past `maxPrepaidDays` | | `MaxFeedsReached(vault)` | The vault already has 20 royalty feeds | | `MaxCombinedShareExceeded(vault, combinedBps)` | Royalties on the vault would pass 5,000 bps | | `ProviderTerminating(vault, providerId)` | You gave notice on this subscription; it must be finalized first | Renewal is the same call. While escrow remains, only the original payer can renew, at the locked daily fee. ## Step 5: Serve the data The vault names one data key for all its feeds with `setVaultDataKey`. Your API accepts requests signed by that key, the vault's keeper or its manager, and checks each one with `verifyAccess(vault, providerId, signer)`. [Gating access](https://docs.degenhive.ai/data/access.md) has a full challenge and response example. ## Step 6: Collect what you earn ```solidity function claim(uint64 providerId, address[] calldata vaults) external returns (uint256 totalPaid); ``` Anyone can call `claim`. For each vault listed, it settles the prepaid stream up to now (finalizing subscriptions that are ready). Then it pays all of `claimablePrepaid + claimableRoyalties` to your payout address. Royalties need no vault list: the fee router credits them at each vault's fee flush. **viem** ```ts const hash = await wallet.writeContract({ address: REGISTRY, abi: registryAbi, functionName: "claim", args: [providerId, [VAULT_A, VAULT_B]], }); await publicClient.waitForTransactionReceipt({ hash }); ``` **cast** ```bash cast send $REGISTRY "claim(uint64,address[])" $PROVIDER_ID "[$VAULT_A,$VAULT_B]" --rpc-url $HYPEREVM_RPC --account provider ``` It reverts with `ZeroAmount()` when there is nothing to pay. Read `provider(providerId)` for settled balances, and `subscription(vault, providerId).accruedPrepaid` for what has streamed but not yet settled. The `Subscribed` and `RoyaltySettled` events, or `GET /v1/data/subscriptions` on the [API](https://docs.degenhive.ai/api.md), list your subscribers. ## Step 7: Change terms or ownership - `updateProvider(providerId, params)` changes price, royalty, payout address, approval mode or manifest. New terms apply to new subscriptions and renewals only. - `setProviderActive(providerId, false)` stops new subscriptions. Live subscriptions keep access and keep paying. - `transferProviderOwnership(providerId, newOwner)` hands the feed to another address in one step. Check the address twice; there is no accept step. ## Step 8: End a subscription Either side can end a subscription with the same function, `cancel(vault, providerId)`. The registry tells the sides apart by caller. | Who cancels | Effect | |---|---| | You (provider owner) | Notice period: access ends at the earlier of `paidUntil` and 7 days from now. The prepaid stream settles first. A second notice reverts with `AlreadyCancelled()`. | | The manager | Access ends now and the remaining escrow is refunded at once. A royalty feed still earns on every vault epoch before the next one. | After access ends and the vault has rolled past it, anyone calls `finalize(vault, providerId)`. It settles what you earned, refunds unstreamed escrow to the payer and deletes the subscription. A subscription that simply lapses can be finalized a day after `paidUntil`, once no performance fee is still pending. Until then, `finalize` reverts with `NotReadyToFinalize()`. ## Step 9: Where to go next - [Gating access](https://docs.degenhive.ai/data/access.md) Authenticate subscribers in your API. - [Data marketplace](https://docs.degenhive.ai/data.md) Pricing models, take, badges and suspension. - [Fees](https://docs.degenhive.ai/vaults/fees.md) How performance royalties flow from vaults. - [API](https://docs.degenhive.ai/api.md) Read providers and subscriptions without a node. --- # Gate access to a feed > Let only paying vaults read your feed. Vaults name a data key; your API checks signers on-chain with verifyAccess. Source: https://docs.degenhive.ai/data/access A provider's API decides who may read the feed. `DataProviderRegistry.verifyAccess` answers the on-chain half: is this signer allowed to read this feed for this vault, and until when. Proving that a request really comes from that signer is your API's job, off-chain. > [!IMPORTANT] > The registry is not deployed yet. `REGISTRY` below is a placeholder; addresses publish at launch on [Network](https://docs.degenhive.ai/network.md). > **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. ## Who may sign Each vault has one data key for every feed it buys. The manager or the council sets it: ```solidity function setVaultDataKey(address vault, address dataKey) external; function vaultDataKey(address vault) external view returns (address); event VaultDataKeySet(address indexed vault, address indexed dataKey); ``` `verifyAccess` accepts three signers for a vault: | Signer | Where it comes from | |---|---| | The data key | `vaultDataKey(vault)` | | The keeper | `vault.keeper()` | | The strategy manager | `vault.strategyManager()` | Give the data key to the process that fetches data, and keep the manager key cold. Rotating is one call to `setVaultDataKey`, and the old key fails `verifyAccess` from the next block. ## The on-chain check ```solidity function verifyAccess(address vault, uint64 providerId, address signer) external view returns (bool active, uint64 paidUntil); function isAccessActive(address vault, uint64 providerId) external view returns (bool); ``` `verifyAccess` returns `(true, endTs)` when all of these hold, and `(false, 0)` otherwise: - `signer` is not zero and is one of the three signers above; - the vault has a live subscription to `providerId` that the manager has not cancelled; - the provider is not suspended by the council; - now is before the end of paid time, and before the end of any notice the provider gave. The second value, named `paidUntil` in the ABI, is the moment access ends. It already includes time credited back after a suspension and the cut-off from a provider's notice. It is a view call: free, and you can make it against any HyperEVM RPC. ## A challenge and response The contracts verify no signatures, so the handshake is yours to design. The pattern below is a recommended one, not a protocol rule: the server issues a one-time nonce, the subscriber signs it with the data key, the server recovers the signer and asks the registry. 1. The client asks for a challenge for its vault and your `providerId`. 2. Your server returns a message with your API's host, the vault, the provider id, a random nonce and an expiry. 3. The client signs the message with the data key (EIP-191 `personal_sign`). 4. Your server recovers the address, checks the nonce is fresh and unused, then calls `verifyAccess(vault, providerId, recovered)`. 5. If access is active, the server issues a short session token that expires no later than `paidUntil`. **server** ```ts import { createPublicClient, defineChain, http, parseAbi, recoverMessageAddress, type Address, type Hex } from "viem"; import { randomBytes } from "node:crypto"; const hyperEvm = defineChain({ id: 999, name: "HyperEVM", nativeCurrency: { name: "HYPE", symbol: "HYPE", decimals: 18 }, rpcUrls: { default: { http: ["https://rpc.hyperliquid.xyz/evm"] } }, }); const REGISTRY = process.env.REGISTRY as Address; // DataProviderRegistry, published at launch const PROVIDER_ID = BigInt(process.env.PROVIDER_ID!); const HOST = "api.example.com"; const client = createPublicClient({ chain: hyperEvm, transport: http() }); const registryAbi = parseAbi([ "function verifyAccess(address vault, uint64 providerId, address signer) view returns (bool active, uint64 paidUntil)", ]); const nonces = new Map(); // nonce -> expiry (ms). Use a shared store in production. export function challenge(vault: Address) { const nonce = randomBytes(16).toString("hex"); const expires = Date.now() + 5 * 60_000; nonces.set(nonce, expires); const message = [ `${HOST} data access`, `provider: ${PROVIDER_ID}`, `vault: ${vault.toLowerCase()}`, `nonce: ${nonce}`, `expires: ${new Date(expires).toISOString()}`, ].join("\n"); return { message }; } export async function verify(vault: Address, message: string, signature: Hex) { const fields = Object.fromEntries(message.split("\n").slice(1).map((l) => l.split(": "))); const expires = nonces.get(fields.nonce); nonces.delete(fields.nonce); // one use only if (!expires || Date.now() > expires) throw new Error("challenge expired or unknown"); if (fields.provider !== PROVIDER_ID.toString() || fields.vault !== vault.toLowerCase()) { throw new Error("challenge does not match this request"); } const signer = await recoverMessageAddress({ message, signature }); const [active, paidUntil] = await client.readContract({ address: REGISTRY, abi: registryAbi, functionName: "verifyAccess", args: [vault, PROVIDER_ID, signer], }); if (!active) throw new Error("no active subscription for this signer"); // Session ends at the earlier of 15 minutes or the end of paid access. const sessionEnd = Math.min(Date.now() + 15 * 60_000, Number(paidUntil) * 1000); return { signer, vault, sessionEnd }; } ``` **client** ```ts import { privateKeyToAccount } from "viem/accounts"; const dataKey = privateKeyToAccount(process.env.DATA_KEY as `0x${string}`); const VAULT = process.env.VAULT as `0x${string}`; const { message } = await fetch(`https://api.example.com/v1/auth/challenge?vault=${VAULT}`).then((r) => r.json()); const signature = await dataKey.signMessage({ message }); const { token } = await fetch("https://api.example.com/v1/auth/verify", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ vault: VAULT, message, signature }), }).then((r) => r.json()); const data = await fetch("https://api.example.com/v1/funding-skew", { headers: { authorization: `Bearer ${token}` }, }).then((r) => r.json()); ``` Notes on the pattern: - **Bind the message to your host and provider id.** A signature made for one provider then cannot be replayed at another. - **Use each nonce once and expire it quickly.** Store nonces where every API instance can see them. - **Keep sessions short.** A manager cancel, a council suspension or your own notice ends access before `paidUntil`. Re-run `verifyAccess` when a session ends, or check `isAccessActive(vault, providerId)` on a timer for long-lived connections such as WebSockets. - **Contract signers.** `recoverMessageAddress` covers externally owned keys. If you want to accept a manager that is a smart-contract wallet, have the client send its address too and check the signature with `client.verifyMessage({ address, message, signature })`, which also handles ERC-1271 wallets. Then call `verifyAccess` with that address. ## Edge cases | Situation | What `verifyAccess` returns | |---|---| | Subscription not yet started, or finalized | `(false, 0)` | | Manager cancelled | `(false, 0)` from that moment | | Provider gave notice | `(true, end)` until the notice ends, then `(false, 0)` | | Council suspended the provider | `(false, 0)` for every vault until the suspension lifts; paid time is credited back | | Paid time ran out | `(false, 0)`, even before anyone calls `finalize` | | Keeper or manager changed on the vault | The new address passes at once; the old one fails | ## Related - [Publish a feed](https://docs.degenhive.ai/data/publish-a-feed.md) Register a feed and collect subscriptions. - [Data marketplace](https://docs.degenhive.ai/data.md) Pricing models, take, badges and suspension. - [REST API](https://docs.degenhive.ai/api.md) Query active subscriptions without a node. - [Vaults](https://docs.degenhive.ai/vaults.md) Roles on a vault: manager, keeper and council. --- # Stock pools (PropAMM) > How the Robinhood Chain PropAMM prices stock-token swaps against USDG with a hook-owned Uniswap v4 pool, a fair-value shield and a daily breaker. Source: https://docs.degenhive.ai/pools The PropAMM is DegenHive's market for Stock Tokens on Robinhood Chain (4663). Each stock trades against USDG in one Uniswap v4 pool, `MakerHook` is that pool's only liquidity provider, and every swap fee is set inside the hook. > [!IMPORTANT] > The contracts on this page are not deployed yet and not externally audited. Addresses publish at launch on [Network](https://docs.degenhive.ai/network.md). ## How it works Five contracts run the market on Robinhood Chain: | Contract | Role | |---|---| | `MakerHook` | The v4 hook for every Stock Token/USDG pool, one pool per stock. It alone adds or removes liquidity, blocks `donate`, enforces the `DOMAIN_ENTRY` pause, and computes each swap's dynamic LP fee on both `MakerHook.swap` and router swaps. | | `MakerQuoter` | Read-only (`eth_call`) quoter (`quoteExactInput` and `quoteExactOutput`) that simulates the real swap fee path and returns exact output, fee paid and post-swap tick. | | `MakerPilot` | The on-chain engine. Anyone calls `step(poolId)`; it sets fees, layout and auction start fees inside the guard policy bounds. | | `BookVault` | One per pool. LPs deposit stock and USDG; the book owns everything the hook holds for that pool. See [Provide liquidity](https://docs.degenhive.ai/pools/liquidity.md). | | `HiveFund` | The protocol's own allocator across books. It deposits like any LP through `allocate()`, once per UTC day. | An off-chain poster, the `fairValueUpdater`, sends `updateFairTick(poolId, fairTick)` with the stock's reference price. When entry is paused (`DOMAIN_ENTRY`), swaps and deposits revert while withdrawals continue to work. > **Figure: How MakerHook prices a swap.** MakerHook builds each swap's dynamic LP fee from seven layers on both MakerHook.swap and any v4 router, with inputs from MakerPilot and the fair-value poster, over liquidity only the hook holds. > > Center, MakerHook's seven-layer dynamic LP fee stack: 1. engine ask or bid fee; 2. fair-value shield; 3. router discount; 4. inventory skew; 5. size surcharge; 6. calendar floor and reopen auction; 7. a cap of 999,999 pips. The fee builds from rows 1 to 6 and never exceeds row 7. Left: a swapper calls MakerHook.swap or any v4 router, and both paths check the entry pause, apply the same seven-layer fee stack and emit SwapFeeCharged. Right: MakerPilot.step sets fees, layout and auctions inside the guard policy and feeds row 1; fairValueUpdater posts updateFairTick, fresh for maxStaleSecs, and feeds rows 2 and 3, which apply only while the fair tick is fresh. Bottom: BookVault books, one per pool, supply all the liquidity, and only MakerHook can add or remove it. ## The swap fee Every swap, through `MakerHook.swap` or any v4 router, applies the same dynamic LP fee in pips (1,000,000 pips = 100%) built in this order: | Part | What it does | |---|---| | Engine fee | `askPips` for buyers of the stock, `bidPips` for sellers, set by the engine. | | Fair-value shield | Arbitrage toward a fresh fair tick pays a surcharge; flow away from it gets `rebDiscountBps` off. | | Router discount | A per-router discount (up to 8,000 bps), only while the fair tick is fresh and the trade is not arbitrage. It tapers to zero with trade size. | | Inventory skew | Flow that reduces the pool's drift from its day-start stock/USDG mix gets up to `invRebDiscountBps` off; flow that worsens it pays up to `invWorsenMaxPips` more. | | Floor | The fee never drops below a quarter of the engine fee. | | Size surcharge | Trades above `sizeThresholdBps` of pool depth pay up to `maxSizeFeePips` extra. | | Calendar floor | The fee is at least the closed-hours fee or the running auction fee, whichever is higher. | | Cap | 999,999 pips. | The hook emits `SwapFeeCharged(poolId, sender, zeroForOne, amountSpecified, parts)` with each part, so integrators can see what a trade paid. ### Fair-value shield The shield is fresh while `block.timestamp <= updatedAt + maxStaleSecs`, with `maxStaleSecs` at most 3,600 seconds. Each update moves at most 500 ticks from the last fair tick and lands within 1,000 ticks of the pool's TWAP. When the pool tick is more than `deadbandTicks` from fair, a trade toward fair pays: `Arbitrage surcharge (pips)` ```math arb = min( (|tick - fairTick| - deadbandTicks) * 100 * lvrGainBps / 10000, maxArbFeePips ) ``` `lvrGainBps` is at most 20,000 and `maxArbFeePips` at most 250,000. With no fresh fair tick, the shield and every router discount switch off and the pool runs on the engine fee and calendar. ### Market hours The council sets a weekly calendar per pool in minutes after Monday 00:00 UTC: up to 16 trading sessions and 16 auction times. Outside every session the fee is at least `closedFeePips` (at most the guard's `maxFeePips`, 10%). At each auction time the fee floor starts at the armed start fee and falls linearly to zero over `auctionDuration` (1 minute to 1 hour). This is a reopen Dutch auction: the price gap that builds while the stock market is closed is sold to the first trader who accepts the falling fee. ## MakerPilot.step `MakerPilot.step(bytes32 poolId)` is permissionless and runs at most once per `minStepSecs` (60 seconds to 1 day) per pool. It reads only the pool's own TWAP, holdings and day-start mix. It measures volatility, sets a fee level plus inventory skew, picks a calm or storm layout, and arms the next auction's start fee. The guard policy bounds every action: fees inside `[minFeePips, maxFeePips]`, the average fee moving at most `feeStepPips` per `feePeriod`, and layout changes rate-limited by `layoutInterval` and `layoutsPerDay`. ## The daily breaker On the first check of each UTC day the hook records the pool's holdings at the TWAP. If the pool later loses more than `dayLossBps` against simply holding those day-start tokens, the breaker trips. The engine is locked for `dayLockSecs`, fees go to `safeFeePips`, and all liquidity moves to full range. Clearing the breaker early (`clearBreaker`) waits the 2-day timelock. ## Why this limits LVR Loss-versus-rebalancing (LVR) is what an AMM gives away when arbitrageurs trade against its stale price after the real price moves. The PropAMM narrows that loss in four places: - The shield prices arbitrage by its distance to fair value, so the pool keeps part of each move. - Closed-hours fees stop cheap trades against a price that cannot be checked. - Reopen auctions sell the overnight gap through a falling fee. - The breaker caps one day's loss against holding. The book's performance fee is charged on gain over holding, so it is paid only when the pool beats holding its tokens. ## The numbers | Parameter | Bound | Who changes it | |---|---|---| | Swap fee cap | 999,999 pips | Fixed | | `maxFeePips` (engine) | 1 to 100,000 pips | Council, 2-day timelock | | `maxStaleSecs` | 0 (off) to 3,600 s | Council, 2-day timelock | | `lvrGainBps` / `maxArbFeePips` | ≤ 20,000 / ≤ 250,000 | Council, 2-day timelock | | Router discount | ≤ 8,000 bps | Cut at once, raise after 2 days | | `auctionMaxPips` | ≤ 200,000 | Council, 2-day timelock | | `dayLossBps` / `dayLockSecs` | 1 to 2,000 bps / 1 hour to 30 days | Council, 2-day timelock | | Calendar | ≤ 16 sessions, ≤ 16 auctions | Council, immediate | ## Edge cases - Swaps revert with `EmptyPool` on both routes if the full-range position has no liquidity. - While `DOMAIN_ENTRY` is paused, every swap reverts with `DomainError` (directly in `MakerHook.swap` and in `beforeSwap` for routers), including the books' own fee sales. Book withdrawals still run. - `MakerHook.swap` enforces the `DOMAIN_ENTRY` pause directly, computes the same dynamic LP fee stack (fair-value shield, swap guard and calendar floor) with `sender` set to the hook itself, and emits `SwapFeeCharged`. A router discount applies to `MakerHook.swap` only if the hook's own address is listed. ## Related - [Swap against a pool](https://docs.degenhive.ai/pools/swapping.md) Build the pool key, quote, and swap through the hook or any v4 router. - [Provide liquidity](https://docs.degenhive.ai/pools/liquidity.md) Deposit into a BookVault and follow the daily roll. - [Networks & status](https://docs.degenhive.ai/network.md) Robinhood Chain endpoints and deployment status. - [Revenue](https://docs.degenhive.ai/revenue.md) Where book fees go after the roll. --- # Provide liquidity > Deposit stock and USDG into a BookVault, follow the daily UTC roll, then withdraw in kind and claim, with viem and cast examples. Source: https://docs.degenhive.ai/pools/liquidity This guide takes you through one full cycle in a `BookVault`, the LP book behind each stock/USDG pool: deposit, the daily roll, shares, withdrawal and claim. **Prerequisites** - A wallet on Robinhood Chain (4663) with ETH for gas, USDG, and the stock token of the pool (or USDG only, for a zap). - The pool's book address. There is one `BookVault` proxy per pool. Addresses publish at launch on [Network](https://docs.degenhive.ai/network.md); the examples use `BOOK`. > [!IMPORTANT] > These contracts are not deployed yet and not externally audited. ## Step 1: Read the book and its terms Each book reports its stock, USDG and the `ProtocolConfig` it reads. Fees come from one `BookTerms` record that applies to every book. No fee values are hard-coded; the council sets them within these caps: | Term | Cap | Meaning | |---|---|---| | `mgmtFeeBps` | 300 | Per year, on the value of outside shares | | `perfFeeBps` | 5,000 | On gain above the book's high-water mark | | `withdrawFeeBps` | 100 | Kept by the book for holders who stay | | `nftBps` | 2,000 | Share of every fee paid to the Stingvestors pot | | `settleDelay` | 1 minute to 12 hours | Wait after 00:00 UTC before the roll | Raising a fee, or any change to `nftBps`, `settleDelay`, `feeRecipient`, `nftPot` or `keeper`, waits the 2-day timelock. Cuts to the other fees apply at once. **viem** ```ts import { createPublicClient, createWalletClient, defineChain, http, parseAbi } from "viem"; import { privateKeyToAccount } from "viem/accounts"; export const robinhood = defineChain({ id: 4663, name: "Robinhood Chain", nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 }, rpcUrls: { default: { http: ["https://rpc.mainnet.chain.robinhood.com"] } }, }); export const BOOK = "0x..."; // addresses publish at launch export const account = privateKeyToAccount(process.env.PK as `0x${string}`); export const pub = createPublicClient({ chain: robinhood, transport: http() }); export const wallet = createWalletClient({ account, chain: robinhood, transport: http() }); export const bookAbi = parseAbi([ "function stock() view returns (address)", "function usdg() view returns (address)", "function config() view returns (address)", "function value() view returns (uint256)", "function quote(uint256 stockAmount, uint256 usdgAmount) view returns (uint256)", "function requestDeposit(uint256 stockAmount, uint256 usdgAmount)", "function zapFloor(uint256 usdgIn) view returns (uint256)", "function zapDeposit(uint256 usdgIn, uint256 minStockOut) returns (uint256 stockIn, uint256 usdgQueued)", "function cancelDeposit() returns (uint256 stockAmount, uint256 usdgAmount)", "function roll()", "function realize(address account)", "function accountOf(address account) view returns ((uint256 shares, uint256 locked, uint256 assetPending, uint256 depositPending, uint256 assetOwed, uint256 owed))", "function balanceOf(address account) view returns (uint256)", "function requestWithdraw(uint256 shares)", "function cancelWithdraw() returns (uint256 shares)", "function claim() returns (uint256 stockPaid, uint256 usdgPaid)", ]); export const erc20 = parseAbi([ "function approve(address spender, uint256 amount) returns (bool)", "function decimals() view returns (uint8)", ]); const configAbi = parseAbi([ "function bookTerms() view returns ((uint16 mgmtFeeBps, uint16 perfFeeBps, uint16 withdrawFeeBps, uint16 nftBps, uint16 maxSlippageBps, uint32 settleDelay, address feeRecipient, address nftPot, address keeper))", ]); const config = await pub.readContract({ address: BOOK, abi: bookAbi, functionName: "config" }); export const terms = await pub.readContract({ address: config, abi: configAbi, functionName: "bookTerms" }); ``` **cast** ```bash cast call $BOOK "stock()(address)" --rpc-url $RH_RPC cast call $BOOK "usdg()(address)" --rpc-url $RH_RPC CONFIG=$(cast call $BOOK "config()(address)" --rpc-url $RH_RPC) cast call $CONFIG "bookTerms()((uint16,uint16,uint16,uint16,uint16,uint32,address,address,address))" --rpc-url $RH_RPC ``` ## Step 2: Queue a deposit in kind Approve the book for both tokens, then call `requestDeposit(stockAmount, usdgAmount)`. The book pulls the tokens now and queues them for the next roll. Several requests on one UTC day merge into one. Use `quote(stockAmount, usdgAmount)` to see the value the roll will credit: stock at the lower of TWAP and spot, plus USDG at par. Reverts with `DomainError` while the `ENTRY` domain is paused, and with `ZeroAmount` if both amounts are zero. **viem** ```ts import { parseUnits } from "viem"; import { BOOK, account, bookAbi, erc20, pub, wallet } from "./setup"; const [stock, usdg] = await Promise.all([ pub.readContract({ address: BOOK, abi: bookAbi, functionName: "stock" }), pub.readContract({ address: BOOK, abi: bookAbi, functionName: "usdg" }), ]); const stockDec = await pub.readContract({ address: stock, abi: erc20, functionName: "decimals" }); const stockAmount = parseUnits("2", stockDec); const usdgAmount = parseUnits("500", 6); await wallet.writeContract({ address: stock, abi: erc20, functionName: "approve", args: [BOOK, stockAmount] }); await wallet.writeContract({ address: usdg, abi: erc20, functionName: "approve", args: [BOOK, usdgAmount] }); const hash = await wallet.writeContract({ address: BOOK, abi: bookAbi, functionName: "requestDeposit", args: [stockAmount, usdgAmount], }); await pub.waitForTransactionReceipt({ hash }); ``` **cast** ```bash cast send $STOCK "approve(address,uint256)" $BOOK $STOCK_AMOUNT --private-key $PK --rpc-url $RH_RPC cast send $USDG "approve(address,uint256)" $BOOK 500000000 --private-key $PK --rpc-url $RH_RPC cast send $BOOK "requestDeposit(uint256,uint256)" $STOCK_AMOUNT 500000000 --private-key $PK --rpc-url $RH_RPC ``` ## Step 3: Or zap in from USDG only `zapDeposit(usdgIn, minStockOut)` buys the stock share of your USDG through `MakerHook.swap` in the same transaction, at the pool's current mix, then queues the stock and the leftover USDG. The swap pays the pool's normal fee, including the closed-hours floor. Read `zapFloor(usdgIn)` for a fair `minStockOut`: it prices the stock at the higher of spot and TWAP, less `maxSlippageBps`. `zapFloor` reverts with `BookOffTwap` when spot sits more than `maxSlippageBps` ticks from TWAP; wait for the pool to settle. The zap reverts with `Slippage` if the swap buys less than `minStockOut`, and with `DomainError` while paused. **viem** ```ts const usdgIn = parseUnits("1000", 6); const minStockOut = await pub.readContract({ address: BOOK, abi: bookAbi, functionName: "zapFloor", args: [usdgIn] }); await wallet.writeContract({ address: usdg, abi: erc20, functionName: "approve", args: [BOOK, usdgIn] }); await wallet.writeContract({ address: BOOK, abi: bookAbi, functionName: "zapDeposit", args: [usdgIn, minStockOut] }); ``` ## Step 4: Cancel the same day if you change your mind The cutoff is 00:00 UTC. Until then, `cancelDeposit()` returns today's whole request in kind. After midnight the request belongs to the next roll and cannot be cancelled. Reverts with `NothingQueued` if you have no request for today. **viem** ```ts await wallet.writeContract({ address: BOOK, abi: bookAbi, functionName: "cancelDeposit" }); ``` ## Step 5: Roll the day `roll()` runs once per UTC day, from `settleDelay` after 00:00 UTC. For the first hour only `BookTerms.keeper` may call it; after that anyone can. It settles every day up to yesterday in one call. Reverts with `RollNotDue` before the window opens or once the day is rolled. > **Figure: A UTC day in a BookVault.** A Robinhood book takes deposits in kind, rolls once a day after settleDelay, pays its fees in USDG and settles deposits and withdrawals in kind. > > Left, during UTC day D: requestDeposit takes the stock and USDG in kind, or zapDeposit takes USDG and buys the stock leg; requestWithdraw takes shares and can be cancelled the same day only. Above them: the roll opens at 00:00 UTC plus settleDelay, for the keeper during the first hour and then for anyone. Middle: roll(), once per UTC day, in five steps: 1. gain over holding, using the lower of TWAP and spot; 2. take the management fee and the performance fee above the alpha high-water mark; 3. harvest the fees into USDG, idle USDG first, then a pool slice; 4. pay the fees; 5. price shares and settle deposits and in-kind withdrawals. From step 4, nftBps of the fees go to the Stingvestors VestorPot and the rest to the fee recipient, the outbox Safe. From step 5: claim, where realize hands over shares and claim() pays USDG and stock. The roll runs in this order: 1. It pokes the hook, which collects pool fees into idle and checks the breaker. 2. It measures gain over holding: the book's holdings now against what it held after the last roll, valued at both TWAP and spot, taking the lower. 3. It charges the management fee on outside shares for the days elapsed, and the performance fee on the part of the gain that lifts the book above its high-water mark. Losing days pay no performance fee. 4. It turns the fees into USDG: idle USDG first, then a pool slice sold through the hook with a TWAP-based floor. If the sale fails, the rest stays due for the next roll. 5. It pays `nftBps` of the fees to `BookTerms.nftPot`, the Stingvestors `VestorPot`, and the rest to `BookTerms.feeRecipient`, the council's outbox Safe. That Safe bridges the USDG to Hyperliquid and calls [`HyperRevenueRouter.notifyRevenue`](https://docs.degenhive.ai/revenue.md). A refused payment is deferred and retried each roll. 6. It prices shares, executes the queued deposits and then the withdrawals, and redeploys idle tokens. Deposits are valued with stock at the lower of TWAP and spot. If they exceed the book's deposit cap, every outside request is cut pro rata and the rest is refunded in kind to your owed balance. A pool that refuses the add, for example while paused, refunds the same way. > [!NOTE] > The `HiveFund` is a depositor in the same queue. Once per UTC day anyone can call `HiveFund.allocate()`, which deposits protocol USDG into books under their target weight and withdraws at most `maxMoveBps` from books over it. The Fund pays no management fee and is not limited by the deposit cap. **viem** ```ts await wallet.writeContract({ address: BOOK, abi: bookAbi, functionName: "roll" }); ``` **cast** ```bash cast send $BOOK "roll()" --private-key $PK --rpc-url $RH_RPC ``` ## Step 6: Realize your shares Shares minted at the roll sit in the book's own entry until they are realized. Your next request, transfer or claim realizes them, or anyone can call `realize(account)`. `accountOf(account).shares` counts them before and after. Book shares are a normal ERC-20 once realized. **viem** ```ts await wallet.writeContract({ address: BOOK, abi: bookAbi, functionName: "realize", args: [account.address] }); const acct = await pub.readContract({ address: BOOK, abi: bookAbi, functionName: "accountOf", args: [account.address] }); console.log(acct.shares, acct.assetOwed, acct.owed); ``` ## Step 7: Request a withdrawal `requestWithdraw(shares)` locks free shares in the book for the next roll. It is never paused. `cancelWithdraw()` returns today's request before 00:00 UTC. At the roll you receive a pro-rata slice of the pool, the book's held stock and its idle USDG, in kind. `withdrawFeeBps` stays in the book for the holders who remain; it is waived when every share leaves. Reverts with `SharesShort` if you ask for more than your free shares, and with `ZeroAmount` for zero. **viem** ```ts const shares = await pub.readContract({ address: BOOK, abi: bookAbi, functionName: "balanceOf", args: [account.address] }); await wallet.writeContract({ address: BOOK, abi: bookAbi, functionName: "requestWithdraw", args: [shares] }); ``` ## Step 8: Claim your tokens After the roll, `claim()` pays your owed stock and USDG. USDG must transfer or the call reverts. If the stock token refuses the transfer, the stock stays owed and you can claim it later. Refunded deposits are claimed the same way. **viem** ```ts const { result } = await pub.simulateContract({ account, address: BOOK, abi: bookAbi, functionName: "claim" }); console.log("stock", result[0], "usdg", result[1]); await wallet.writeContract({ address: BOOK, abi: bookAbi, functionName: "claim" }); ``` **cast** ```bash cast send $BOOK "claim()" --private-key $PK --rpc-url $RH_RPC ``` ## Step 9: Where to go next - [Stock pools](https://docs.degenhive.ai/pools.md) How the hook prices swaps and protects the book. - [Swap and integrate](https://docs.degenhive.ai/pools/swapping.md) Quote and swap Stock Tokens against USDG. - [NFTs](https://docs.degenhive.ai/nfts.md) How the `nftBps` share reaches Stingvestor holders. - [Revenue](https://docs.degenhive.ai/revenue.md) What happens to the fee recipient's share on Hyperliquid. --- # Swap and integrate > Integrate stock-token/USDG swaps on Robinhood Chain through MakerHook.swap or any Uniswap v4 router, with pool keys, quotes, fees in pips and reverts. Source: https://docs.degenhive.ai/pools/swapping This guide shows how to swap a Stock Token against USDG in a PropAMM pool. You can call the hook's own `swap` (route A) or any Uniswap v4 router that goes through the `PoolManager` (route B). Both routes enforce the `DOMAIN_ENTRY` pause, apply the same dynamic LP fee stack (fair-value shield, swap guard and calendar floor), and emit `SwapFeeCharged`. **Prerequisites** - A wallet on Robinhood Chain (4663) with ETH for gas and the token you sell. - The `MakerHook` address. Addresses publish at launch on [Network](https://docs.degenhive.ai/network.md); the examples use `MAKER_HOOK`. > [!IMPORTANT] > These contracts are not deployed yet and not externally audited. ## Step 1: Find the pool and build its key There is exactly one pool per stock. `MakerHook.poolOfStock(stock)` returns its id, which is the standard v4 `PoolId`. The key is: | Field | Value | |---|---| | `currency0`, `currency1` | The stock and USDG, sorted by address | | `fee` | `0x800000` (v4 dynamic fee flag) | | `tickSpacing` | `MakerHook.tickSpacing()`, one value for every pool of the hook | | `hooks` | `MAKER_HOOK` | **viem** ```ts import { createPublicClient, defineChain, encodeAbiParameters, http, keccak256, parseAbi } from "viem"; export const robinhood = defineChain({ id: 4663, name: "Robinhood Chain", nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 }, rpcUrls: { default: { http: ["https://rpc.mainnet.chain.robinhood.com"] } }, }); export const pub = createPublicClient({ chain: robinhood, transport: http() }); export const MAKER_HOOK = "0x..."; // addresses publish at launch export const STOCK = "0x..."; // the stock token you trade export const hookAbi = parseAbi([ "function poolOfStock(address stock) view returns (bytes32)", "function tickSpacing() view returns (int24)", "function usdg() view returns (address)", "function poolManager() view returns (address)", "function swap(bytes32 poolId, bool buyStock, uint256 amountIn, uint256 minOut, uint64 deadline) returns (uint256 amountOut)", ]); export const poolId = await pub.readContract({ address: MAKER_HOOK, abi: hookAbi, functionName: "poolOfStock", args: [STOCK] }); export const usdg = await pub.readContract({ address: MAKER_HOOK, abi: hookAbi, functionName: "usdg" }); const tickSpacing = await pub.readContract({ address: MAKER_HOOK, abi: hookAbi, functionName: "tickSpacing" }); const [currency0, currency1] = BigInt(STOCK) < BigInt(usdg) ? [STOCK, usdg] : [usdg, STOCK]; export const key = { currency0, currency1, fee: 0x800000, tickSpacing, hooks: MAKER_HOOK } as const; // The hook's id is keccak256(abi.encode(key)), the same as v4's PoolIdLibrary. const id = keccak256(encodeAbiParameters( [{ type: "address" }, { type: "address" }, { type: "uint24" }, { type: "int24" }, { type: "address" }], [key.currency0, key.currency1, key.fee, key.tickSpacing, key.hooks], )); if (id !== poolId) throw new Error("pool key mismatch"); ``` **cast** ```bash cast call $MAKER_HOOK "poolOfStock(address)(bytes32)" $STOCK --rpc-url $RH_RPC cast call $MAKER_HOOK "tickSpacing()(int24)" --rpc-url $RH_RPC cast call $MAKER_HOOK "usdg()(address)" --rpc-url $RH_RPC ``` A zero id means the stock has no pool. ## Step 2: Quote the swap Fees are in pips: 1,000,000 pips is 100%, so 3,000 pips is 0.30%. A swap's fee depends on the side, the trade size, the pool's inventory, the fair-value shield and the calendar, so the reliable quote runs the real swap path. You can either call immutable `MakerQuoter.quoteExactInput(poolId, buyStock, amountIn)` (or `quoteExactOutput`) via `eth_call` with no token approval required, or approve the hook and simulate `MakerHook.swap` with `minOut = 0`, then apply your own slippage margin to the result. The fee can rise during closed hours and right after a reopen auction starts. See [Stock pools](https://docs.degenhive.ai/pools.md#the-swap-fee) for each part. **viem** ```ts import { createWalletClient, http, parseAbi, parseUnits } from "viem"; import { privateKeyToAccount } from "viem/accounts"; import { MAKER_HOOK, hookAbi, poolId, pub, robinhood, usdg } from "./pool"; const account = privateKeyToAccount(process.env.PK as `0x${string}`); const wallet = createWalletClient({ account, chain: robinhood, transport: http() }); const erc20 = parseAbi(["function approve(address spender, uint256 amount) returns (bool)"]); const amountIn = parseUnits("250", 6); // 250 USDG in, buying the stock await wallet.writeContract({ address: usdg, abi: erc20, functionName: "approve", args: [MAKER_HOOK, amountIn] }); const { result: quoted } = await pub.simulateContract({ account, address: MAKER_HOOK, abi: hookAbi, functionName: "swap", args: [poolId, true, amountIn, 0n, 0n], }); const minOut = (quoted * 9_950n) / 10_000n; // 0.5% margin ``` ## Step 3: Route A: swap through MakerHook.swap `swap(poolId, buyStock, amountIn, minOut, deadline)` is exact-in and all-or-nothing. `buyStock = true` spends USDG; `false` sells the stock. `MakerHook.swap` checks the `DOMAIN_ENTRY` pause directly, pulls `amountIn` from you, computes the pool's dynamic LP fee (fair-value shield, swap guard and calendar floor), emits `SwapFeeCharged` with `sender` set to the hook itself, swaps through the `PoolManager`, and sends the output to you. Pass `deadline = 0` for no deadline. Reverts: - `DeadlineExpired` after `deadline`. - `ZeroAmount` for `amountIn = 0`; `UnknownPool` for a bad id. - `DomainError` while `DOMAIN_ENTRY` is paused; `EmptyPool` when full-range liquidity is zero. - `Slippage` if the output is below `minOut`. - `ExactValueMismatch` if the input token takes a transfer fee or the swap cannot fill in full. **viem** ```ts const deadline = BigInt(Math.floor(Date.now() / 1000) + 300); const hash = await wallet.writeContract({ address: MAKER_HOOK, abi: hookAbi, functionName: "swap", args: [poolId, true, amountIn, minOut, deadline], }); await pub.waitForTransactionReceipt({ hash }); ``` **cast** ```bash cast send $USDG "approve(address,uint256)" $MAKER_HOOK 250000000 --private-key $PK --rpc-url $RH_RPC cast send $MAKER_HOOK "swap(bytes32,bool,uint256,uint256,uint64)" $POOL_ID true 250000000 $MIN_OUT 0 \ --private-key $PK --rpc-url $RH_RPC ``` ## Step 4: Route B: swap through any v4 router Any contract that calls `PoolManager.unlock` and then `swap` on the key from step 1 works, exact-in or exact-out. The calling contract is the `sender` the hook sees, so a router discount set with `setRouterDiscount(router, bps)` applies to that router's flow. The discount applies only while the fair tick is fresh and the trade is not arbitrage. This minimal exact-in router shows the calls. In v4, a negative `amountSpecified` means exact input. `ExactInSwapper.sol` ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.26; import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol"; import {IUnlockCallback} from "@uniswap/v4-core/src/interfaces/callback/IUnlockCallback.sol"; import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol"; import {Currency} from "@uniswap/v4-core/src/types/Currency.sol"; import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol"; import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract ExactInSwapper is IUnlockCallback { IPoolManager public immutable manager; constructor(IPoolManager manager_) { manager = manager_; } function swapExactIn(PoolKey calldata key, bool zeroForOne, uint128 amountIn, uint128 minOut) external returns (uint256 out) { bytes memory data = abi.encode(msg.sender, key, zeroForOne, amountIn, minOut); out = abi.decode(manager.unlock(data), (uint256)); } function unlockCallback(bytes calldata data) external returns (bytes memory) { require(msg.sender == address(manager), "only manager"); (address payer, PoolKey memory key, bool zeroForOne, uint128 amountIn, uint128 minOut) = abi.decode(data, (address, PoolKey, bool, uint128, uint128)); BalanceDelta d = manager.swap( key, IPoolManager.SwapParams({ zeroForOne: zeroForOne, amountSpecified: -int256(uint256(amountIn)), sqrtPriceLimitX96: zeroForOne ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1 }), "" ); (Currency tokenIn, Currency tokenOut) = zeroForOne ? (key.currency0, key.currency1) : (key.currency1, key.currency0); uint256 paid = uint256(uint128(-(zeroForOne ? d.amount0() : d.amount1()))); uint256 out = uint256(uint128(zeroForOne ? d.amount1() : d.amount0())); require(out >= minOut, "slippage"); manager.sync(tokenIn); IERC20(Currency.unwrap(tokenIn)).transferFrom(payer, address(manager), paid); manager.settle(); manager.take(tokenOut, payer, out); return abi.encode(out); } } ``` `zeroForOne` is true when you sell `currency0`. If the stock sorts first, selling the stock is `zeroForOne = true`. ## Step 5: Read the fee you paid Every swap emits `SwapFeeCharged` from the hook with the parts of its fee: `fee` (charged), `base` (engine ask or bid), `arb` (shield surcharge), `size`, `inventory` and `least` (calendar floor). `MakerHook.swap` also emits `Swapped(poolId, account, buyStock, amountIn, amountOut)`. **viem** ```ts import { parseEventLogs, parseAbi } from "viem"; const events = parseAbi([ "event SwapFeeCharged(bytes32 indexed poolId, address indexed sender, bool zeroForOne, int256 amountSpecified, (uint24 fee, uint24 base, uint24 arb, uint24 size, uint24 inventory, uint24 least, uint16 tradeSizeBps, int16 invSkewBps) parts)", ]); const receipt = await pub.getTransactionReceipt({ hash }); const [charged] = parseEventLogs({ abi: events, logs: receipt.logs, eventName: "SwapFeeCharged" }); console.log(`fee ${Number(charged.args.parts.fee) / 10_000}%`); ``` ## Step 6: Handle pauses, closed hours and empty pools - **`ENTRY` paused.** Every swap reverts with `DomainError`. On route A, `MakerHook.swap` checks `DOMAIN_ENTRY` before unlocking and reverts `DomainError` directly. On route B, `PoolManager` calls `beforeSwap`, so `DomainError` reaches you wrapped in v4's `WrappedError(target, selector, reason, details)`; decode `reason` to see `DomainError`. Retry after the council resumes. - **Closed hours.** Swaps do not revert. Outside the pool's trading sessions the fee is at least `closedFeePips` (up to 10%), so a tight `minOut` fails with `Slippage` on route A. Re-quote before you send. - **Reopen auctions.** At each scheduled auction time the fee floor starts at the armed start fee (up to 20%) and falls to zero over `auctionDuration`. The floor drops every second, so a later swap in the window meets a lower floor. - **Empty pool.** Both routes revert with `EmptyPool` while the full-range position holds no liquidity. > [!TIP] > Read the current ask and bid floors with `MakerHook.pool(poolId)`. Its `askFee` and `bidFee` fields are the engine fee or the calendar floor, whichever is higher. The shield, size and inventory parts are added per trade. ## Step 7: Where to go next - [Stock pools](https://docs.degenhive.ai/pools.md) The fee parts, the shield, the calendar and the breaker. - [Networks & status](https://docs.degenhive.ai/network.md) Robinhood Chain RPC and deployment status. - [Provide liquidity](https://docs.degenhive.ai/pools/liquidity.md) Earn the swap fees as a BookVault LP. --- # Revenue router > How HyperRevenueRouter receives every protocol dollar on HyperEVM, splits it into four lanes, and holds the buyback and locker reserves until token launch. Source: https://docs.degenhive.ai/revenue `HyperRevenueRouter` is the single USDC landing point for protocol revenue on HyperEVM (999). Each payment to `notifyRevenue` splits into four lanes: ops, a buyback reserve, a locker reserve and the Fangvestors NFT pot. > [!IMPORTANT] > The router is not deployed yet and not externally audited. Addresses publish at launch on [Network](https://docs.degenhive.ai/network.md). ## Where revenue comes from > **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). | Source | Contract that pays | What it pays | |---|---|---| | Vault fee take | `HyperVaultFeeRouter` | On third-party vaults, the protocol take (default 2,000 bps, at most 5,000) of each management and performance fee | | Flagship fees | `HyperVaultFeeRouter` | The whole management fee, and the performance fee left after data royalties and the forecaster share | | Creation fees | `HyperVaultFactory` | The USDC fee for creating a third-party vault (default 10 USDC) | | Marketplace take | `DataProviderRegistry` | The protocol's cut of data-feed payments | | Robinhood books | Council outbox Safe | `BookVault` fees less `nftBps`, bridged to HyperEVM by hand | There is no bridge contract. The `BookVault` fee recipient on Robinhood Chain is a council Safe. Its signers bridge the USDG, then approve USDC and call `notifyRevenue` on HyperEVM. ## The four lanes > **Figure: Router lanes and a Flagship profit of 100.** Every dollar into HyperRevenueRouter splits four ways, and a Flagship profit of 100 leaves 75 with depositors. > > Two stacked bars. Top bar, HyperRevenueRouter, each dollar: ops 3,167 bps (31.67%), buyback reserve 3,167 bps (31.67%), locker reserve 3,166 bps (31.66%), NFT lane 500 bps (5%). Both reserves are held until token launch; the NFT lane pays the Fangvestors pot while it is live. Bottom bar, a Flagship profit of 100 at a 25% performance fee: depositors 75, forecasters 10, ops 4.75, buyback reserve 4.75, locker reserve 4.75, Fangvestors 0.75. Forecasters take 40% of the 25 fee, and the router splits the other 15 like any dollar. The example has no data royalties and no locker rebate. | Lane | Default | Where it goes | |---|---|---| | Ops | 3,167 bps (31.67%) | Paid to `opsRecipient` at once | | Buyback reserve | 3,167 bps (31.67%) | Held in the router until token launch | | Locker reserve | 3,166 bps (31.66%) | Held in the router until token launch | | NFT | 500 bps (5%) | Paid to the Fangvestors `VestorPot`, only while the pot is live | The NFT lane pays only while `nftPot.live()` returns true, which means at least `minLiveSeats` Fangvestors circulate. Otherwise its share, and any rounding dust, goes to ops. If the ops or NFT transfer fails, the amount waits in `pendingOpsUsdc` until anyone calls `flushOps()`. The council can change the split with `submitChange(LANE_BPS, …)` and a 48-hour wait. The four values must sum to 10,000 and the NFT lane is capped at 2,000 bps. ## Counted revenue Every payment is split, but only some payments count. The router adds the full amount to `dailyRevenueUsdc(day)` when the payer is on the allowlist, set by the council with `setRevenueSource(source, true)`. The intended sources are the fee router, the factory, the data registry and the outbox Safe. A payment from any other address is split normally and not counted. Counted revenue matters at token launch: `DGVEmissions` paces DGV by the last 30 complete days of it. See [Token](https://docs.degenhive.ai/token.md#emissions). **viem** ```ts import { createPublicClient, defineChain, http, parseAbi } from "viem"; const hyperEvm = defineChain({ id: 999, name: "HyperEVM", nativeCurrency: { name: "HYPE", symbol: "HYPE", decimals: 18 }, rpcUrls: { default: { http: ["https://rpc.hyperliquid.xyz/evm"] } }, }); const hyper = createPublicClient({ chain: hyperEvm, transport: http() }); const REVENUE_ROUTER = "0x..."; // addresses publish at launch const routerAbi = parseAbi([ "function dailyRevenueUsdc(uint64 day) view returns (uint256)", "function revenueSource(address payer) view returns (bool)", "function buybackReserveUsdc() view returns (uint256)", "function lockerReserveUsdc() view returns (uint256)", ]); const day = BigInt(Math.floor(Date.now() / 86_400_000)); // UTC day index const counted = await hyper.readContract({ address: REVENUE_ROUTER, abi: routerAbi, functionName: "dailyRevenueUsdc", args: [day] }); ``` ## Reserves before the token The product launches with no token. Until then the buyback and locker lanes only accumulate. Both lanes are inactive, nothing drips, `releaseBuyback` reverts with `BuybackExecutorNotSet` or `InsufficientReleasable`, and `releaseLockerYield` reverts with `LockerPotNotSet` or `ZeroAmount`. The reserves are visible on chain at any time through `buybackReserveUsdc()` and `lockerReserveUsdc()`. ## At token launch At token launch, the buyback and locker lanes activate once and begin streaming their accumulated USDC reserves along fixed drip schedules: `Drip per lane` ```math releasable += (reserve - releasable) * (now - lastDripAt) / (unlockEnd - lastDripAt) ``` Additional funding merges into the schedule, weighted by amount, so a spike in fees smooths out over the lane's horizon instead of releasing in one block. | Setting | Default | Bounds | Change delay | |---|---|---|---| | Buyback horizon | 90 days | 1 to 365 days | Longer at once; shorter after 48 hours | | Locker horizon | 30 days | 1 to 365 days | Longer at once; shorter after 48 hours | | Daily release cap | Uncapped | Configurable | Lower cap at once; higher cap after 48 hours | A paused lane stops dripping, and its schedule shifts out by the paused duration when resumed. Once active, the buyback lane funds automated DGV buybacks and burns on HyperCore, and anyone can call `releaseLockerYield()` to send releasable locker USDC to `HyperLockerPot`. ## Slashed USDC Slashed forecaster bonds go straight into the buyback reserve. They are not split across the four revenue lanes and are not counted as protocol revenue. ## Worked example A Flagship vault earns 100 USDC of profit above its high-water mark. The Flagship runs a 25% performance fee. Its forecaster share is set as a fraction of the fee (`forecastShareBps`, at most 5,000); here it is 4,000 bps, which is 10% of the profit. No data feeds earn royalties in this example, and the management fee is left out. | Step | Amount (USDC) | |---|---| | Profit above the high-water mark | 100.00 | | Stays with depositors (75%) | 75.00 | | Performance fee (25%) | 25.00 | | To forecasters through `HyperCrowdPay` (4,000 bps of the fee) | 10.00 | | To `HyperRevenueRouter.notifyRevenue` (Flagship: the rest) | 15.00 | | Ops lane: 15 × 3,167 bps, plus dust | 4.75 | | Buyback reserve: 15 × 3,167 bps | 4.75 | | Locker reserve: 15 × 3,166 bps | 4.75 | | Fangvestors pot: 15 × 500 bps | 0.75 | The exact router figures are 4.7505, 4.7505, 4.749 and 0.75, which sum to 15. If the Fangvestors pot is not live, ops receives 5.5005. At token launch, while `HyperBookRewards` is set, 20% of each performance fee is first offered back to depositors who lock DGV, which lowers the router's share. ## Related - [Networks & status](https://docs.degenhive.ai/network.md) Chains and deployment status. - [Vault fees](https://docs.degenhive.ai/vaults/fees.md) How management and performance fees are taken at the roll. - [Token](https://docs.degenhive.ai/token.md) What the reserves fund once DGV launches. - [NFTs](https://docs.degenhive.ai/nfts.md) How the NFT lane reaches Fangvestor holders. --- # Stingvestors & Fangvestors > Stingvestors on Robinhood Chain and Fangvestors on HyperEVM, each with a 5,100 cap, a curve sale, and a pot that pays its chain's revenue when an NFT is burned. Source: https://docs.degenhive.ai/nfts DegenHive has one NFT collection per chain: Stingvestors on Robinhood Chain (4663) and Fangvestors on HyperEVM (999). Each NFT accrues a share of its own chain's protocol revenue in a `VestorPot`, and the only way to collect it is to burn the NFT. > [!IMPORTANT] > The collection, pot and minter contracts are not deployed yet and not externally audited. Addresses publish at launch on [Network](https://docs.degenhive.ai/network.md). ## The two collections | | Stingvestors | Fangvestors | |---|---|---| | Chain | Robinhood Chain (4663) | HyperEVM (999) | | Cap | 5,100 | 5,100 | | Pot asset | USDG | USDC | | Revenue source | `nftBps` of every `BookVault` fee (at most 2,000 bps) | The 500 bps NFT lane of `HyperRevenueRouter` | | Deployment | Live collection upgraded in place | Fresh collection on HyperEVM | | DGV | Holders at the snapshot receive a patron DGV allocation at token launch | No DGV allocation | Stingvestors keeps its 572 minted NFTs through the upgrade, including 111 reserve ids (11,001 to 11,111). Additional sale and treasury ids continue in mint order. ## Minting on the curve Each collection has a `VestorCurveMinter` that sells on a linear stablecoin curve. The curve's prices are constructor inputs; the launch inputs are 4,200 NFTs from $1 to $50. `Price of the k-th curve NFT (k from 0)` ```math priceAt(k) = startPrice + (endPrice - startPrice) * k / (curveSupply - 1) ``` With `startPrice = 1e6`, `endPrice = 50e6` and `curveSupply = 4,200`, the whole curve raises 107,100 USDG or USDC, an average of $25.50. Payment goes straight from the buyer to the minter's `proceedsRecipient`. Each address may mint up to `walletCap`. > **Interactive simulator (VestorCurveMinter mint price):** Position `k` (from 0) costs `startPrice + (endPrice - startPrice) * k / (curveSupply - 1)`, floored, in the chain's 6-decimal dollar token (USDG on Robinhood Chain, USDC on HyperEVM). A mint of `count` at position `sold` pays `count * startPrice + (endPrice - startPrice) * sumK / (curveSupply - 1)` with `sumK = count * (2 * sold + count - 1) / 2`, floored once. Defaults $1 to $50 over 4,200 NFTs: a sold-out curve raises $107,100. Reverts `ZeroAmount` for 0 and `CapExceeded` past the curve. The council (Stingvestors) or owner (Fangvestors) mints the rest with `mintTreasury(to, count, receipt)`. It cannot use room the curve has not sold yet. That leaves 328 treasury NFTs for Stingvestors and 900 for Fangvestors. **viem** ```ts import { parseAbi } from "viem"; // pub, wallet and erc20 are set up as in /pools/liquidity; MINTER and PAY_TOKEN publish at launch. const minterAbi = parseAbi([ "function quote(uint256 count) view returns (uint256)", "function mint(uint256 count, uint256 maxTotalPrice) returns (uint256 firstId, uint256 totalPrice)", ]); const count = 3n; const price = await pub.readContract({ address: MINTER, abi: minterAbi, functionName: "quote", args: [count] }); await wallet.writeContract({ address: PAY_TOKEN, abi: erc20, functionName: "approve", args: [MINTER, price] }); await wallet.writeContract({ address: MINTER, abi: minterAbi, functionName: "mint", args: [count, price] }); ``` `mint` reverts with `SaleNotStarted` before `startTime`, `CapExceeded` past the curve, `Slippage` if the total exceeds `maxTotalPrice`, `WalletCapExceeded` above the wallet cap, and `EnforcedPause()` while the owner has paused the minter. ## How the pot accrues > **Figure: How a VestorPot pays each NFT.** Each flush raises the pot's index by the new revenue per circulating NFT, and burning an NFT pays the rise since its mint. > > Left, a staircase chart of the pot index over time; each step is one flush of amount / circulating. NFT A is minted at index 0 and burned at the end, when the index is 125, so burn(A) pays 125. NFT B is minted later, when the index is 65, and has accrued 60 by the end. Right, four boxes in order: revenue arrives as a plain transfer to VestorPot; flush() adds amount / circulating to the index; each NFT accrues the index minus the index at its mint; burn(id) pays the accrued amount. A note: new mints start at the current index, and excluded holders earn nothing. Revenue reaches a pot by plain transfer. Anyone can call `flush()`, and the collection calls it before every mint, burn or excluded-holder move. A flush spreads the new balance over every circulating NFT through one index: `Flush` ```math index += amount * 1e18 / circulating accrued(id) = frozen(id) + (index - seat(id).start) / 1e18 ``` - A new NFT starts at the current index, so it earns only from later funding. - Excluded holders do not earn. The council lists them with `setExcludedHolder`; their seats freeze what they earned so far, and they do not count as circulating. On Stingvestors the retired lootbox, which holds the reserve ids, is excluded before the pot's first funding. - While fewer than `minLiveSeats` NFTs circulate, a flush sends the whole new balance to the pot's `fallbackRecipient`. On HyperEVM the router checks `live()` first and keeps the NFT lane in ops instead. `accrued(id)` and `batchAccrued(ids)` include any balance not yet flushed. ## Burn to claim `burn(uint256 id) returns (uint256 amount)` is the payout. Only the current owner can call it; an approved operator cannot. The collection flushes the pot, burns the NFT and calls `pot.redeem(id, owner)`, which pays the NFT's accrual in USDG (Stingvestors) or USDC (Fangvestors). Burned ids are never minted again, and later revenue is shared among the NFTs that remain. **viem** ```ts // COLLECTION publishes at launch; account is the NFT's owner. const { result: amount } = await pub.simulateContract({ account, address: COLLECTION, abi: parseAbi(["function burn(uint256 id) returns (uint256 amount)"]), functionName: "burn", args: [tokenId], }); // amount is what the burn pays now ``` > [!WARNING] > Burning is irreversible. The NFT is gone and its future share goes to the remaining holders. If the stablecoin refuses the transfer, for example to a blocklisted address, the amount is booked to `unpaid[owner]`. Anyone can later call `claimUnpaid(owner)` on the pot, which pays the owner. An NFT minted or re-included in the same block as its burn forfeits the accrual since that block; the forfeited amount goes back to the other holders at the next flush. ## Royalties and transfers Both collections implement ERC-2981. `royaltyInfo(id, price)` returns the immutable receiver and `price × royaltyBps / 10,000`, with `royaltyBps` at most 1,000. An optional ERC-721C transfer validator applies to transfers when the admin sets one. Mint and burn never reach the validator. ## The numbers | Parameter | Value | |---|---| | `MAX_SUPPLY` | 5,100 per collection | | Curve (launch inputs) | 4,200 NFTs, $1 to $50 | | `MAX_ROYALTY_BPS` | 1,000 | | `minLiveSeats` | 1 to 5,100, set at pot deployment | | `INDEX_SCALE` | 1e18 | | Stingvestors pot funding | `nftBps` of book fees, at most 2,000 bps | | Fangvestors pot funding | 500 bps router lane, at most 2,000 bps | ## Related - [Networks & status](https://docs.degenhive.ai/network.md) HyperEVM and Robinhood Chain deployment status. - [Revenue](https://docs.degenhive.ai/revenue.md) The router lane that funds the Fangvestors pot. - [Provide liquidity](https://docs.degenhive.ai/pools/liquidity.md) The book fees that fund the Stingvestors pot. - [Token](https://docs.degenhive.ai/token.md) The Stingvestor patron allocation at token launch. --- # DGV launch > DGV for developers. The product launches first; DGV launches later on Hyperliquid with claims, a sale, revenue-paced emissions, locks, lock yield and order-book buybacks. Source: https://docs.degenhive.ai/token DGV is DegenHive's token: a fixed-supply HIP-1 spot token on HyperCore, linked to an ERC-20 on HyperEVM (999). The product launches with no token. DGV and every contract on this page go live later, at token launch, on Hyperliquid only. > [!IMPORTANT] > None of the contracts here is deployed yet or externally audited. Nothing about DGV exists on Robinhood Chain. Addresses publish at launch on [Network](https://docs.degenhive.ai/network.md). DGV is not equity and never a share of a vault. Before the token, the protocol builds USDC reserves in [`HyperRevenueRouter`](https://docs.degenhive.ai/revenue.md) for buybacks and lock yield. ## DGV facts | Property | Value | |---|---| | Supply | 1,000,000,000 DGV, fixed supply; no mint function | | Decimals | 6 | | Upgradeability | Immutable, no owner, no transfer hooks | | Extras | EIP-2612 `permit`; `burn(amount)` from the caller's balance; a `burned()` counter | | HIP-1 link | Linked 1:1 between HyperCore HIP-1 spot and the HyperEVM ERC-20 | Transfers to the HIP-1 token system address move DGV between HyperEVM and HyperCore spot balances. ## Launch sequence > **Figure: Token launch sequence.** The token arrives in nine ordered steps on Hyperliquid, and the reserves held since launch start to drip at steps 7 and 8. > > Nine numbered steps in order. 1. HIP-1 deploy: the spot token on HyperCore. 2. DGV: 1 billion supply, 6 decimals, an immutable ERC-20 linked to the HIP-1 token. 3. Locks: HyperDGVLocks, then enableStaking(). 4. DGVClaim: Robinhood DGV holders claim 1:1, plus Stingvestor patrons and Season 0. 5. DGVSale: a fixed USDC price and a linear vest. 6. Emissions: HyperBookRewards and DGVEmissions. 7. Buyback: OrderBookComb and activateBuyback(), a 90-day drip. 8. Locker yield: activateLocker(), a 30-day drip. 9. DGV bonds: startDgvBonds() with a 7 to 60 day window. 1. **HIP-1 deploy**: the spot token and its DGV/USDC pair on HyperCore. 2. **DGV**: the ERC-20 on HyperEVM mints the fixed 1,000,000,000 supply (6 decimals) once and links 1:1 to the HIP-1 token. 3. **Locks**: `HyperDGVLocks`, `HyperLockerWeights` and `HyperLockerPot`, then `enableStaking()`. Holders lock for 4 to 52 weeks or permanently. 4. **Claims** (`DGVClaim`): retired Robinhood DGV holders 1:1, Stingvestor holders at the snapshot, and Season 0 participants. 5. **Sale** (`DGVSale`): a fixed USDC price with linear vesting. 6. **Emissions** (`HyperBookRewards` and `DGVEmissions`), paced by 30-day counted protocol revenue. 7. **Buyback**: `OrderBookComb` becomes the router's buyback executor, and `activateBuyback()` drips the buyback reserve over 90 days. 8. **Locker yield**: `activateLocker()` drips the locker reserve over 30 days. 9. **Forecaster bonds**: `HyperCrowdPay.startDgvBonds(window)` moves bonds from USDC to DGV over a 7 to 60 day window. ## Claims `DGVClaim` pays launch allocations from one Merkle tree: retired Robinhood DGV holders one for one, Stingvestor holders at the snapshot, and Season 0 participants. Each wallet claims its whole amount once. | Call | Who | Notes | |---|---|---| | `claim(amount, proof)` | Wallet in the tree | Inside `[claimStart, claimEnd)` | | `claimAndLock(amount, proof, weeks_)` | Wallet in the tree | Straight into a lock once staking is enabled | The leaf is OpenZeppelin's standard double hash, so `@openzeppelin/merkle-tree` builds compatible proofs: **ts** ```ts import { StandardMerkleTree } from "@openzeppelin/merkle-tree"; // leaf = keccak256(bytes.concat(keccak256(abi.encode(account, amount)))) const tree = StandardMerkleTree.of(allocations, ["address", "uint256"]); // [[account, amount], ...] const proof = tree.getProof([account, amount]); ``` Errors: `ClaimNotOpen`, `AlreadyClaimed`, `InvalidProof`, `ZeroAmount`. ## Sale `DGVSale` sells at one fixed USDC price per whole DGV, set at deployment with every other parameter. `buy(dgvAmount, proof)` charges `costUsdc(dgvAmount)`, rounded up, and sends 100% of it to `proceedsRecipient` in the same transaction. An optional allowlist root uses the leaf `keccak256(bytes.concat(keccak256(abi.encode(buyer))))`. Bought DGV vests linearly over `vestSecs` from `closeTime()`, the sale end or the earlier `endSale()`. Buyers pull it with `claim()`. After close, anyone can call `sweepUnsold()`. Reverts: `SaleNotOpen`, `NotAllowlisted`, `WalletCapExceeded`, `TotalCapExceeded`, `SaleUnderfunded`, `PaymentFailed`. ## Emissions `DGVEmissions` holds the emissions allocation and releases it once per UTC day. Anyone may call `release()`; a second call the same day reverts with `AlreadyReleasedToday`. `R` is the router's counted revenue over the 30 complete days before today. `Daily release` ```math amount = min( rate * R / 30, (R / 30) / dgvPrice, dailyCap, balance ) ``` `rate` is DGV per 1 USDC of average daily revenue. `dgvPrice` is the reference price from `HyperBookRewards`, a 7-day EMA of HyperCore spot. The second term caps each day's DGV at the value of one day's revenue. While the price reads 0, nothing is released. | Limit | Value | |---|---| | `MAX_RATE_DGV_PER_USDC` | 1,000 DGV per USDC | | `MAX_DAILY_CAP` | 2,000,000 DGV (0.2% of supply) | | Lowering rate or cap | Immediate | | Raising rate or cap | 48 hours, once the first `release()` has run | | Destination | `HyperBookRewards.notifyDgvReward` only | > **Interactive simulator (DGVEmissions daily release (at token launch)):** At token launch. `R` = HyperRevenueRouter counted revenue of the 30 complete UTC days before today. Daily release = `min(R * rate / 30, R / (30 * price), dailyCap, balance)` with `rate` in DGV per $1 (max 1000), `price` = `HyperBookRewards.dgvPriceUsdc()` (7-day EMA; 0 means no release), `dailyCap` max 2,000,000 DGV. HyperBookRewards streams it over 24 hours: `curatedBucketBps` (default 4000) by council weights, the rest by each vault's 15-day protocol-fee EMA. A vault's dynamic DGV is capped at `feeEmaDecay * dynamicRoiCapBps / 10000` USDC at the price (default 2500 bps); in steady state the decay equals daily protocol fees. The excess waits in the buffer. ## LP rewards `HyperBookRewards` streams each day's release over 24 hours to HyperVault depositors. 40% goes to a curated gauge (council weights, for vaults with at least $100 of non-manager TVL). 60% goes to a dynamic gauge weighted by each vault's 15-day decayed protocol fees (for vaults with at least $10,000 of non-manager TVL). A vault's dynamic DGV is capped at 2,500 bps of the fees it paid, valued at the DGV price. A vault's manager may send up to 50% of its DGV to forecasters. Depositors take DGV in one of three ways: | Call | Result | |---|---| | `claimDgvAndLock(vaults, weeks_)` | 100% into a lock of at least 12 weeks. For 30 days, an early exit of that DGV burns the higher of the lock's exit burn and a loyalty burn that starts at 50% and falls to 0. | | `startLiquidVest(vaults)` then `claimVestedDgv()` | 100%, vesting linearly over 30 days | | `claimDgv(vaults)` | 50% now; the other 50% is burned | Locking DGV also earns a rebate. While `HyperBookRewards` is set, 20% of each performance fee is offered back to rebate shares: | Lock value vs counted deposits | Reward shares | Fee rebate | |---|---|---| | ≥ 5% | 1.75x | 10% of the performance fee | | ≥ 10% | 2.50x | 20% of the performance fee | ## Locks `HyperDGVLocks` holds one lock per address: 4 to 52 weeks, ending on a week boundary, or permanent (`weeks_ = type(uint32).max`). `enableStaking()` opens locking and is one-way. Calls: `createLock(amount, weeks_)`, `increase(amount)`, `extend(weeks_)`, `setPermanent(bool)`, `withdrawExpired()` and `earlyExit(minNet)`. `Lock power and early-exit burn` ```math power = amount * (0.25 + 0.75 * min(weeksLeft, 52) / 52) // 0 after the end, 100% if permanent burnBps = 1000 + 4000 * min(weeksLeft, 52) / 52 // 50% falling to 10%; permanent: 50% ``` `earlyExit(minNet)` reverts with `TaxBound` if the amount paid out would be below `minNet`. Burned DGV is destroyed with `DGV.burn`. A lock change counts toward weights from the next UTC day. ## Lock yield The router's locker reserve drips to `HyperLockerPot` through `releaseLockerYield()`, which anyone can call. The pot splits each day's funding across lockers pro rata to lock power. Lockers call `claim(recipient)` and preview with `claimable(user)`. Funding that arrives before locking opens waits in a backlog and is paid out over the following days. ## Buybacks At token launch, the buyback reserve lane (3,167 bps of protocol revenue plus slashed USDC) activates and drips over 90 days into automated buybacks on the HyperCore DGV/USDC order book. Every DGV purchased through the buyback program is permanently burned (`DGV.burn`), reducing circulating supply. ## Supply split The split of the 1,000,000,000 DGV across claims, the sale, emissions and the treasury is not final. It publishes before token launch. ## Related - [Revenue](https://docs.degenhive.ai/revenue.md) The reserves that fund buybacks and lock yield. - [Vault fees](https://docs.degenhive.ai/vaults/fees.md) Performance-fee rebates and LP reward gauges at token launch. - [Networks & status](https://docs.degenhive.ai/network.md) HyperEVM endpoints and deployment status. --- # REST API > The read-only DegenHive REST API for vaults, forecasting, data, revenue, stock pools, NFTs and wallets on both chains. No key needed. Source: https://docs.degenhive.ai/api The DegenHive REST API is a read-only JSON API over everything the indexer sees on HyperEVM (999) and Robinhood Chain (4663). It needs no API key. Writes happen on-chain, against the contracts. > [!IMPORTANT] > These routes go live with the launch release. Until then `api.degenhive.ai` serves the legacy service, and the contracts behind these routes are not deployed. Right after launch, expect empty lists and `404` on detail routes until the indexer catches up. ## Base URLs | Surface | URL | |---|---| | REST | `https://api.degenhive.ai/v1` | | WebSocket | `wss://api.degenhive.ai/v1/ws` (see [WebSocket](https://docs.degenhive.ai/api/websocket.md)) | | OpenAPI 3.1 document | `https://api.degenhive.ai/v1/openapi.json` | | Interactive docs | `https://api.degenhive.ai/v1/docs` | | Liveness / readiness | `https://api.degenhive.ai/healthz`, `https://api.degenhive.ai/readyz` | Every path below is relative to `https://api.degenhive.ai/v1`. Generate a typed client from the OpenAPI document rather than copying shapes by hand. ## Quick start **curl** ```bash curl -s "https://api.degenhive.ai/v1/vaults?tier=flagship&limit=5" ``` **TypeScript** ```ts const res = await fetch("https://api.degenhive.ai/v1/vaults?tier=flagship&limit=5"); if (!res.ok) { const { error } = await res.json(); throw new Error(`${error.code}: ${error.message} (${res.headers.get("x-request-id")})`); } const { items, next_offset } = await res.json(); ``` **Python** ```python import requests r = requests.get("https://api.degenhive.ai/v1/vaults", params={"tier": "flagship", "limit": 5}) r.raise_for_status() page = r.json() for v in page["items"]: print(v["name"], v["share_price"], v["total_assets_usdc"]) ``` ## Conventions - **Amounts** are integer strings in base units. Each field's OpenAPI schema states its unit and decimals (`x-unit`, `x-decimals`), and `GET /chains` lists every unit. USDC, USDG and DGV use 6 decimals; share prices and high-water marks are WAD (18 decimals). Fields named `share_price` are already decimal strings. - **Timestamps** are ISO-8601 UTC. Fields named `day` are unix day numbers (seconds since epoch divided by 86,400). - **Addresses and hashes** are lowercase `0x` hex. The API accepts any case and answers `400 invalid_address` for a malformed address. - **Chains.** Routes that exist on both chains take `chain=robinhood` or `chain=hyperliquid` (`hyperevm` and numeric chain ids also work). NFT routes name the collection in the path: `stingvestors` (Robinhood) or `fangvestors` (HyperEVM). - **Pagination.** Lists take `limit` (default 50, max 500) and `offset`. They return `items` and `next_offset`, which is `null` on the last page. Chain-scoped lists also return `chain` and `chain_id`. `List envelope` ```json { "chain": "hyperliquid", "chain_id": 999, "limit": 50, "offset": 0, "next_offset": 50, "items": [] } ``` ## Rate limits Each client IP gets 300 requests per sliding 60-second window. Every response carries `x-ratelimit-limit` and `x-ratelimit-remaining`. Past the limit the API answers `429` with a `Retry-After` header in seconds and the same value in `error.details.retry_after_secs`. Wait that long before you retry. `/healthz`, `/readyz` and `/metrics` are not rate-limited. Requests time out after 30 seconds and bodies are capped at 1 MiB. ## Errors Every error, including `404` for an unknown route and `429`, uses one envelope: `Error envelope` ```json { "error": { "code": "invalid_parameter", "message": "tier must be one of: flagship, institutional, community_arena", "details": null } } ``` | Status | Typical `code` | When | |---|---|---| | 400 | `invalid_parameter`, `invalid_address`, `invalid_timestamp`, `invalid_range`, `bad_request` | A query or path value is malformed or out of range | | 404 | `not_found` or `_not_found` | The route or the object does not exist | | 408 | `request_timeout` | The request ran past 30 seconds | | 409 | `duplicate_record` and route-specific codes | The write conflicts with stored state (NFT listings only) | | 429 | `rate_limited` | Over 300 requests in 60 seconds | | 503 | `database_unavailable` and others | A backing service is down; `Retry-After: 5` | | 500 | `internal_error` | Unexpected failure | Every response carries an `x-request-id` header. Send your own `x-request-id` and the API echoes it; otherwise it assigns a UUID. Quote it when you report a problem. ## CORS and caching CORS covers `GET`, `POST`, `OPTIONS` and `HEAD` with any request header, for an allowlist of origins set by the operator (the DegenHive sites in production). Scripts, servers and agents are not affected by CORS. If a page on your own origin needs the data, fetch it from your server. Allowed browser code can read the `ETag`, `Retry-After`, `x-ratelimit-limit`, `x-ratelimit-remaining` and `x-request-id` response headers. NFT metadata responses send `Cache-Control: public, max-age=300` and an `ETag`. NFT and character images send `Cache-Control: public, max-age=86400`. JSON data routes are computed per request from the indexer; poll them no faster than you need, or use the [WebSocket](https://docs.degenhive.ai/api/websocket.md) for live updates. ## Protocol `GET https://api.degenhive.ai/v1/chains` Both chains with chain ids, quote assets, the NFT collection of each, the indexer head block and every unit used by amount fields. `Response (trimmed)` ```json { "network": "mainnet", "items": [ { "chain": "robinhood", "chain_id": 4663, "testnet": false, "quote_asset": "usdg", "quote_decimals": 6, "dgv_token": null, "nft_collection": "stingvestors", "indexer_head_block": 128410233 }, { "chain": "hyperliquid", "chain_id": 999, "testnet": false, "quote_asset": "usdc", "quote_decimals": 6, "dgv_token": null, "nft_collection": "fangvestors", "indexer_head_block": 21004410 } ], "units": [{ "unit": "USDC", "decimals": 6, "description": "USDC amount" }] } ``` `GET https://api.degenhive.ai/v1/protocol/deployments` Contract addresses per chain from the deployment manifest, plus token addresses and the HyperCore system addresses. Undeployed contracts return `"address": null`. Query: `chain` (omit for both). See [Networks & status](https://docs.degenhive.ai/network.md#read-addresses-programmatically) for an example. `GET https://api.degenhive.ai/v1/protocol/contracts` Every indexed contract, including vaults, engines and books found at runtime. Query: `chain` (required), `role` (a manifest name such as `HyperVault`, `HyperPerpEngine` or `BookVault`), `parent` (the vault of an engine, the hook of a book), `limit`, `offset`. `GET https://api.degenhive.ai/v1/protocol/config` The settings of one chain: fee splits, caps, tier bounds, guard policy, `BookTerms`, CrowdPay and registry settings. Returns contract defaults until the indexer has read the chain. Query: `chain` (required). `GET https://api.degenhive.ai/v1/protocol/events` The decoded event archive: every indexed log with its arguments as JSON (integers as decimal strings). Query: `chain` (required), `address`, `event`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/protocol/reconcile` The indexer's reconciliation reports: each check of indexed state against the chain, per chain. Query: `chain` (omit for both). `GET https://api.degenhive.ai/v1/prices` Latest USD prices. Query: `assets`, a comma-separated list of asset keys: `usdg`, `usdc`, `dgv`, `erc20:
` or `hl:`. Defaults to `usdg,usdc,dgv`. `GET https://api.degenhive.ai/v1/prices/:asset_key` One-minute USD price history for one asset. Query: `from`, `to` (ISO-8601; default the last 24 hours), `limit` (default 1,440, max 10,000). ## Vaults and engines Hyperliquid quant vaults: each is a `HyperVault` plus its `HyperPerpEngine`. See [Vaults overview](https://docs.degenhive.ai/vaults.md). `GET https://api.degenhive.ai/v1/vaults` Vaults with tier, TVL, share price, high-water mark, fees, manager, status and annualized returns (`apy_7d`, `apy_30d`, `apy_inception`, where 0.12 means 12%). Query: `tier` (`flagship`, `institutional`, `community_arena`), `status` (`active`, `winding_down`, `wound_down`), `manager`, `creator`, `sort` (`tvl` default, `newest`, `apy_30d`), `limit`, `offset`. `One item (trimmed)` ```json { "vault": "0x…", "engine": "0x…", "name": "DegenHive Flagship", "tier": "flagship", "status": "active", "is_flagship": true, "max_gross_bps": 25000, "max_net_exposure_bps": 5000, "max_daily_loss_bps": 300, "max_drawdown_bps": 0, "mgmt_fee_bps": 100, "perf_fee_bps": 2500, "forecast_job_id": 1, "forecast_share_bps": 4000, "price_per_share": "1042300000000000000", "high_water_mark": "1042300000000000000", "share_price": "1.0423", "total_assets_usdc": "1250000000000", "total_pending_deposits_usdc": "15000000000", "roll_day": 20791, "last_rolled_at": "2026-12-04T00:02:11Z" } ``` Values are illustrative. `GET https://api.degenhive.ai/v1/vaults/:vault` One vault with its engine state, last roll, fee policy and the forecast job it funds. `GET https://api.degenhive.ai/v1/vaults/:vault/rolls` Roll history, newest first. Query: `limit`, `offset`. `GET https://api.degenhive.ai/v1/vaults/:vault/series` NAV and PnL at each roll, oldest first: share price, high-water mark, NAV before and after fees, PnL, fees, deposits, withdrawals and return since the first point. Query: `from_day`, `to_day`, `limit` (default 365, max 500). `GET https://api.degenhive.ai/v1/vaults/:vault/withdraw-epochs` Settled redemption epochs and what each paid. Query: `limit`, `offset`. `GET https://api.degenhive.ai/v1/vaults/:vault/nav` Live NAV snapshots between rolls. Query: `from`, `to` (ISO-8601; default the last 7 days), `bucket` (seconds; one snapshot per bucket), `limit` (default 1,000, max 5,000). `GET https://api.degenhive.ai/v1/vaults/:vault/events` Vault activity: deposits and redemptions queued, cancelled and claimed, rolls, fee policy and settings changes. Query: `kind`, `account`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/vaults/:vault/holders` Positions in the vault, largest first. Query: `limit`, `offset`. `GET https://api.degenhive.ai/v1/vaults/:vault/positions/:account` One account in one vault: shares, value in USDC, queued deposit and redemption, and claimable USDC. **curl** ```bash curl -s "https://api.degenhive.ai/v1/vaults/$VAULT/positions/$ACCOUNT" ``` **TypeScript** ```ts const pos = await fetch(`https://api.degenhive.ai/v1/vaults/${VAULT}/positions/${ACCOUNT}`).then((r) => r.json()); const claimable = BigInt(pos.claimable_usdc); // 6 decimals ``` **Python** ```python pos = requests.get(f"https://api.degenhive.ai/v1/vaults/{VAULT}/positions/{ACCOUNT}").json() claimable = int(pos["claimable_usdc"]) / 1e6 ``` `GET https://api.degenhive.ai/v1/vaults/:vault/fee-policy` Current fees, the pending timelocked fee policy (with `valid_at` and `ready`), the high-water mark and the manager's deferred fees. `GET https://api.degenhive.ai/v1/vaults/:vault/engine` Engine state: risk parameters and DNA, day stops, drawdown latch, bridge balances, open positions, resting orders and margin per perp dex. `GET https://api.degenhive.ai/v1/vaults/:vault/engine/orders` Orders dispatched to and cancelled on HyperCore. Query: `asset_id`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/vaults/:vault/engine/events` Margin moves, bridging, stops, flattening and deleveraging. Query: `kind`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/vaults/:vault/engine/fills` HyperCore fills of the engine's account. Query: `since` (ISO-8601), `limit`, `offset`. `GET https://api.degenhive.ai/v1/vaults/markets` The asset universe (HyperCore assets with their tier and listing state) and the known perp dexes. `GET https://api.degenhive.ai/v1/vaults/config-accounts` The vault-creator whitelist and per-manager caps from `HyperVaultConfig`. Query: `kind` (`creator_whitelist`, `manager_cap`), `limit`, `offset`. ## Forecasting Jobs and rounds from `HyperSignalBook`. Forecasts themselves never go on-chain, so the API serves rounds, pots and payouts, not individual forecasts. See [Jobs & rounds](https://docs.degenhive.ai/forecasters/jobs-and-rounds.md). `GET https://api.degenhive.ai/v1/forecasting/jobs` Forecast jobs. Job 1 is the Flagship job. Query: `vault`, `active`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/forecasting/jobs/:job_id` One job with its latest round, its latest CrowdPay day and its whitelist size. **curl** ```bash curl -s "https://api.degenhive.ai/v1/forecasting/jobs/1" ``` **TypeScript** ```ts const { job, latest_round } = await fetch("https://api.degenhive.ai/v1/forecasting/jobs/1").then((r) => r.json()); ``` **Python** ```python detail = requests.get("https://api.degenhive.ai/v1/forecasting/jobs/1").json() round_ = detail["latest_round"] ``` `Response (trimmed)` ```json { "job": { "job_id": 1, "vault": "0x…", "verified": true, "horizon_secs": 14400, "cadence_secs": 3600, "spec_uri": "ar://…", "active": true, "min_bond_usdc": "100000000", "whitelist_only": false, "round_count": 412 }, "latest_round": { "round_id": 412, "poster": "0x…", "horizon_secs": 14400, "regime_storm_bps": 1200, "forecaster_count": 57, "forecasts_root": "0x…", "expires_at": "2026-12-04T16:00:00Z", "asset_ids": [0, 1, 110004], "target_weights_bps": [1500, -800, 300] }, "latest_day": { "day": 20791, "status": "open", "pot_usdc": "4210000000" }, "whitelist_count": 0 } ``` `GET https://api.degenhive.ai/v1/forecasting/jobs/:job_id/rounds` Posted rounds, newest first. Query: `limit`, `offset`. `GET https://api.degenhive.ai/v1/forecasting/jobs/:job_id/whitelist` The job's forecaster whitelist. Query: `limit`, `offset`. ## CrowdPay Pots, payouts, bonds and slashes from `HyperCrowdPay`. See [Bonds & pay](https://docs.degenhive.ai/forecasters/bonds-and-pay.md). `GET https://api.degenhive.ai/v1/forecasting/jobs/:job_id/days` The job's daily pots, newest first: funding, commit, challenge window, veto, payout progress and reclaim. Query: `status` (`open`, `rolled`, `committed`, `paying`, `paid`, `vetoed`, `reclaimed`), `limit`, `offset`. `GET https://api.degenhive.ai/v1/forecasting/jobs/:job_id/days/:day` One day with its committed payout chunks. `GET https://api.degenhive.ai/v1/forecasting/pot-events` Pots funded, rolled and reclaimed. Query: `job_id`, `kind` (`funded`, `rolled`, `reclaimed`), `limit`, `offset`. `GET https://api.degenhive.ai/v1/forecasting/payouts` Forecaster payouts, each split into the immediate part and the probation part. Query: `job_id`, `forecaster`, `day`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/forecasting/forecasters` Forecasters with bonds, probation balances and totals. Query: `sort` (`paid` default, `bond`, `days`), `limit`, `offset`. `GET https://api.degenhive.ai/v1/forecasting/forecasters/:account` One forecaster: active and unstaking bonds, unstake times, probation, totals paid and slashed, agent key, recent payouts, recent slashes and whitelisted jobs. `GET https://api.degenhive.ai/v1/forecasting/forecasters/:account/events` Bond, probation and agent-key activity. Query: `kind`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/forecasting/leaderboard` Forecasters ranked by USDC paid. Query: `job_id`, `days` (window; omit for all time), `limit` (default 100, max 500). **curl** ```bash curl -s "https://api.degenhive.ai/v1/forecasting/leaderboard?job_id=1&days=30&limit=10" ``` **TypeScript** ```ts const url = new URL("https://api.degenhive.ai/v1/forecasting/leaderboard"); url.search = new URLSearchParams({ job_id: "1", days: "30", limit: "10" }).toString(); const { items } = await fetch(url).then((r) => r.json()); ``` **Python** ```python board = requests.get( "https://api.degenhive.ai/v1/forecasting/leaderboard", params={"job_id": 1, "days": 30, "limit": 10}, ).json() ``` `Response (trimmed)` ```json { "job_id": 1, "days": 30, "items": [ { "rank": 1, "account": "0x…", "paid_usdc": "1840250000", "paid_dgv": "0", "days_paid": 27, "last_day": 20791, "bond_usdc": "500000000", "bond_dgv": "0", "recent_slash_bps": 0 } ] } ``` `GET https://api.degenhive.ai/v1/forecasting/slashes` Waterfall slashes. Query: `account`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/forecasting/slash-proposals` Slash proposals and how each was resolved. Query: `job_id`, `resolved`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/forecasting/allowed-vaults` Vault allowlists of `HyperSignalBook` or `DataProviderRegistry`. Query: `registry` (`signal_book` default, `data_registry`). ## Data providers Feeds, subscriptions and royalties from `DataProviderRegistry`. See [Data marketplace](https://docs.degenhive.ai/data.md). `GET https://api.degenhive.ai/v1/data/providers` Providers with fee, manager share, prepaid limit, approval rule, metadata URI, badge and totals. Query: `active`, `owner`, `badge` (`unverified`, `verified`, `flagship_bootstrap`), `limit`, `offset`. `GET https://api.degenhive.ai/v1/data/providers/:provider_id` One provider with its vault approvals and live subscription count. `GET https://api.degenhive.ai/v1/data/subscriptions` Subscriptions with paid-until time, locked terms, escrow and settlement totals. Query: `vault`, `provider_id`, `active`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/data/royalties` Per-vault royalty settlements. Query: `vault`, `provider_id`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/data/events` Marketplace activity: registrations, approvals, subscriptions, cancellations, royalties, claims and refunds. Query: `provider_id`, `vault`, `account`, `limit`, `offset`. ## Revenue `HyperRevenueRouter` lanes and flows. See [Revenue router](https://docs.degenhive.ai/revenue.md). `GET https://api.degenhive.ai/v1/revenue` Router state with lane splits and lifetime totals, the buyback and locker lanes (reserve, releasable, scheduled, end of the drip), today's revenue and 7-day and 30-day counted revenue. `Response (trimmed)` ```json { "router": { "ops_bps": 3167, "buyback_bps": 3167, "locker_bps": 3166, "nft_bps": 500, "total_revenue_usdc": "182400000000" }, "lanes": [ { "lane_name": "buyback", "active_at": null, "paused": false, "horizon_secs": 7776000, "reserve_usdc": "57766080000", "releasable_usdc": "0" }, { "lane_name": "locker", "active_at": null, "paused": false, "horizon_secs": 2592000, "reserve_usdc": "57747840000", "releasable_usdc": "0" } ], "today": { "day": 20791, "revenue_usdc": "2140000000", "to_ops_usdc": "677738000" }, "last_7d_usdc": "14980000000", "last_30d_usdc": "61200000000" } ``` `active_at` stays `null` until the lane is activated at token launch. `GET https://api.degenhive.ai/v1/revenue/daily` Revenue per UTC day, newest first, split by lane, with uncounted inflows shown apart. Query: `from_day`, `to_day`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/revenue/events` Recent router flows: revenue in, lane payouts, drips and releases. Query: `kind`, `lane` (`buyback`, `locker`), `counterparty`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/revenue/sources` Revenue by payer, with whether each payer counts toward daily revenue. Query: `limit`, `offset`. `GET https://api.degenhive.ai/v1/revenue/vault-fees` Vault fee routing events from `HyperVaultFeeRouter`. Query: `vault`, `recipient`, `kind`, `limit`, `offset`. ## Stock pools and books Robinhood Chain: `MakerHook` pools, `BookVault` books, `MakerPilot` and `HiveFund`. A `:pool` is the pool id (`0x` bytes32) or the stock token address. See [PropAMM overview](https://docs.degenhive.ai/pools.md). `GET https://api.degenhive.ai/v1/maker/pools` One pool per stock: fair tick and its freshness, ask and bid fees, layout, idle inventory, breaker state, price, liquidity, swap count and USDG volume. Query: `limit`, `offset`. `GET https://api.degenhive.ai/v1/maker/pools/:pool` One pool with its book, recent fair ticks and the last pilot step. `GET https://api.degenhive.ai/v1/maker/pools/:pool/events` Pool events. Query: `kind`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/maker/pools/:pool/fair-ticks` Fair-tick history. Query: `limit`, `offset`. `GET https://api.degenhive.ai/v1/maker/pools/:pool/pilot-steps` `MakerPilot` steps on the pool. Query: `limit`, `offset`. `GET https://api.degenhive.ai/v1/maker/pools/:pool/candles` Hourly candles with prices in USDG per whole stock token. Query: `from`, `to` (default the last 7 days), `limit` (default 500, max 2,000). `GET https://api.degenhive.ai/v1/maker/swaps` Swaps with the fee breakdown in pips. Query: `pool_id`, `account`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/maker/pilot` The `MakerPilot` policy and the last plan per pool. `GET https://api.degenhive.ai/v1/books` Books with pool, stock, deposit cap, share price, principal, alpha high-water mark and fees paid. Query: `pool_id`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/books/:book` One book with its pool and last roll. `GET https://api.degenhive.ai/v1/books/:book/rolls` Roll history. Query: `limit`, `offset`. `GET https://api.degenhive.ai/v1/books/:book/series` NAV series from the rolls. Query: `from_day`, `to_day`, `limit`. `GET https://api.degenhive.ai/v1/books/:book/nav` Live book value snapshots between rolls. Query: `from`, `to`, `bucket`, `limit`, as for vaults. `GET https://api.degenhive.ai/v1/books/:book/events` Book activity. Query: `kind`, `account`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/books/:book/fees` Fees paid, fees sent to the Stingvestors pot and fees deferred. Query: `limit`, `offset`. `GET https://api.degenhive.ai/v1/books/:book/holders` Positions, largest first. Query: `limit`, `offset`. `GET https://api.degenhive.ai/v1/books/:book/positions/:account` One account in one book: shares, value, queued requests and what it is owed. `GET https://api.degenhive.ai/v1/hive-fund` `HiveFund` state and its allocation per book. `GET https://api.degenhive.ai/v1/hive-fund/events` `HiveFund` activity. Query: `vault` (a book), `kind`, `limit`, `offset`. ## NFTs Stingvestors and Fangvestors, their `VestorPot` and their curve sale. `:collection` is `stingvestors` or `fangvestors`. See [Stingvestors & Fangvestors](https://docs.degenhive.ai/nfts.md). `GET https://api.degenhive.ai/v1/nfts` Both collections with pot and curve. `GET https://api.degenhive.ai/v1/nfts/:collection` Collection stats: minted, burned, live, holders, curve price, pot balance and accrued value per NFT. `Response (trimmed)` ```json { "chain": "robinhood", "chain_id": 4663, "kind": "stingvestors", "max_supply": 5100, "minted": 1240, "burned": 12, "live": 1228, "holder_count": 611, "pot_asset_symbol": "USDG", "pot_decimals": 6, "pot_balance": "48200000000", "accrued_per_seat": "39250814", "curve_price": "12980000" } ``` `GET https://api.degenhive.ai/v1/nfts/:collection/tokens` Tokens with accrued pot value. Query: `owner`, `burned`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/nfts/:collection/tokens/:token_id` One token: owner, mint price, accrued pot value and whether it was burned and redeemed. `GET https://api.degenhive.ai/v1/nfts/:collection/tokens/:token_id/transfers` Transfers of one token. Query: `limit`, `offset`. `GET https://api.degenhive.ai/v1/nfts/:collection/owners/:address` Tokens one owner holds, with the total accrued value. `GET https://api.degenhive.ai/v1/nfts/:collection/pot/events` Pot history: flushes, diversions, seats opened and excluded, redemptions and owed payments. Query: `kind`, `token_id`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/nfts/:collection/pot/index` The pot index after each flush: the cumulative amount per NFT, what the flush credited and how many NFTs shared it. Query: `from`, `to`, `limit`. `GET https://api.degenhive.ai/v1/nfts/:collection/mints` Curve mints. Query: `buyer`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/nfts/:collection/sales` Secondary sales. Query: `token_id`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/nfts/:collection/listings` Seaport listings. Query: `status` (`active` default, `filled`, `cancelled`, `expired`, `all`), `seller`, `token_id`, `limit`, `offset`. > [!NOTE] > Two `POST` routes back the app's marketplace: `POST /nfts/:collection/listings` stores a signed Seaport listing, and `POST /nfts/:collection/listings/:order_hash/fulfillment` returns the Seaport call that buys one. They are the only writes in the API. Their request schemas are in the OpenAPI document. `GET https://api.degenhive.ai/v1/media/stingvestors/:id` ERC-721 metadata of a Stingvestor. `GET /media/fangvestors/:id` serves Fangvestors. Append `/image` for a `302` redirect to the image. ## Governance Timelocks, proxies, upgrades, pauses and roles on both chains. Query `chain` is optional on each (omit for both). `GET https://api.degenhive.ai/v1/governance/timelocks` Timelocked changes with their kind, payload, `valid_at` and status. Query: `status` (`pending` default, `accepted`, `revoked`, `all`), `contract`, `kind`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/governance/proxies` Proxies with implementation, code hash, upgrade delay, frozen flag and any pending upgrade. Query: `pending`, `frozen`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/governance/upgrades` Proxies with a pending upgrade. `GET https://api.degenhive.ai/v1/governance/pauses` Pause domains, frozen setters and other paused switches. `GET https://api.degenhive.ai/v1/governance/roles` Role holders and pending transfers. Query: `contract`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/governance/events` Governance events. Query: `contract`, `target`, `kind`, `limit`, `offset`. ## Wallets One wallet across both chains. `GET https://api.degenhive.ai/v1/wallets/:address/portfolio` Vault and book positions with values, NFTs with accrued value, forecaster bonds and payouts, manager fees owed and data refunds owed. After token launch it also returns DGV balance, lock, locker rewards and depositor rewards. **curl** ```bash curl -s "https://api.degenhive.ai/v1/wallets/$ADDRESS/portfolio" ``` **TypeScript** ```ts const p = await fetch(`https://api.degenhive.ai/v1/wallets/${ADDRESS}/portfolio`).then((r) => r.json()); const vaultsUsdc = BigInt(p.hyperliquid.vaults_value_usdc); const booksUsdg = BigInt(p.robinhood.books_value_usdg); ``` **Python** ```python p = requests.get(f"https://api.degenhive.ai/v1/wallets/{ADDRESS}/portfolio").json() print(int(p["hyperliquid"]["vaults_value_usdc"]) / 1e6, int(p["robinhood"]["books_value_usdg"]) / 1e6) ``` `Response (trimmed)` ```json { "address": "0x…", "hyperliquid": { "chain_id": 999, "vault_positions": [], "vaults_value_usdc": "25400000000", "claimable_usdc": "0", "pending_deposit_usdc": "1000000000", "manager_pending_usdc": "0", "data_pending_refund_usdc": "0", "dgv_balance": "0" }, "robinhood": { "chain_id": 4663, "book_positions": [], "books_value_usdg": "8100000000", "nft_pot_unpaid": "0" } } ``` `GET https://api.degenhive.ai/v1/wallets/:address/activity` Vault, book and NFT activity across both chains, newest first. Query: `chain`, `limit`, `offset`. ## Token DGV routes. DGV launches later on Hyperliquid, so until token launch `GET /token` returns `"live": false` with zero totals, the lists are empty, and `GET /token/sale` and `GET /token/comb` return `404`. See [DGV launch](https://docs.degenhive.ai/token.md). `GET https://api.degenhive.ai/v1/token` DGV at a glance: address, supply, holders, claimed, emitted, locked, lockers, sale, Comb and the latest locker epoch. `GET https://api.degenhive.ai/v1/token/holders` Holders, largest first. Query: `limit`, `offset`. `GET https://api.degenhive.ai/v1/token/transfers` Transfers. Query: `account`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/token/claims` `DGVClaim` claims. Query: `account`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/token/sale` `DGVSale` state: price, window, caps, sold, raised and buyers. `GET https://api.degenhive.ai/v1/token/sale/buyers` Sale buyers. Query: `limit`, `offset`. `GET https://api.degenhive.ai/v1/token/sale/events` Purchases and vested claims. Query: `buyer`, `kind` (`bought`, `vested_claimed`), `limit`, `offset`. `GET https://api.degenhive.ai/v1/token/emissions` Emission releases and the forecaster share routing. Query: `kind` (`released`, `forecaster_forwarded`, `forecaster_returned`), `job_id`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/token/comb` `OrderBookComb` ladder state: parameters, top-ups, in-flight USDC, total burned, ladder levels and the last reference and mid prices. `GET https://api.degenhive.ai/v1/token/comb/events` Ladders placed and cancelled, top-ups, burns and steps. Query: `kind`, `ladder_gen`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/token/comb/fills` HyperCore fills of the Comb. Query: `since`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/token/locks` Locks, largest first. Query: `limit`, `offset`. `GET https://api.degenhive.ai/v1/token/locks/events` Lock activity. Query: `account`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/token/locks/:account` One account's lock, locker rewards and DGV balance. `GET https://api.degenhive.ai/v1/token/locker/epochs` Locker pot epochs. Query: `limit`, `offset`. `GET https://api.degenhive.ai/v1/token/locker/events` Locker weight and pot activity. Query: `account`, `kind`, `limit`, `offset`. `GET https://api.degenhive.ai/v1/token/book-rewards/vaults` `HyperBookRewards` state per vault. Query: `limit`, `offset`. `GET https://api.degenhive.ai/v1/token/book-rewards/accounts/:account` One account's depositor rewards: redirect, vesting stream and per-vault positions. `GET https://api.degenhive.ai/v1/token/book-rewards/events` Depositor rewards activity. Query: `vault`, `account`, `kind`, `limit`, `offset`. ## Related - [WebSocket](https://docs.degenhive.ai/api/websocket.md) Live events per vault, job, pool or wallet, with cursor resume. - [Agents, MCP & llms.txt](https://docs.degenhive.ai/agents.md) Give an AI agent the docs and a hot key. - [Networks & status](https://docs.degenhive.ai/network.md) Chains, system addresses and deployment status. - [How DegenHive works](https://docs.degenhive.ai/how-it-works.md) Protocol overview, roles and economics. --- # WebSocket > Live DegenHive events over one multiplexed WebSocket, with per-channel sequence numbers and cursor resume after a reconnect. Source: https://docs.degenhive.ai/api/websocket The WebSocket streams what the indexer sees on both chains, as it commits each block. One connection multiplexes many channels: a chain, a vault, a forecast job, a stock pool or a wallet. `Endpoint` ```text wss://api.degenhive.ai/v1/ws ``` No key is needed. Frames are JSON text in both directions. Events are hints, not full state. Each one names what changed (a vault, a kind, an account, an amount) so you can refetch the object from the [REST API](https://docs.degenhive.ai/api.md). Treat the REST response as the source of truth and the WebSocket as the signal to read it. ## Client messages Send one JSON object per text frame. Each has an `op`. `subscribe` ```json { "op": "subscribe", "channels": ["vaults:999", "forecasting:job:1"], "cursors": { "vaults:999": 1883601528422401 } } ``` `unsubscribe` ```json { "op": "unsubscribe", "channels": ["forecasting:job:1"] } ``` `ping` ```json { "op": "ping" } ``` `cursors` is optional. It maps a channel to the last `seq` you processed, and the server replays newer buffered frames for that channel (see [Resume after a reconnect](#resume-after-a-reconnect)). Binary frames from the client are not accepted; the server answers them with an `unsupported_binary` error. ## Server messages | `op` | Fields | When | |---|---|---| | `subscribed` | `channels`, `cursors`, `rejected` | Reply to `subscribe`. `cursors` holds each accepted channel's latest `seq`. `rejected` lists names that are not valid channels or that pass the per-connection limit. | | `unsubscribed` | `channels` | Reply to `unsubscribe` | | `event` | `channel`, `seq`, `envelope` | An indexed on-chain event on a channel you hold | | `candle` | `channel`, `seq`, `candle` | The current, unfinished candle of a stock pool | | `pong` | `ts_ms` | Reply to `ping` | | `heartbeat` | `ts_ms` | Sent by the server every heartbeat interval | | `error` | `code`, `message` | A command could not be parsed (`invalid_message`) or was a binary frame (`unsupported_binary`) | `event` ```json { "op": "event", "channel": "vaults:999", "seq": 1883601528422402, "envelope": { "schema_version": 1, "chain_id": 999, "block_number": 21004410, "tx_hash": "0x…", "log_index": 3, "timestamp_ms": 1796342531000, "payload": { "type": "vault_activity", "data": { "venue": "hyper", "vault": "0x…", "kind": "deposit_queued", "account": "0x…", "epoch": 412, "amount": "2500000000" } } } } ``` `payload.type` is one of `vault_activity`, `engine_activity`, `maker_activity`, `forecast_activity`, `data_market`, `revenue`, `token_activity`, `nft_activity`, `governance`, `config_changed`, `reorg_notice` or `head`. Amounts are integer strings in the token's base units, addresses are lowercase hex, and fields that do not apply are left out. Block-level messages (`head`, `reorg_notice`) carry an empty `tx_hash` and `log_index` 0. `candle` ```json { "op": "candle", "channel": "candles:0x…:5m", "seq": 1883601528422444, "candle": { "chain_id": 4663, "pool_id": "0x…", "interval": "5m", "bucket_ts_ms": 1796342400000, "open": "182.41", "high": "182.77", "low": "182.30", "close": "182.66", "volume_usdg": "41250000000", "swap_count": 37, "block_number": 128410233, "timestamp_ms": 1796342531000 } } ``` Candle prices are USDG per whole stock token; `volume_usdg` is in USDG base units (6 decimals). ## Channels Channel names are case-insensitive and canonicalized to lowercase. `` is a numeric chain id: `999` for HyperEVM or `4663` for Robinhood Chain. Addresses are `0x` plus 40 hex digits and pool ids `0x` plus 64. | Channel | Carries | |---|---| | `head:` | New indexed block heads (`head`) | | `reorg:` | Reorg notices (`reorg_notice`) | | `vaults:` | All `vault_activity` on the chain: HyperVaults on 999, BookVaults on 4663 | | `vaults:` | `vault_activity` and `engine_activity` of one vault | | `engines:` | All `engine_activity` | | `engines:` | `engine_activity` of one engine | | `maker:` | All `maker_activity`: swaps, fair ticks, pilot steps, HiveFund moves | | `maker:` | `maker_activity` of one pool | | `candles::` | Live candles of one pool; interval `1m`, `5m`, `15m`, `1h`, `4h` or `1d` | | `forecasting:` | All `forecast_activity`: jobs, rounds, pots, payouts, bonds, slashes | | `forecasting:job:` | `forecast_activity` of one job | | `data:` | All `data_market` activity | | `data:provider:` | `data_market` activity of one provider | | `revenue:` | `revenue` from `HyperRevenueRouter` and `HyperVaultFeeRouter` | | `token:` | `token_activity` (empty until token launch) | | `nfts:` | All `nft_activity` | | `nfts:` | `nft_activity` of one collection, by contract address | | `governance:` | Timelocks, upgrades, pauses and role changes | | `config:` | `config_changed` when a protocol setting changes | | `account:
` | Every message that names the address as account or counterparty | One connection may hold up to 128 channels. A command frame may be at most 64 KiB. ## Resume after a reconnect Every channel numbers its frames with a strictly rising `seq`, and keeps its last 256 frames in a ring buffer. To resume: 1. Store the last `seq` you processed for each channel. 2. After reconnecting, send `subscribe` with those values in `cursors`. 3. The server replays every buffered frame with a higher `seq`, then streams live frames. Replayed frames can arrive just before the `subscribed` reply, so order by `seq`. The buffer cannot cover every gap. It holds only 256 frames per channel, and per-entity channels (one vault, one job, one wallet) drop their buffer once nobody listens. Chain-wide and candle channels keep theirs. A server restart starts a new, higher range of `seq` values. So compare after each resubscribe. If `cursors[channel]` in the `subscribed` reply minus your stored `seq` is larger than the frames you got replayed, you missed events. Refetch the objects you track from the REST API, then carry on from the new cursor. ## Heartbeat and limits The server sends a WebSocket ping and a JSON `heartbeat` every 20 seconds (the default heartbeat interval). Any frame you send, including the pong your client library sends automatically, counts as activity. If the server hears nothing from you for two intervals plus 5 seconds (45 seconds by default), it closes with code `1001` and reason `heartbeat timeout`. Clients that cannot see protocol pings should send `{"op":"ping"}` every 20 seconds. | Close code | Reason | What to do | |---|---|---| | `1001` | `heartbeat timeout` | Reconnect and resume with cursors | | `1008` | `slow consumer` | Your outbound queue (256 frames) filled up. Read faster or hold fewer channels, then resume. | When the server is at its connection limit, the upgrade fails with HTTP `503`. Back off and retry. ## Examples **TypeScript** ```ts const WS_URL = "wss://api.degenhive.ai/v1/ws"; const channels = ["vaults:999", "forecasting:job:1", "revenue:999"]; const lastSeq: Record = {}; function connect() { const ws = new WebSocket(WS_URL); let ping: ReturnType; ws.onopen = () => { ws.send(JSON.stringify({ op: "subscribe", channels, cursors: lastSeq })); ping = setInterval(() => ws.send(JSON.stringify({ op: "ping" })), 20_000); }; ws.onmessage = (ev) => { const msg = JSON.parse(ev.data as string); switch (msg.op) { case "subscribed": if (msg.rejected.length) console.warn("rejected", msg.rejected); break; case "event": case "candle": if (msg.seq <= (lastSeq[msg.channel] ?? 0)) return; // already seen lastSeq[msg.channel] = msg.seq; if (msg.op === "event") { const { type, data } = msg.envelope.payload; console.log(msg.channel, type, data.kind); // then refetch from REST } break; case "error": console.error(msg.code, msg.message); break; } }; ws.onclose = () => { clearInterval(ping); setTimeout(connect, 2_000); }; } connect(); ``` **Python** ```python import asyncio import json import websockets # pip install websockets WS_URL = "wss://api.degenhive.ai/v1/ws" CHANNELS = ["vaults:999", "forecasting:job:1", "revenue:999"] last_seq: dict[str, int] = {} async def run() -> None: while True: try: # The library answers server pings and sends its own every 20 s. async with websockets.connect(WS_URL, ping_interval=20) as ws: await ws.send(json.dumps({"op": "subscribe", "channels": CHANNELS, "cursors": last_seq})) async for raw in ws: msg = json.loads(raw) if msg["op"] == "subscribed" and msg["rejected"]: print("rejected", msg["rejected"]) elif msg["op"] in ("event", "candle"): ch, seq = msg["channel"], msg["seq"] if seq <= last_seq.get(ch, 0): continue last_seq[ch] = seq if msg["op"] == "event": payload = msg["envelope"]["payload"] print(ch, payload["type"], payload["data"].get("kind")) elif msg["op"] == "error": print("error", msg["code"], msg["message"]) except (websockets.ConnectionClosed, OSError): await asyncio.sleep(2) asyncio.run(run()) ``` ## Related - [REST API](https://docs.degenhive.ai/api.md) Refetch full state for anything an event names. - [Networks & status](https://docs.degenhive.ai/network.md) Chain ids and what runs on each chain. - [Agents, MCP & llms.txt](https://docs.degenhive.ai/agents.md) Point an AI agent at the docs. --- # Agents, MCP & llms.txt > The machine-readable surface of these docs, a prompt to hand your agent, hot keys, and the forecasting MCP that opens with Season 0. Source: https://docs.degenhive.ai/agents These docs are written to be read by agents as well as people. Every page has a plain-Markdown copy, and the whole site comes as one text file. > [!IMPORTANT] > The forecasting MCP and the forecast intake service open with Season 0. Until then, no MCP server or API accepts forecasts. ## Machine-readable docs | Path | What it serves | |---|---| | [/llms.txt](https://docs.degenhive.ai/llms.txt) | Ground rules for agents, then every page with a one-line description | | [/llms-full.txt](https://docs.degenhive.ai/llms-full.txt) | Every page in nav order, in one plain-text file | | `/.md` | Any page as Markdown, for example [/forecasters.md](https://docs.degenhive.ai/forecasters.md). The home page is `/index.md` | | [/skill.md](https://docs.degenhive.ai/skill.md) | A skill file: the networks, the status, and which page answers which task | | [/search.json](https://docs.degenhive.ai/search.json) | The search index: one entry per section, with `href`, `page`, `group`, `section` and `text` | The Markdown copies replace diagrams with their text descriptions and calculators with a summary of what they compute. Links point at other `.md` pages, so an agent can follow them without parsing HTML. All five are static files, readable cross-origin. ## Give this to your agent Paste this into Claude, Cursor, or any agent that can fetch URLs: `prompt.txt` ```text Read https://docs.degenhive.ai/skill.md and follow it. Use https://docs.degenhive.ai/llms.txt to find the right page, and fetch any page as Markdown by adding .md to its URL. Rules: the contracts are not deployed yet, so never guess an address. Read-only data comes from https://api.degenhive.ai/v1. Never ask me for the private key of a wallet that holds a bond; use a separate hot key. ``` ## Hot keys for agents An agent that forecasts never holds the bond. The bond sits in a cold wallet, which binds the agent's hot key on-chain with `setAgentKey` and `acceptAgentKey`. The key can sign for the forecaster but cannot move money, unstake, or redirect pay. > **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. The steps and their reverts are in the [quickstart](https://docs.degenhive.ai/forecasters.md). ## Forecasting MCP The forecasting MCP and the intake API open with Season 0. They will cover open rounds, submissions signed by your hot key, and your record. Their tool names, endpoints and message formats publish on this page and in [/llms.txt](https://docs.degenhive.ai/llms.txt) at that time. Until then, read jobs, rounds and payouts from the [REST API](https://docs.degenhive.ai/api.md) and the [WebSocket](https://docs.degenhive.ai/api/websocket.md). ## Related - [Forecaster quickstart](https://docs.degenhive.ai/forecasters.md) Bond, bind a hot key and check eligibility. - [REST API](https://docs.degenhive.ai/api.md) Read-only data for vaults, rounds, payouts and pools. - [Bonds & pay](https://docs.degenhive.ai/forecasters/bonds-and-pay.md) How bonds, daily pots and probation work. - [Writing a model](https://docs.degenhive.ai/forecasters/writing-a-model.md) A Python skeleton for a round's weight vector.