# Elyra documentation > Elyra is a liquidity venue and an LP, hedging and perps toolkit on Elysium (chain id 99901, gas in HYPE): Uniswap v3 and v4 liquidity management, Elyra's own pools, ERC-4626 vaults and a swap router. Elyra never holds a key and never asks for a private key, a seed phrase or a session key. The chapters of https://elyratrade.io/docs as plain text, in reading order. The index is https://elyratrade.io/llms.txt. --- # Introduction Source: https://elyratrade.io/docs/overview · Get started What Elyra does on Elysium, the rules it will not bend, and where to read next. Elyra is a trading and liquidity app on Elysium, Kinetiq's chain beside Hyperliquid. From one wallet you can swap, trade perps on Hyperliquid, put liquidity to work in a pool, a range or a vault, hedge a stock position and launch a token. This page covers what you can do, the rules the contracts keep, and where each topic is explained. In brief: - Elyra runs on Elysium, chain id 99901, and nowhere else. Gas is paid in HYPE, the stablecoin is USDC. - No contract sits behind a proxy, and no admin function can withdraw, move or freeze what you hold. - Perp orders go to Hyperliquid, signed by a trade-only agent wallet you approve once. It can place and cancel orders and cannot withdraw. - Tokenised stocks are EQX tokens bridged from HyperEVM. Their on-chain price comes from Elyra's own keeper-updated feed. - $ELYRA is the protocol token: protocol fees buy it and burn it. ## What you can do | You want to | Use | Read | | --- | --- | --- | | Swap one token for another | Swap, or Buy and Sell on Trade | [Swaps and routing](https://elyratrade.io/docs/swaps) | | Sell at a price, earning fees while you wait | Limit on Trade, or a DLMM pool | [Limit orders](https://elyratrade.io/docs/range-orders) | | Trade perps with leverage | Trade | [Perpetuals](https://elyratrade.io/docs/perps) | | Earn on a deposit without managing a range | Earn | [Vaults](https://elyratrade.io/docs/vaults), [Hedged vaults](https://elyratrade.io/docs/hedged-vaults), [Structured notes](https://elyratrade.io/docs/structured) | | Provide liquidity yourself | Pools, or the Liquidity mode on Trade | [Elyra pools](https://elyratrade.io/docs/pools), [One-token deposits](https://elyratrade.io/docs/zap) | | Keep a position harvested and centred | Portfolio | [Position automation](https://elyratrade.io/docs/keeper) | | Launch a token, or trade one before it lists | Launch | [Launch a token](https://elyratrade.io/docs/launch), [Graduation and pre-market perps](https://elyratrade.io/docs/graduation) | Swaps route across Elyra's own pools (DAMM, DLMM and stock pools) and public Uniswap v4 pools on Elysium. Perps run on Hyperliquid, stock perps on its HIP-3 `xyz` markets; a token no venue lists can trade on Elyra's own pre-market perp. [Using the app](https://elyratrade.io/docs/app-guide) walks through every page. ## Rules that hold everywhere **One chain.** Every contract is deployed on Elysium (99901), and the app sends transactions there only; development builds also accept a local test chain. Contracts and transactions open on the [Elysium explorer](https://elysium.kinetiq.xyz/explorer). **What the owner can and cannot do.** Contracts cannot be upgraded, and no owner function can withdraw, transfer or freeze a position, a vault share or a deposit. The venue's owner can pause swaps and new liquidity, never withdrawals, and tune fees and limits, most of them inside caps written into the contracts. The DLMM and stock vaults can be re-laid by their keeper or the owner, inside the same on-chain guards. [Security model](https://elyratrade.io/docs/security) lists each key and its bounds. **Perps stay in your Hyperliquid account.** Collateral is USDC in your own Hyperliquid account. Your wallet approves an agent wallet that signs orders for you, and a builder fee that is Elyra's charge on perps. Withdrawals from Hyperliquid always need your wallet. Funding the account from Elysium means bridging USDC out first, which takes about 24 hours. **Stock prices.** Elysium has no third-party oracle network. Stock pools, stock vaults and the HYPE price the contracts read come from Elyra's own price feed, which a keeper updates. Each read checks the feed's age, and a stale price changes how a pool trades. **Fees on earnings, not principal.** A zap or a Uniswap-path spot trade costs 25 bps, a managed position pays 10 % of the fees it earns, and Elyra pools send 20 % of their swap fee to the protocol. Every fee and the 20 % referral share are in [Fees and referrals](https://elyratrade.io/docs/fees). **$ELYRA.** Protocol fees become HYPE, the HYPE buys $ELYRA, and the $ELYRA is burned, each step by a call anyone can make. See [Buyback and burn](https://elyratrade.io/docs/protocol). ## How these docs are arranged | Group | Chapters | Read it when | | --- | --- | --- | | Get started | Introduction, [Using the app](https://elyratrade.io/docs/app-guide), [What's new](https://elyratrade.io/docs/whats-new), [The Lounge](https://elyratrade.io/docs/lounge) | you are new, or looking for a page | | Trade | [Swaps and routing](https://elyratrade.io/docs/swaps), [Limit orders](https://elyratrade.io/docs/range-orders), [Perpetuals](https://elyratrade.io/docs/perps) | you want to know how an order fills | | Earn | [Vaults](https://elyratrade.io/docs/vaults), [Hedged vaults](https://elyratrade.io/docs/hedged-vaults), [Structured notes](https://elyratrade.io/docs/structured) | you are choosing where to deposit | | Pools | [Elyra pools](https://elyratrade.io/docs/pools), [One-token deposits](https://elyratrade.io/docs/zap), [Position automation](https://elyratrade.io/docs/keeper) | you manage liquidity yourself | | Launch | [Launch a token](https://elyratrade.io/docs/launch), [Graduation and pre-market perps](https://elyratrade.io/docs/graduation) | you are launching or backing a new token | | Protocol | [Buyback and burn](https://elyratrade.io/docs/protocol), [Fees and referrals](https://elyratrade.io/docs/fees), [Security model](https://elyratrade.io/docs/security) | you want to know where money goes and who can do what | | Reference | [Architecture](https://elyratrade.io/docs/architecture), [Indexer, API and bots](https://elyratrade.io/docs/offchain), [Agents and integrations](https://elyratrade.io/docs/agents), [Glossary](https://elyratrade.io/docs/glossary) | you are building on Elyra | Diagrams are drawn from data in the repository, so a label in a diagram matches a function, a field or a constant in the code. Where it lives: - `contracts/src/`: every contract, none upgradeable - `contracts/script/ElyraWiring.sol`: the deploy sequence and its values - `contracts/script/venue/VenueWiring.sol`: the venue deploy and its owner hand-over - `docs/project-brief.md`: the product decisions --- # Using the app Source: https://elyratrade.io/docs/app-guide · Get started Each page of the app in a paragraph: what it is for, what it reads, and what it can sign. This chapter goes through the app page by page: what each page is for, where its numbers come from, and what it can ask you to sign. It describes behaviour rather than layout, which changes more often. Each section ends with the chapter that explains the mechanism underneath. In brief: - Every on-chain write is simulated first. If the simulation reverts, your wallet never opens. - Approvals are always for the exact amount, never unlimited. - A write needs a connected wallet, Elysium (99901) and deployed contracts. A disabled button says which one is missing. - Perp orders are messages you sign, not transactions. On Hyperliquid they are signed by your agent wallet, which cannot withdraw. ## Before you start ### Signing in When the build has a Privy app id (`NEXT_PUBLIC_PRIVY_APP_ID`), you sign in with email or a wallet. Signing in by email creates an embedded wallet if you have none. Without Privy, the app offers browser wallets, plus WalletConnect wallets when a WalletConnect project id is configured. The top bar shows the network you are on. On any other network it shows a "Wrong network" button that switches you to Elysium; pressing an action does not switch for you. Development builds also accept a local test chain. ### When data does not load Pages read the Elyra API. When it cannot be reached, a page shows its empty state and a "Data is not loading" notice with a Try again button. Nothing is filled in by guesswork, and signing does not depend on it: every write is checked against the chain first. ### How a write is sent 1. Check: The app checks the wallet, the network and that the contract is deployed, and stops with the reason if one is missing. 2. Simulate: It runs the call as an eth_call. A revert stops here, with the reason in a toast, before your wallet opens. 3. Confirm: Your wallet asks you to confirm. Rejecting it shows as "Rejected in the wallet". 4. Send: Once the transaction has a hash, a toast links to it on the Elysium explorer. 5. Refresh: The affected data reloads 1.5 s, 4 s and 10 s later, so the indexer has time to catch up. Approvals come first when a token needs one. They are for the exact amount; an existing allowance of a different size is reset to zero first, as some tokens require. Permit2 is used only for the Uniswap Universal Router and the v4 position manager, and its allowance expires after 30 minutes. Approvals are the one step that waits for the receipt before the next button unlocks. Slippage defaults to 50 bps for a spot trade and 100 bps for a zap; above 500 bps you have to tick an acknowledgement first. ### Perp orders Every perp action (set up, place, cancel) is an EIP-712 message you sign, with a fresh nonce and a timestamp. The server decides the venue: the default is an in-memory practice book; the live venue sends real orders to Hyperliquid. To trade on Hyperliquid you need USDC in your own Hyperliquid account. The Perp ticket then asks your wallet for two approvals, each signed once: one that approves Elyra's agent wallet for your account, and one that approves Elyra's builder fee. The agent wallet places and cancels orders and cannot withdraw. See [Perpetuals](https://elyratrade.io/docs/perps). ### The tour The landing page's "Take the tour" opens `/liquidity?tour=1`, a guided walk through the main pages. It moves between pages for you; Esc ends it and the arrow keys step through it. Your place is kept in the browser until you finish or end it. The Planner also has its own short guide. ## Managed liquidity ### Liquidity The page the app leads with, for liquidity that is managed for you. Three cards set out the ways in: provide with one token, hand the range to the keeper, or let a vault run it. Under them: - **Choose a market.** The deepest public Uniswap pools from `GET /radar`, one row per asset, with price, pool APR and pool TVL. **Provide** opens Trade on the Liquidity ticket (`/trade/?provide=1`), where you set the range on the chart and the zap mints it from one token. - **Your ranges.** The connected wallet's Uniswap ranges from `GET /portfolio/:address`, the ones that left their band with nobody managing them first. Each row says whether it is in range, what it is worth, the fees waiting and who manages it. **Automate** opens the keeper policy. On a range the keeper holds, **Re-centre now** calls `PositionKeeper.rebalance` once it is out of range and **Stop keeper** calls `unenroll`. The keeper takes Uniswap v3 positions only; a v4 range links to Portfolio. - **Vaults that run their own range.** The LP, hedged, DLMM and stock vaults, largest first, with APR and TVL. **Deposit** opens that vault's deposit on Earn. Re-centring keeps a range earning; it does not undo the price move. Taking the price risk off is the hedge's job: the Hedge panel on Markets, or a hedged vault. Read [Position automation](https://elyratrade.io/docs/keeper) and [Vaults](https://elyratrade.io/docs/vaults). ## Trading pages ### Markets A ranked list of every asset across public Uniswap pools on Elysium and Hyperliquid perps, for finding where liquidity earns. Rows come from `GET /radar` and show price, 24h change, pool fee APR, funding and **carry**: the pool's fee APR plus a year of the perp funding rate, shown only when the asset has both a pool and a perp market (8 % and up is worth watching, 20 % and up is strong). An EQX stock token is paired with its HIP-3 market on Hyperliquid's `xyz` dex, so EQNVDA reads `xyz:NVDA` and EQSPY reads `xyz:SP500`. Tabs narrow the list to Crypto, Tokenized or Seasoned, and a search field filters it. Elyra's own pools sit in a separate block under the list. The **Seasoned** label marks a token whose pool is at least 3 days old, with a market cap above $1M and 100 or more trades in the last 24 h (`isEstablished` in the code); it is a label, not a gate. Selecting a row opens its market brief beside the list: carry as one bar split into pool fees, funding received and hedge cost, with pool depth and perp open interest under it. The brief has three actions. **Trade** opens the asset on Trade, **Plan** opens it in the Planner, and **Hedge** pairs an LP position with a perp short sized to its delta: it sends you to Trade to provide the liquidity, then signs the short as a perp order. A `?basis=` link selects that asset. Read [Perpetuals](https://elyratrade.io/docs/perps) and [Hedged vaults](https://elyratrade.io/docs/hedged-vaults). ### Watchlist Star a market with the star beside it, in the trade terminal's market switcher (press `/`) or on Markets. Starred markets sit at the top of the switcher, and the **Starred** tab in both lists shows only them. - **Without a wallet** the stars are kept in this browser. - **With a wallet connected** they are kept with your wallet address, so they are the same on every device you connect it on. Each change is a message your wallet signs (EIP-712 `WatchlistUpdate`, sent to `POST /watchlist`), not a transaction, and stars made within 1.5 s of each other are signed together. The line under the Starred tab reads "Synced to your wallet". - **The first time a wallet connects** while this browser holds stars, the switcher and Markets offer once to add them to the wallet's list. Adding keeps everything the wallet already starred. - A watchlist holds up to 100 markets. It is not private: `GET /watchlist/
` answers for any address, and a `?as=0x…` link shows that address's stars without letting you change them. ### Trade A terminal for one asset. A market bar across the top shows the price, 24h change, funding and open interest; click the asset name or press `/` to switch markets. The ticket has four modes, Spot, Perp, Limit and Liquidity, with a Buy and Sell (Long and Short) toggle; the chart sits beside it, with Positions, Orders, History, Funding and Ideas tabs under it. On a phone the ticket opens from a Trade button. The page reads `GET /radar`, `GET /markets`, `GET /marks` and `GET /candles`, and before it builds a spot trade it checks the pool's price on chain against the API's. While the tab is open it stays live: the price, the newest candle and your open perps' mark price and open PnL move with the mark every 2 s, the market facts, your positions and your orders refresh every 15 s, and the candles every minute. A hidden tab pauses all of it and catches up when you come back. The **order book** and **recent trades** are Hyperliquid's, from `GET /book` and `GET /trades`, refreshed every second while they are on screen. On a wide screen they sit in a column beside the ticket, which you can fold away; on a narrower one they are the Order book tab under the chart. Group the book's prices with the tick buttons; each level shows its size, the running total and a depth bar, with the spread and the mid between the two sides. Clicking a level opens the Perp ticket as a limit order at that price. - **Spot.** The line under the amount shows your balance of the token you pay with, and Max fills it in, keeping a little HYPE back for gas when you pay in HYPE; an amount above your balance turns the button into "Insufficient". Uniswap's quoter prices the market's pool, the Elyra Router's route search prices every Elyra route, and both refresh every 15 s. The ticket shows what you get, the minimum, the price impact and the route; price impact of 1 % or more shows a warning, 5 % or more needs your acceptance, and 15 % or more is refused. The default path is the Uniswap Universal Router (approve to Permit2, then `execute`), which pays a 25 bps Elyra fee from the output. When the Elyra Router pays more on a live quote, the trade goes through `Router.swapExactIn` instead, with one approval and no Elyra fee. - **Perp.** Size by notional, by a share of your available margin (25, 50 or 75 % or Max, at the chosen leverage) or by risk budget, leverage from 1x to the market's maximum, market or limit, reduce-only, optional stop-loss and take-profit. A line above the size shows your equity, available margin and margin in use (`GET /perp/account`). Market orders carry a 1 % price tolerance. The liquidation price shown is Elyra's estimate, not Hyperliquid's figure. - **Liquidity.** One token in, a Uniswap range out, through `ElyraZapV3.zapMint` or `ElyraZapV4.zapMint` (25 bps of the input). Range shapes are Spot, Curve, Wide and Custom; a stock pool's range widens while the market is closed. - **Limit.** `RangeOrders.place` parks a one-sided position that sells as the price crosses it; it works on Uniswap v3 pools. Where the asset has an Elyra DLMM pair, the page links to its limit orders. The Positions tab lists each perp with its ROE, liquidation price and the funding it has paid or received. Close opens a drawer that closes a share of the position or all of it, at market or as a reduce-only limit. **SL / TP** changes a stop or target in place, and the Orders tab edits a resting order's price or size, shows how much has filled and keeps a bracket's orders together. History lists your perp fills (side, maker or taker, realised PnL) and Funding the hourly funding settled on each position. The chart draws the open perp's entry and liquidation price and its resting limit orders. Your positions on the page can be closed, collected (`collect`), removed (v3: `decreaseLiquidity`, then `collect`; v4: one `modifyLiquidities` call), enrolled for automation (`PositionKeeper.enroll`) or cancelled (`RangeOrders.cancel`). Read [Swaps and routing](https://elyratrade.io/docs/swaps), [One-token deposits](https://elyratrade.io/docs/zap) and [Limit orders](https://elyratrade.io/docs/range-orders). ### Keyboard shortcuts Wider than 640 px, the trade terminal answers single keys; press `?` there, or click **Keyboard shortcuts** under the ticket, for the list. No key sends or cancels an order: `O` only moves the focus to the order button, and the order goes when you press Enter or click it. | Key | What it does | | --- | --- | | `1` `2` `3` `4` | The Spot, Perp, Limit or Liquidity ticket | | `B` / `S` | Buy or Sell (Long or Short on Perp) | | `A` | Put the cursor in the amount (on Perp, the size) | | `O` | Move the focus to the order button | | `M` / `L` | Perp: a market or a limit order | | `Q` `W` `E` `R` | Perp: size from 25, 50 or 75 % or all of your free margin, at the chosen leverage | | `+` / `-` | Perp: leverage up or down by 0.5x, within 1x and the market's maximum | | `/` | Change market | | `Esc` | Leave a field, or close a drawer or the list | | `?` | Open the list | Q W E R need your perp account loaded with free margin, like the buttons they stand for. Keys do nothing while you type in a field (Esc leaves it), with Ctrl, Cmd or Alt held, or while a drawer is open, and a held `+` or `-` keeps stepping. On a phone, where the ticket is a bottom sheet, they are off. The switch at the top of the list turns them off and on, and this browser remembers it; while they are off, `?` still opens the list. The chart keeps its own keys: Esc stops drawing, Ctrl or ⌘ + Z undoes (with Shift, redoes) and Delete removes the selected drawing. ### Swap Any token for any token through the Elyra Router, which splits a trade across Elyra pools and public Uniswap v4 pools. Quotes come from `Router.quoteExactIn`; without a deployed Router, routes are estimates and cannot be sent. The write is an exact approval to the Router, then `Router.swapExactIn`; native HYPE needs no approval. Price impact of 1 % or more shows a warning, 5 % or more needs your acceptance, and 15 % or more is refused. Slippage defaults to 50 bps and the deadline is 20 minutes. Max keeps a little HYPE back for gas when you pay in HYPE. You can paste any token address, and the `?in=`, `?out=` and `?amt=` parameters make a swap shareable as a link. No Elyra fee is added. Read [Swaps and routing](https://elyratrade.io/docs/swaps). ## Liquidity, launches and your positions ### Pools Elyra's own pools: DAMM (dynamic-fee Uniswap v4 pools), DLMM bin pairs and stock pools banded to Elyra's price feed. Data comes from `GET /pools`, `GET /pools/:id` and `GET /stocks`. - **Create a pool**, one permissionless transaction: `DammHook.createPool`, `DlmmFactory.createPair` or `StockHook.createPool`. - **DLMM pairs.** Add liquidity over a chosen number of bins in a Spot, Curve or Bid-Ask shape (`DlmmPositionNFT.mint`), or place, claim and cancel a limit order (`DlmmLimitOrders`). - **DAMM and stock pools.** Add a full-range or custom-band position through the v4 position manager. A stock pool also shows its feed price, the gap between pool and feed, the band and the market session. Read [Elyra pools](https://elyratrade.io/docs/pools). ### Earn Every vault in one list, filterable by kind. It reads `GET /vaults`, `GET /amm/vaults`, the graduated vaults from `GET /launch`, and share balances and previews on chain. - **LP vaults:** approve, then `deposit`; withdraw with `redeem`. - **DLMM and stock vaults:** deposit both tokens, or one token into a DLMM vault through `DlmmVaultZap`; withdraw to both tokens or, for DLMM, to one. - **Hedged vaults:** approve, then `deposit`, like an LP vault. The card and the deposit drawer say where the hedge margin is: on Hyperliquid, in an account the vault's funder key controls. - **Protected notes:** approve, then `deposit`. A note opens once the hedged vault under it has sent its first hedge report, and while that vault is paused the app holds both deposits and exits. Leaving before maturity costs 0.5 %, and the withdraw drawer shows the amount after the fee. - **Income notes** are listed as Coming soon and take no deposits. A deposit is also blocked when a vault is paused, its hedge report is stale, a hedged vault has never been reported on, or it is past maturity or settled. A vault's own page shows its range or bins, its keeper and its recent rebalances. Read [Vaults](https://elyratrade.io/docs/vaults), [Hedged vaults](https://elyratrade.io/docs/hedged-vaults) and [Structured notes](https://elyratrade.io/docs/structured). ### Launch Two tabs, Launch a token and Graduation, fed by `GET /launch` and on-chain reads. - **Launch a token** creates a fixed-supply token and its locked HYPE pool in one transaction (`LaunchPools.launch`), with an anti-snipe fee that decays after launch, or opens a pre-launch vault (`LaunchVault.open`) that pools buyers' HYPE and refunds it if nobody launches within 3 days. A launch's pool fees can be collected here; they go to its fee recipient, the creator at launch. - **Graduation** tracks a young token and graduates it into a managed vault (`LaunchPipeline.track`, `graduate`, both public); counts across the top show how many tokens are tracked, on the clock, ready to graduate and graduated. It also lists pre-market perps: 3x markets on tokens no venue lists, opened with USDC (`PreMarketPerp.open`, `close`, `createMarket`). Read [Launch a token](https://elyratrade.io/docs/launch) and [Graduation and pre-market perps](https://elyratrade.io/docs/graduation). ### Portfolio Everything an address holds: Uniswap v3 and v4 ranges, DLMM positions and limit orders, vault shares, range orders, perps and automation. It reads `GET /portfolio/:address` and reads DLMM and vault positions on chain. Remove on a v4 range is one `PositionManager.modifyLiquidities` call that pays the fees out with the liquidity; its pool key and ticks are read from the position manager and its minimums from the pool's `StateView` price. Add `?as=0x…` to view any address read-only. From here you can harvest, rebalance or unenroll an automated position, enroll a new one, remove liquidity, cancel a range order, withdraw or burn a DLMM position, cancel or claim a DLMM limit order, close a perp or set its stops, and claim referral earnings. Read [Position automation](https://elyratrade.io/docs/keeper). ## More pages ### Lounge Elyra's community view, with no chat: the points leaderboard (`GET /points/leaderboard`, your own row marked), a live feed of ideas, vault deposits and withdrawals, new pools, graduations and filled limit orders (`GET /lounge/feed`, every 15 s while the tab is open), and the week's top ideas. Every address opens its profile at `/lounge/u/
`: ideas, track record, points, followers and referrals. Follow is a signed message (EIP-712, no gas); switch the feed to Following to see only those addresses. Read [The Lounge](https://elyratrade.io/docs/lounge). ### Stocks Elyra's EQX stock pools, refreshed every 20 s from `GET /stocks`: feed price, pool price, the gap between them, the band, the current fee, the market session and TVL. The open or closed status uses NYSE hours on your device's clock. A stock with no pool offers to create one at the feed price (`StockHook.createPool`). Only the EQX addresses in Elyra's chain config are listed; other tokens with stock names are not. Read [Elyra pools](https://elyratrade.io/docs/pools). ### Protocol Where fees go: fees by token, conversions, buybacks, burned supply and the $ELYRA price, from `GET /protocol` and live chain reads. Each step has a button anyone can press: `FeeRouter.flush`, the fee collector's conversion and forwarding calls, `BuybackV2.buyback` (with optional HYPE of your own) and `poke`. A call that would revert shows its reason in plain words. Until $ELYRA exists, the buyback steps show that they are not configured yet. Read [Buyback and burn](https://elyratrade.io/docs/protocol). ### Ideas A feed of **ideas**: a real position with the argument for it, its PnL and a leaderboard, from `GET /theses`. To post one, pick one of your own positions and write up to 500 characters; you sign the idea (EIP-712, no gas). **Mirroring** copies an idea: a perp idea becomes an order you confirm and sign, a vault idea opens the deposit, and an LP idea opens Trade with the range filled in. Each idea has its own page with a share link and card. An author's address opens their Lounge profile. Opened from a `?ref=` link, the page raises a strip that binds you to that referrer in one click, on chain, if you have none yet. Your own code is registered on the Portfolio page's Referrals tab. Read [Fees and referrals](https://elyratrade.io/docs/fees). ### Alerts Watches any address's LP and perp positions, and the price of any market. You build a rule in two steps, the wallet and then the rule, from five kinds: nearing a range edge, left its range, funding changed sign, close to liquidation, and crossed a price. Each rule has an on/off switch, and what fired is listed in a history below and shown as a toast. Alerts check every 30 s on every page of the app, using live data only, and pause when data is unavailable. Rules and history stay in your browser, and browser notifications are optional. It never trades. A **price alert** names a market, a side (above or below) and a price, with the market's mark shown beside the price. On Trade, the bell beside the price, **Alert at a price**, opens the same form with the market and its live mark filled in. The alert fires once when the mark crosses the price on its side, and again only after the mark has gone back to the other side. On Trade the live mark is read every 2 s, so an open terminal sees a cross within seconds. With **Telegram** connected, the worker also checks the rules every 2 minutes while Elyra is closed. **Connect Telegram** has the watched wallet sign a request (EIP-712, no gas) that carries its rules and the page's language; the API answers a one-time link to the Elyra bot that works for 10 minutes, and pressing Start in the chat links the wallet. A rule sends one message when its condition begins and stays quiet for 30 minutes after it, and a chat gets at most 12 messages an hour. After you change rules, **Sync rules** signs the new set. **Disconnect**, or `/stop` in the chat, removes the link and the server's copy of the rules. A chat can follow up to 5 wallets. ## Tools The four tools share one arrangement: inputs on the left in numbered groups, results on the right as headline figures, a chart, a breakdown table, and a "Use this" row that hands the result to the page that can act on it. None of them signs anything. ### Planner Compares Hold, LP, Hedge and Perp on the same capital, using current market data. Ranges come from the ±5, 25 and 50 % presets or a custom band. "Share scenario" copies the URL, which carries every input. The "Use this" row opens the result: add this range, open the hedge, open the perp, or buy spot. The perp's capital is its margin, so its ticket opens at the capital times the leverage. "Guide me" walks through the chart step by step; it only opens when you press it. ### Ranges Compares a tight, a middle and a broad range (±5 %, ±25 % and ±50 % by default) for the same deposit. A calculator: no data, no writes. Each band opens in the Planner. Read [One-token deposits](https://elyratrade.io/docs/zap). ### Backtest Replays Hold, LP and Hedge over real hourly closes from the API's candles; there is no generated fallback. You set the fee APR and funding; the period defaults to the last 7 days and reaches back 90. "Plan this range" carries the band to the Planner, and "Download CSV" saves the series. ### Sizing Works out a position size from your risk budget and stop distance. Leverage changes only the margin estimate. It sends nothing itself: the result opens the perp ticket on Trade, on the side you chose. Read [Perpetuals](https://elyratrade.io/docs/perps). Where it lives: - `apps/web/components/chrome/nav.ts`: every page and how the nav groups them - `apps/web/lib/tx.ts`: the check, simulate, send and refresh path - `apps/web/lib/writeGate.ts`: when a write is allowed - `apps/web/lib/trade/approvals.ts`: exact approvals and Permit2 - `apps/web/lib/data.ts`: what a page shows when the API does not answer - `apps/web/lib/env.ts`: FIXTURES_ALLOWED and the Privy switch - `apps/web/lib/usePerp.ts`: signed perp actions and the Hyperliquid approvals - `apps/web/lib/tour/steps.ts`: the tour --- # What's new Source: https://elyratrade.io/docs/whats-new · Get started What the app does today on Elysium, in one dated entry. What the app does today. Each entry describes the product as it stands on the day it is dated. ## 29 November 2026 Elyra runs on Elysium, chain id 99901, with HYPE for gas, WHYPE as the wrapped native token and USDC as the stablecoin. Every contract and transaction opens on the [Elysium explorer](https://elysium.kinetiq.xyz/explorer). ### Trade - **Swaps** route through the Elyra Router across Elyra's DAMM, DLMM and stock pools and public Uniswap v4 pools, up to three hops in one transaction, with no Elyra fee. The trade terminal's spot ticket also quotes the Uniswap path through the Universal Router and takes whichever pays more. [Swaps and routing](https://elyratrade.io/docs/swaps) has the details. - **Perps on Hyperliquid.** The Perp ticket trades Hyperliquid markets from your own Hyperliquid account, with USDC as collateral. Your wallet approves a trade-only agent wallet and Elyra's builder fee once each; the agent wallet signs orders and cannot withdraw. Stock perps are HIP-3 markets on the `xyz` dex, such as `xyz:NVDA`, `xyz:TSLA` and `xyz:SP500`. [Perpetuals](https://elyratrade.io/docs/perps) explains the set-up and the bounds every order is checked against. - **Limit orders** rest as one-sided Uniswap v3 ranges or in a single DLMM bin, and earn swap fees while they wait. [Limit orders](https://elyratrade.io/docs/range-orders) has the details. - **The terminal** streams marks, Hyperliquid's order book and recent trades, keeps exits in place when you change them, and answers keyboard shortcuts. [Using the app](https://elyratrade.io/docs/app-guide#keyboard-shortcuts) lists every key. ### Earn and pools - **Stock pools and vaults** for EQX tokens bridged from HyperEVM: EQNVDA, EQTSLA, EQSPY, EQQQQ, EQAAPL, EQMETA and EQSPCX. Their prices on chain come from Elyra's own keeper-updated feed, and each pool trades inside a band around it. [Elyra pools](https://elyratrade.io/docs/pools) covers the band and the session fees. - **Hedged vaults** pair a liquidity position with a short on Hyperliquid, run by Elyra's hedger through a funder account for each vault. Margin leaves the vault as USDC under per-call and per-day caps. [Hedged vaults](https://elyratrade.io/docs/hedged-vaults) says who holds which key. - **One-token deposits, position automation and LP vaults** on the official Uniswap v3 and v4 deployments on Elysium. [One-token deposits](https://elyratrade.io/docs/zap), [Position automation](https://elyratrade.io/docs/keeper) and [Vaults](https://elyratrade.io/docs/vaults) have the details. ### Launch and protocol - **Launch pools** create a token and its locked HYPE pool in one transaction, with an anti-snipe fee and an optional pre-launch vault for pooled buying. Tokens that age and hold depth graduate into a managed vault. [Launch a token](https://elyratrade.io/docs/launch) and [Graduation and pre-market perps](https://elyratrade.io/docs/graduation) explain both. - **Fees, referrals and $ELYRA.** A referred user's fees credit 20 % to their referrer; the rest reaches the fee collector, becomes HYPE and buys $ELYRA, which is burned. The token is launched by its owner; until then the buyback holds what it receives. [Buyback and burn](https://elyratrade.io/docs/protocol) walks through each step. - **Agents** connect with their own wallet through `/llms.txt`, the deployment files and the ABIs on this site. [Agents and integrations](https://elyratrade.io/docs/agents) is the integrator's chapter. --- # The Lounge Source: https://elyratrade.io/docs/lounge · Get started The community view: the points leaderboard, live activity, the week's top ideas, profiles and signed follows. The Lounge (`/lounge`) is Elyra's community view: who is active, what they just did, and how the points stand. It has no chat. Everything it shows is on chain, signed by a wallet, or read from the points ledger, and every address in it links to that address's profile. In brief: - The points leaderboard ranks every address with points, from the same ledger and rule as `GET /points/:address`. - The live activity feed lists new ideas, vault deposits and withdrawals, new Elyra pools, graduations and filled limit orders, newest first. It refreshes every 15 seconds while the tab is open. - Top ideas this week are the ideas posted in the last 7 days with the best result so far. - Following someone is a message your wallet signs (EIP-712, no gas). The API keeps it, so your follows are the same on every device, and the feed can show only the people you follow. Follows are public. - Points are an off-chain ledger. Nothing is promised about them. ## Points leaderboard `GET /points/leaderboard` ranks every address with more than zero points. It computes the totals the way `GET /points/:address` does: 1 point per dollar of volume and 5 per dollar of fees earned, and volume counts double for 7 days after you post an idea. The rule and what earns points are in [Fees and referrals](https://elyratrade.io/docs/fees#points). Addresses on equal points share a rank and the next rank skips past them (1, 2, 2, 4). Ties are listed in address order. The ranking is rebuilt from the whole ledger at most once a minute, so a new point can take up to a minute to move a rank. The page shows the top ten and can open the top fifty. With a wallet connected, your own row is marked and tagged "You". When you rank below the rows shown, your rank and points are written under the table. Each row links to that address's profile and has a Follow button. Parameters: GET /points/leaderboard - `limit` (allowed: 0 to 200; default: 50): rows returned; 0 returns only your own row - `address` (allowed: 0x address; default: none): adds that address as `you`, wherever it ranks The answer carries `rows`, `you` (null without points), `ranked` (how many addresses have points) and `asOf` (unix seconds of the ranking). ## Live activity `GET /lounge/feed` merges the newest rows of what the API and the indexer already store, without any indexer change: | Line | Where it comes from | | --- | --- | | Idea | the API's `theses` table: the market, the side and the first 200 characters | | Deposit, withdrawal | indexer `vaultEvent` rows of kind `deposit` or `withdraw`, named after their vault | | Pool launch | indexer `ammPool` rows of kind `damm`: a token launched from Launch, or an Elyra pool opened for an existing token | | Graduation | indexer `graduation` rows once the token has a managed vault | | Limit order filled | indexer `rangeOrder` rows with status `filled`, with the amount the order sold | The API reads the newest 40 of each source and keeps the newest 120 lines in all. One build answers every request for 10 seconds. Amounts are priced as the points ledger prices them (USDC at $1, HYPE and WHYPE at the HYPE mark, EQX stock tokens at their market); a token nothing prices shows its amount without a dollar value. Elyra's own contracts are never named as the one who acted: a vault depositing into its sleeve is left out, and a pool created through the launch contract shows no creator. The page asks again every 15 seconds and stops while the tab is hidden; it asks once more when you come back. New lines fade in once. If one source does not answer, the others are still listed and the page says some on-chain activity is still loading. **Everyone / Following.** Following sends `follower=`, and the API keeps only the lines whose actor you follow. The kind pills (Ideas, Vaults, Launches, Limit orders) narrow the list on the page. Parameters: GET /lounge/feed - `limit` (allowed: 1 to 120; default: 40): lines returned, newest first - `follower` (allowed: 0x address; default: none): only lines from the addresses it follows ## Top ideas this week The ideas posted in the last 7 days (`GET /theses`), best result so far first; ideas without a result yet follow, newest first. Each shows its author's place on the Ideas track records (`GET /theses/leaderboard`) and opens the idea's own page. ## Profiles `/lounge/u/
` shows one address: its ideas with their results, its track record (rank, ideas, fees realised and PnL from the Ideas leaderboard), its points, rank and where they came from, how many addresses follow it and how many it follows, how many addresses it has referred (`referredCount` from `GET /referral/:address`, read from `ReferralRegistry` events), and its recent lines in the feed. Authors on the Ideas board and rows of the leaderboard link here. Profiles are rendered on request and kept out of search engines. ## Follows A follow is a public edge from one address to another, kept in the API's Postgres (`follows`: follower, followee, created at; migration `0002`). Every change is one `POST /follows` carrying a signature from the follower's wallet over ```text FollowUpdate { address account; address[] follow; address[] unfollow; string nonce; uint256 ts } ``` under the domain the ideas and perp orders use (`{ name: 'Elyra', version: '1', chainId }`). The addresses are in the message itself, so your wallet shows exactly whom you follow. `@elyra/core`'s `buildFollowTypedData` builds it on both sides. It costs no gas and moves no funds. Parameters: POST /follows - `follow + unfollow` (allowed: 1 to 100 addresses): per update; one address cannot be in both - `following` (allowed: up to 500 addresses): per address, after the update - `ts` (allowed: ±300 s): from the API clock, like the perp envelope - `nonce` (allowed: 16 to 64 bytes): random, used once per address | Code | Status | When | | --- | --- | --- | | `invalid_address` | 400 | the body has no 0x `address` | | `invalid_follow_list` | 400 | a list is not addresses, or one address is in both | | `empty_follow_update` | 400 | nothing to follow or unfollow | | `too_many_addresses` | 400 | more than 100 addresses in one update | | `self_follow` | 400 | an address follows itself | | `too_many_follows` | 400 | the update would pass 500 follows | | `unauthorized` | 401 | no envelope, or the signature is not from `address` | | `stale_ts` | 401 | `ts` more than 300 s from the API clock | | `nonce_used` | 409 | the nonce was already used by this address | Follows kept in this browser before you connected a wallet still show, and the first signature you give sends them with it; after that the browser copy is cleared. "Keep them with your wallet" sends them on their own. Signed out, Follow opens the wallet connection. Where it lives: - `apps/api/src/lounge/leaderboard.ts`: rankPoints and the one-minute ranking - `apps/api/src/lounge/feed.ts`: the feed sources, labels, prices and the 10-second build - `apps/api/src/routes/follows.ts`: GET and POST /follows: the checks in order - `packages/core/src/follows.ts`: the FollowUpdate message both sides build - `apps/web/lib/lounge/useFollowing.ts`: signing a follow and moving the browser list - `apps/web/app/[lang]/(app)/lounge/ActivityFeed.tsx`: the 15-second poll and the Following switch --- # Swaps and routing Source: https://elyratrade.io/docs/swaps · Trade How one swap is split into hops across Elyra pools and public v4 pools, and how a route is chosen. The Swap page trades any token for any other through the Elyra `Router`, a contract that chains up to three swaps across Elyra pools and public Uniswap v4 pools on Elysium in one transaction. This chapter covers what the Router does on chain, how the app finds and ranks routes, and the checks that run before you sign. The pools themselves are described in [Elyra pools](https://elyratrade.io/docs/pools). In brief: - A swap is one `Router.swapExactIn` call with an exact input. It allows up to 3 swap hops, charges no fee of its own and reverts with `TooLittleReceived` unless the final output reaches your minimum. - The app quotes every candidate route live with `Router.quoteExactIn` and ranks them by output; a route through an Elyra DLMM pair leads while it pays within 15 % of the best. - Price impact from 1 % is flagged, from 5 % you must tick a box to accept it, and from 15 % the swap is refused. - An ERC-20 input needs one exact-amount approval to the Router and no Permit2 signature. HYPE goes in as the transaction value. ## A route is a list of hops You hand the Router the hops, the input amount, your minimum output, a recipient and a deadline. Each hop names a venue kind and carries that venue's own data: | Kind | Venue | `data` | Direction flag | | --- | --- | --- | --- | | `0` | any Uniswap v4 pool | `abi.encode(PoolKey, zeroForOne, hookData)` | `zeroForOne`: currency0 goes in | | `1` | an Elyra DLMM pair | `abi.encode(pair, swapForY)` | `swapForY`: token X goes in | | `3` | WHYPE | empty | wraps HYPE or unwraps WHYPE; not a swap hop | Diagram: One Router swap, from call to payout. swapExactIn checks the call, takes the input, runs each hop in order and pays out only if the final amount clears minAmountOut. A wrap hop does not count toward the three-swap limit, and nothing stays in the Router afterwards. The Router checks the shape first. `routeTokens` requires each hop to start in the token the previous one ended in, treats HYPE and WHYPE as the same asset, and allows at most `MAX_SWAP_HOPS` (3) hops that are not wrap hops. Then it takes your input: either HYPE sent as value, which must equal `amountIn` and must suit the first hop, or an ERC-20 pulled with `transferFrom`. Between hops it wraps or unwraps as the next venue needs. To receive HYPE when the last pool pays WHYPE, the route ends with a wrap hop. Each v4 hop must consume its whole input or the call reverts `PartialFill`; hops carry no price limit of their own. The only price protection in a swap is therefore your final minimum, checked once at the end. On success the Router sends the output to the recipient and emits `Swapped`, with the zero address standing for HYPE. Warning: The Router trusts the hops it is given It will swap through any v4 pool key, hooked or not, and any contract that answers like a DLMM pair. The app only builds hops from Elyra's own pools and hookless public pools. If you call the Router from your own code, vet the venues yourself. ## Quoting a route `quoteExactIn(hops, amountIn)` runs the same hops without moving tokens. It is not a view function, so the app calls it with an `eth_call`. A v4 hop runs the real swap inside a `PoolManager` unlock and reverts with `QuoteResult(amountOut)`; a DLMM hop asks the pair's `getSwapOut` and reverts `InsufficientLiquidity` if the bins cannot absorb the whole input. A quote reads the chain at that moment. Anything that moves the price before your transaction lands is covered by your minimum, nothing else. ## How the app picks a route The Swap page and the trade terminal share one search (`packages/agent/src/route/route.ts`, which the web's `lib/amm/route.ts` re-exports, and `useSwapRoutes`): 1. Gather the pools: Elyra's DAMM, DLMM and stock pools from the API, the v4 ones with their exact key from the deployment manifest. With a Router deployed, also public hookless v4 pools at the 0.01 %, 0.05 %, 0.3 % and 1 % tiers that hold in-range liquidity. Hookless only, because a hook can run arbitrary code during a swap. 2. Build candidates: Every pool holding both tokens, and every two-hop route through USDC or HYPE, up to 40. The app does not build three-hop routes. It drops a route whose first pool wants native HYPE when you pay WHYPE, because the Router cannot unwrap your input, and adds a final wrap hop where your output needs it. For the same reason WHYPE to HYPE on its own never goes through the Router: the page unwraps it with WHYPE's own `withdraw`, 1:1 and with no approval. HYPE to WHYPE is a one-hop Router route. 3. Quote and rank: Each candidate is quoted every 15 s. A failed or zero quote drops the route; the rest are ranked by output. The best route through an Elyra DLMM pair moves to the top unless it pays 15 % or more below the leader (`DLMM_FALLBACK`), since that far down the bins the price impact gate would refuse it anyway. 4. Measure the impact: Price impact is the leading route's rate against a quote for 1/1000 of the amount on the same hops, so the pool fees cancel out. With no Router in the manifest the page estimates each route from the pools' own prices net of their fees, labels the result as an estimate and will not send it. ## Before you sign The minimum you sign is the leading quote less your slippage: `minAmountOut = out × (1 − slippage)`. The page shows the rate, the price impact, the pools' compound fee, that minimum and how many routes returned a quote, with up to four other routes and how far each trails the best. Two gates can hold the button: - **Slippage.** Presets of 0.1 %, 0.5 %, 1 % and 3 %, 0.5 % by default, or any custom value up to 50 %. Above 5 % you must acknowledge the risk first. - **Price impact.** Flagged from 1 %. From 5 % you tick a box accepting the impact; from 15 % the swap is refused and you are asked to split the trade. An impact the page cannot measure does not gate. The transaction carries a 20-minute deadline. For an ERC-20 the steps are an exact-amount approval to the Router, then the swap; the Permit2 step is shown as done because the Router never uses it. The page URL follows the form (`?in=`, `?out=`, `?amt=`), so a swap can be shared as a link. ## Reading prices A v4 pool's own price is token1 per token0, in address order and in raw units, and a DLMM pair's is Y per X. USDC has 6 decimals and EQX stock tokens have 8, so a stock pool's raw price is far from the dollar price you read. Every page turns a pool round to read base in quote: the quote is USDC when the pool has it, otherwise HYPE or WHYPE, otherwise token1, and a stock pool's asset is always the base. The hop flags above follow the raw order, never the displayed one. ## Buy and Sell in the trade terminal The terminal's spot Buy and Sell normally trade the asset's Uniswap pool through the Universal Router: approve, Permit2, swap, with a 10-minute deadline. Its quote is an estimate at the pool's on-chain price less the pool fee and Elyra's 25 bps fee on the output. The same route search runs beside it. When a live Router quote pays more than that estimate, the trade goes through the Elyra Router instead: one exact approval, no Permit2, no 25 bps Elyra fee (the pools' own fees still apply), and the route is drawn above the button. The Uniswap estimate ignores price impact, so the Router takes over only when it beats a generous number. The terminal applies the slippage acknowledgement and checks the pool's on-chain price against the API, and the same impact gates as Swap. ## Reference Parameters: Thresholds the app applies - `Slippage` (allowed: 0 - 50 %; default: 0.5 %): Becomes minAmountOut. Above 5 % needs an acknowledgement. - `IMPACT_WARN` (allowed: fixed; default: 1 %): Impact shown as a warning. - `IMPACT_CONFIRM` (allowed: fixed; default: 5 %): You must accept the impact to swap. - `IMPACT_BLOCK` (allowed: fixed; default: 15 %): The swap is refused. - `DLMM_FALLBACK` (allowed: fixed; default: 15 %): How far below the best a DLMM route may pay and still lead. - `Deadline` (allowed: fixed; default: 20 min (Swap), 10 min (terminal)): Passed to swapExactIn; Expired after it. | Router error | When | | --- | --- | | `Expired`, `ZeroRecipient`, `ZeroAmount` | past the deadline, no recipient, or a zero input | | `BadRoute`, `BadKind` | an empty route, more than 3 swap hops, hops that do not chain, or an unknown kind | | `ValueMismatch` | HYPE sent that differs from `amountIn` or does not suit the first hop, or no HYPE for a route that starts in HYPE | | `PartialFill` | a v4 hop that could not take its whole input | | `InsufficientLiquidity` | a DLMM hop in a quote that the bins cannot fill | | `TooLittleReceived` | the final output is below `minAmountOut` | Where it lives: - `contracts/src/venue/periphery/Router.sol`: swapExactIn, quoteExactIn, routeTokens, the HYPE and WHYPE bridge - `contracts/src/venue/interfaces/IRouter.sol`: hop kinds, their data, errors and the Swapped event - `packages/agent/src/route/route.ts`: hop encoding, candidates, dlmmFirst, estimates, price impact - `packages/agent/src/route/venues.ts`: where legs come from: Elyra pools and public v4 pools - `apps/web/lib/amm/useSwapRoutes.ts`: the live quote loop behind every page - `apps/web/lib/amm/orient.ts`: base and quote for display - `apps/web/app/[lang]/(app)/swap/SwapClient.tsx`: slippage, the impact gates, the approval and the swap - `apps/web/lib/amm/useElyraSpot.ts`: when the terminal hands a trade to the Router --- # Limit orders Source: https://elyratrade.io/docs/range-orders · Trade A one-sided position that sells as the price crosses it and earns swap fees while it waits. An Elyra limit order sells one token for another once the price reaches a level you choose, and earns swap fees while it waits. Under the hood it is a narrow Uniswap v3 position placed just beyond the current price, holding only the token you want to sell; as the price moves through it, the pool converts it into the other token. You place one from the Limit mode of the ticket on the Trade page, and the `RangeOrders` contract holds it until it is filled or you cancel. Elyra DLMM pairs have a second kind of limit order that rests in a single price bin and fills at exactly that bin's price. Those are described in [Elyra pools](https://elyratrade.io/docs/pools); this chapter covers the Uniswap kind. In brief: - A sell order sits above the price, a buy order below it. The app makes the band one tick spacing wide. - An order can be closed only after the price has crossed the whole band. Until then you may cancel at any time and take back whatever the position holds. - Whoever closes a crossed order keeps 1 % of the converted amount. The protocol takes 10 % of the swap fees the order earned, never of the principal. Placing and cancelling are otherwise free. - The contract never closes an order by itself; someone has to call `fill`. If the price crosses and comes back first, the order converts back. - Payouts are always ERC-20: you receive WHYPE, not HYPE. Orders do not expire and cannot be edited or transferred. ## Setting the price You choose a side, a limit price and an amount, and the app (`limitBand` in `lib/trade/limit.ts`) builds the band: - **Sell** the asset above the market: the asset itself goes into the band. - **Buy** the asset below the market: the other token goes into the band. The near edge of the band is the usable tick closest to your price, moved one spacing outward if rounding left it touching the current price. A sell price at or below the market, or a buy price at or above it, is refused before anything is sent. The band is built from the pool's own `slot0`, and the button stays locked while that price and the API's differ by more than 100 bps. Only v3 pools are supported. The order converts as the price walks across the band, so your average price lies between its two edges: about 0.1 % apart on a 0.05 % pool, 0.6 % on a 0.30 % pool and 2 % on a 1 % pool. The panel shows the near edge as "Fills at" and an estimate of the fees the order would earn per day if the price sat inside it. ## What the contract checks `place` re-checks everything against the pool at the moment the transaction lands. 1. Inputs: A passed `deadline` is `Deadline` and a zero `amountIn` is `ZeroAmount`. `token0` must sort below `token1` and `tickLower` must be below `tickUpper`, or `BadRange`. The pool comes from `factory.getPool(token0, token1, fee)`; none is `NoPool`. 2. Side of the price: Selling token0 (`zeroForOne`) needs `tickLower > tick`. Selling token1 needs `tickUpper ≤ tick`. A band that touches the current price would need both tokens and is `BadRange`. 3. Funding: With HYPE attached, the sold token must be WHYPE and `msg.value` must equal `amountIn` (`ZeroAmount` otherwise); the HYPE is wrapped. Without HYPE, the token is pulled with `transferFrom`, which needs an exact-amount approval first. The Limit mode pays in HYPE automatically when you sell WHYPE. 4. Position: The contract mints the position to itself with the full amount on the sold side and zero on the other. Minimums are zero because the unused side is zero by construction. Whatever the mint could not use is returned to you at once, as an ERC-20: the contract never pays out native HYPE, because a fill pays the owner rather than the caller. 5. Record: The order is stored under the next id (ids start at 1) with you as `owner` and status `Open`, and `Placed` is emitted. Diagram: A limit order, placed to closed. A sell-token0 order must sit strictly above the price, a sell-token1 order at or below it. An open order ends by fill, open to anyone once the price has crossed the whole band, or by cancel, the owner's at any time. Neither can be undone. The position NFT stays with the contract, so a fill needs no approval from you. Your claim on it is the `owner` field of the order, which cannot be changed. ## When an order is done A Uniswap position covers ticks from `tickLower` up to, but not including, `tickUpper`. That sets both the placing rule and the closing rule. A **sell-token0** order sits above the price. It must start strictly above the current tick, because at `tickLower` itself the position would already hold some token1. It is fully converted once the tick reaches `tickUpper`: `fillable` is true when `tick ≥ tickUpper`. A **sell-token1** order sits below the price. It may end exactly at the current tick, because a position whose upper tick equals the current tick is already all token1. It is fully converted only once the tick drops strictly below `tickLower`: `fillable` is true when `tick < tickLower`, since at `tickLower` the position is live again. A partly crossed band holds both tokens and is not fillable. Orders have no clock: one the price never reaches stays open, earning fees, until you cancel it. ## Closing an order **Fill** is open to anyone once `fillable` is true. The contract marks the order `Filled`, then: 1. Removes the position's live liquidity, collects and burns the NFT. It reads the liquidity from the position manager rather than the figure stored at placing, because anyone can add liquidity to a position the contract holds. Without that, a few wei of donated liquidity would stop the burn and lock your order; with it, the donation goes to you. 2. Splits what came back into principal and fees: the decrease returns principal only, so the fee portion is what `collect` paid on top. 3. Sends 10 % of the fee portion of each token (`PROTOCOL_FEE_BPS` = 1000) to the `FeeRouter`, booked to you so that your referrer earns 20 % of it. 4. Pays the caller 1 % (`KEEPER_BOUNTY_BPS` = 100) of the converted principal, taken from your share of the bought token. 5. Sends everything else to you and emits `Filled`. **Cancel** is yours alone (`NotOwner` for anyone else) and works whenever the order is `Open`, inside the band or outside it. It runs the same unwind and the same 10 % share of earned fees, pays no bounty, and returns the position as it stands: all principal if the price never touched the band, a mix if it is part-way through, all the other token if it has crossed. Once an order is `Filled` or `Cancelled` it cannot reopen; a second close is `NotOpen`. ## Who closes orders In practice Elyra's keeper bot does. Every minute by default, it reads `fillable` for every open order in one Multicall3 batch. For each crossed order it values the bounty at 1 % of the order's size in USD, converts that to wei at the HYPE price, and sends `fill` only when the bounty is at least three times the estimated gas (`GAS_BOUNTY_MULTIPLE`). If the order cannot be priced, it skips rather than sending blind. After a success it leaves the order alone for 5 minutes; after a skip or a failure, for 15. A small order may therefore wait until its bounty covers the gas, or for you or anyone else to call `fill`. A filler may also push the price through the band and then close the order. That is allowed by design: it is the same trade any arbitrageur could make against the position, it pays the position fees on the way, and it can only happen at or beyond your price. The filler still cannot act before the cross, take part of an order, or redirect the proceeds: they always go to the owner. Warning: A crossed order is not yet a filled one Until `fill` runs, your order is ordinary liquidity. If the price crosses the band and then returns through it, the pool converts the order back into the token you were selling, and it is no longer fillable. It keeps earning fees and waits for the next cross. If the bot has not closed a crossed order, close it yourself: call `fill` and the 1 % bounty comes back to you, or `cancel`, which after a full cross returns the bought token with no bounty at all. ## Reference ### Call parameters Parameters: PlaceParams (RangeOrders.place) - `token0` (allowed: the lower-sorted pool token): Not reordered for you; the wrong order is BadRange. - `token1` (allowed: the higher-sorted pool token): With token0 and fee, finds the pool. - `fee` (allowed: 100 · 500 · 3000 · 10000 hundredths of a bip): The pool fee tier. - `zeroForOne` (allowed: true · false): true sells token0 into a band above the price; false sells token1 into a band at or below it. - `tickLower` (allowed: above the current tick when selling token0 ticks): Lower edge of the band; one spacing below tickUpper in the app. - `tickUpper` (allowed: at or below the current tick when selling token1 ticks): Upper edge of the band. - `amountIn` (allowed: above 0 wei of the sold token): The principal. Equals msg.value when paying in HYPE. - `deadline` (allowed: unix seconds; default: now + 600): Latest block time; also passed to the position manager. `orders(orderId)` returns the stored order, including `owner`, `tokenId` (the NFT the contract holds), `pool`, the ticks, `amountIn` (the principal the position actually took) and `status`. `nextOrderId()` is the id the next order will get. ### Reverts | Revert | Cause | | --- | --- | | `Deadline` | `place` after `deadline`. | | `ZeroAmount` | `amountIn` is zero, HYPE was sent for a token that is not WHYPE, or `msg.value` differs from `amountIn`. | | `BadRange` | Tokens out of order, `tickLower` not below `tickUpper`, or the band on the wrong side of the current tick. | | `NoPool` | No pool for the pair and fee. | | `NotFillable` | `fill` before the price has crossed the whole band. | | `NotOwner` | `cancel` by anyone but the order's owner. | | `NotOpen` | `fill` or `cancel` on an order already closed. | ### Emitted events | Event | Emitted by | Carries | | --- | --- | --- | | `Placed` | `place` | `orderId`, `owner`, `tokenId`, `zeroForOne`, the two ticks, `amountIn` after the leftover was returned | | `Filled` | `fill` | `orderId`, `keeper` (the caller), `amountOut` (converted principal before the bounty), `feesEarned` (bought token only), `bounty` | | `Cancelled` | `cancel` | `orderId`, `amount0` and `amount1` paid to the owner | `feesEarned` counts only the bought token: the swaps that cross an order pay their fee in the token the order is buying, so the other side is dust. The 10 % protocol share still applies to both. The indexer turns these events into the `rangeOrder` table behind the Trade page's "Resting limit orders in this market" and Portfolio's "Uniswap range orders", and behind the bot's list of open orders. Where it lives: - `contracts/src/RangeOrders.sol`: place, fillable, fill, cancel, the unwind and the fee split - `contracts/test/RangeOrders.t.sol`: both sides, the cross, the split, native HYPE and the donated-liquidity case - `apps/web/lib/trade/limit.ts`: limitBand and earnsPerDayUsd - `apps/web/app/[lang]/(terminal)/trade/[asset]/LimitPanel.tsx`: the Limit mode: HYPE or approval, and the price check before placing - `apps/api/src/bots/keeper.ts`: sweepRangeOrders: fillable in one batch and the bounty in wei - `apps/api/src/bots/chain.ts`: GAS_BOUNTY_MULTIPLE and the skip rule --- # Perpetuals Source: https://elyratrade.io/docs/perps · Trade Perps on Hyperliquid through an agent wallet you approve once, which can place orders and has no way to withdraw, and Elyra's builder fee. The perps on the Trade page, and the shorts behind the [hedged vaults](https://elyratrade.io/docs/hedged-vaults), trade on Hyperliquid. Elyra is a client of that venue, not a venue itself. To give you one-click orders without a wallet popup for each one, an Elyra service called the signer holds a trade-only agent wallet for your Hyperliquid account. This chapter covers what that agent wallet can and cannot do, how an order is checked before it is signed, how Elyra's builder fee works, and what runs when no Hyperliquid account is connected. In brief: - Your Hyperliquid account belongs to your wallet's address. The agent wallet your wallet approves can place, modify and cancel orders and set leverage. Hyperliquid does not let an agent wallet withdraw or transfer funds, and withdrawals always need your wallet. - Elyra's fee on perps is a Hyperliquid builder fee. Your wallet approves a maximum once; each order names Elyra as builder at a rate no higher than that, and Hyperliquid collects it with the trade fee. - Collateral is USDC in your own Hyperliquid account. Funding it from Elysium means bridging USDC out to HyperEVM first, which takes about 24 hours. - The signer measures every order against Hyperliquid's current mark: the signed price must sit within 1,000 bps (10 %) of it, one order is capped at $250,000 of notional, and nothing is signed when there is no mark. - Every write to `/perp/*` carries an EIP-712 signature from your wallet over the exact request, a one-time nonce and a timestamp within 300 s. An opt-in trading session lets a key held by one browser tab sign orders and cancels instead, for at most 24 h; it can never withdraw. ## Who holds which key Hyperliquid accounts are addresses. An account can approve agent wallets, separate keys that sign orders for it and cannot move funds out. In Elyra the browser holds only your wallet, plus a key for orders and cancels while a [trading session](#trading-sessions) is on. The API checks that each write was signed by the wallet that owns the address, then forwards it; it holds no key. The signer (`services/signer`) generates and stores your agent wallet encrypted, signs within fixed bounds, and accepts calls only from the API, which signs each one with a shared secret over a timestamp and a one-time nonce, so a captured call cannot be replayed. Hyperliquid executes. Diagram: Who holds which key. The signer holds your agent wallet, and the top group is what it does on its own. Every step in the lower group needs a signature only your wallet can make; dashed arrows hand typed data back to the browser. With VENUE=sim no order leaves the API. The agent wallet can place market and limit orders with exits attached, modify and cancel orders, set a market's leverage and read your account. Approving a new agent wallet needs your wallet's signature. So does every withdrawal or transfer: Elyra has no route that asks the signer for one. ## Connect your Hyperliquid account 1. Hold USDC on Hyperliquid: Your collateral is USDC in your own Hyperliquid account, at the same address as your wallet. If you hold USDC on Elysium, bridge it to HyperEVM through the [Elysium bridge](https://elysium.kinetiq.xyz/bridge) (withdrawals from Elysium take about 24 hours), then move it into your Hyperliquid account. The USDC never passes through Elyra. The Perp ticket reads your account (`GET /perp/account/:address`) and moves on once Hyperliquid shows a balance. 2. Approve the agent wallet: The Approve agent button signs a `POST /perp/onboard`. The signer generates one agent wallet per address (asking again returns the same one), stores it encrypted and returns its address. Your wallet then signs Hyperliquid's agent approval for that address, and the API forwards it to Hyperliquid. 3. Approve the builder fee: Your wallet signs Hyperliquid's builder fee approval once: Elyra's builder address and the most it may charge per trade. Hyperliquid refuses any order that names a higher fee, and you can lower the maximum or revoke it from your wallet at any time. 4. Trade: The account read reports the agent and the builder fee as approved, and the set-up box disappears. A smart-contract wallet is refused before any approval, because Hyperliquid's approvals need a signature from the account's own key. On the simulated venue the first step completes set-up and no deposit is asked for. ## Elyra's builder fee A Hyperliquid builder fee is a charge an app adds to the orders it sends, on top of Hyperliquid's own trading fee. It is paid in USDC from the trade, only on orders that name the builder, and only up to the maximum your wallet approved. Hyperliquid caps builder fees on perps at 0.1 % of notional. The ticket shows Elyra's rate before you approve it and beside every order. Builder fees accrue to Elyra's builder account on Hyperliquid. An owner-run sweep brings them to Elysium and books them through the `FeeRouter` in each trader's name, so a referrer earns 20 % of what their referred traders paid, and the rest goes to the [buyback](https://elyratrade.io/docs/protocol). Orders the hedger sends for the hedged vaults carry no builder fee. ## How an order is checked The signer takes one write at a time per address, and signs an order only if every check passes: 1. The address has an agent wallet (404) and Hyperliquid reports it approved (409). 2. The request is well formed: side, type, a finite size above zero, leverage of at least 1 (422). 3. Hyperliquid has a current mark for the market. Without one the answer is 503 and nothing is signed: a bound is only as good as the price it is measured from. 4. The price to sign: a limit order uses your price. A market order uses `mark × (1 ± s)`, sent immediate-or-cancel, where `s` is the requested slippage but never under 100 bps. A request over 1,000 bps is refused (422), not clamped. 5. That price is within 1,000 bps of the mark, whichever order type produced it (422). 6. The size, rounded down to the market's size precision, meets the market's minimum unless the order is reduce-only, and size times mark is at most $250,000 (422). The signer then sets leverage if you sent it, submits, and reads your account back. It reports success only when a market order has moved your position, or a limit order has moved it or rests on the book. An order Hyperliquid rejected returns its reason. One whose outcome cannot be read yet returns as unconfirmed: refresh orders and positions before sending it again. The Perp form sends no slippage value, so every market order from it is priced at the mark plus or minus 1 %, as the form says beside the button. The liquidation price the form shows is Elyra's estimate from the market's margin rules, counting that order alone, without fees or funding. It is not Hyperliquid's own figure. ### Stock perps Stock and index perps are HIP-3 markets on Hyperliquid's `xyz` dex: `xyz:NVDA`, `xyz:TSLA`, `xyz:AAPL`, `xyz:META` and others, each named with its dex prefix. There is no SPY perp; the S&P 500 market is `xyz:SP500`, and that is the market Elyra uses to hedge EQSPY. Margin, leverage limits and liquidation on these markets follow Hyperliquid's rules for HIP-3 markets, and the ticket shows the limits of the market you picked. The hedger uses the same signing path for the hedged vaults' shorts: market orders for the vault's hedge account, which is its funder's address, reduce-only when it buys back. The funder approves the signer's agent wallet for that account once, with the same onboard and approval steps the web makes. Warning: What the bounds do and do not limit A key that can trade can move value without a withdrawal: a resting sell at a tiny price, crossed from another account, hands the position to the buyer. That is why the band and the notional cap apply to the signed price of every order type, and why the signer will not start with a market-order ceiling below the 100 bps floor or wider than the band. The band limits each order, not how many are sent, so the signer's host and secrets still matter. See [Security model](https://elyratrade.io/docs/security). ## Exit orders Attach exits when you open a position in the Perp form, or add them later with **SL / TP** on a position in the terminal or in Portfolio. For a long the stop sits below the reference price and the take-profit above it; for a short, the other way round. The reference is your limit price for a limit entry and the mark otherwise. The form shows estimated gross PnL at each level, before fees, funding and slippage, and draws the levels on the chart. The exits are Hyperliquid's own trigger orders, triggered by the mark price, and they rest on Hyperliquid with your browser closed: - **With a new entry** they are grouped with it: they take effect when the entry fills, and one cancels the other. A reduce-only entry cannot carry exits. - **On an existing position** an exit is reduce-only, on the closing side, and its size is capped at the position. Without `replaceExits` the signer refuses new levels (409) while exits already rest in that market. - **Changing levels** never leaves the position without its exits. A new price for a resting stop or target modifies that order in place (`POST /perp/modify`). Adding or dropping a level places the new exits first and then cancels the old ones; if that cleanup fails, both sets rest (every exit is reduce-only) and the answer says so. A resting limit order's price and size, and an exit's trigger and size, can also be edited from the Orders tab. The signer checks the change like a new order: a limit price inside the band around the mark, a trigger on the side of the mark where it does not fire at once, the market's precision and minimum, and the notional cap. A trigger does not promise a fill at its price: a gap or a thin book can leave part of the position open, so check it after one fires. When a reduce-only market order closes a position flat, the signer also cancels the remaining exits in that market, and says so plainly if it could not confirm the cleanup. Your fills and funding come from Hyperliquid's public account data, newest first, a page at a time. `GET /perp/fills/:address` lists your fills (side, maker or taker, and the PnL a reducing fill realised); `GET /perp/funding/:address` lists the hourly funding settled on each position. At a positive rate longs pay shorts. ## Signed requests A request's `address` names an account, and a plain HTTP request proves nothing about who owns it. So every `POST /perp/onboard`, `/order`, `/modify` and `/cancel` carries an `auth` envelope: a `nonce` (`0x` plus 16 to 64 random bytes), a `ts` in unix seconds, and an EIP-712 `signature` by `address` over `PerpAction { string action; address account; bytes32 payloadHash; string nonce; uint256 ts }` under the domain `{ name: 'Elyra', version: '1', chainId }`. The route fixes `action`. `payloadHash` is the keccak256 of the body without `auth`, as canonical JSON (keys sorted at every level, no whitespace), so your wallet signs the exact request and a signature cannot be moved to another body. The API and the web build this message from the same file, `packages/core/src/perpAuth.ts`. `requirePerpAuth` checks, in order: a valid body and `address` (400), a well-formed envelope (401 `unauthorized`), `ts` within 300 s of the server clock (401 `stale_ts`), a signature that recovers to `address` over this body (401 `unauthorized`), and a nonce this address has not used (409 `nonce_used`). The nonce is spent only after the signature verifies, so a forged request cannot burn the owner's next nonce. It is remembered for 300 s plus 60 s of slack, after which the timestamp check already fails. Reads carry no envelope. ## Trading sessions Signing every order in your wallet is the default. To trade without a prompt for each one, turn on **Trade without confirming each order** in the Perp form and pick a length: 1 hour, 8 hours (the default) or 24 hours. The browser generates a new key for this tab, and your wallet signs one EIP-712 message under the same domain: `PerpSession { address account; address sessionKey; string[] actions; uint256 expiresAt; uint256 chainId }` `sessionKey` is the tab key's address, `actions` is `order` and `cancel`, and `expiresAt` is when the session ends. From then on the tab key signs each order and cancel over the same `PerpAction` as above, and the request carries the grant as `auth.session`; the nonce and the 300 s window apply as before. The key stays in the tab's memory and its `sessionStorage`, never in `localStorage`, and is never sent anywhere: a reload keeps the session and closing the tab ends it. `requirePerpAuth` honours a grant on `/perp/order` and `/perp/cancel` only (403 `session_scope` on any other route), and only if it is well formed, its actions are `order` or `cancel` and include this route (403 `session_scope`), it has not ended (401 `session_expired`), it ends no more than 24 h, plus the 300 s window, after the server clock (401 `session_invalid`), your wallet's signature on it recovers to `address` on this chain (401 `session_invalid`), the request's signature recovers to `sessionKey` (401 `unauthorized`), and the session has not been ended (401 `session_ended`). Set-up and the Hyperliquid approvals always need your wallet. While a session is on, the form shows **Session active · ends HH:MM** with **End session**. Ending it discards the key in this tab and revokes the grant at the API: the key signs one last `POST /perp/session/end`, and the API refuses that key from then until the grant would have expired, so a copy of it (a duplicated tab) stops working too. Disconnecting the wallet, or connecting another one, ends the session the same way. Warning: What a session allows Until it ends, anyone with access to this tab can place and cancel perp orders for your wallet without a prompt, inside the signer's price band and notional cap. A session can never withdraw or approve anything. Closing the tab discards the key without revoking the grant, which then lapses at its expiry: on a shared computer, end the session before you leave, or keep it short. ## Keyboard shortcuts On the Perp ticket, `B` and `S` pick Long or Short, `M` and `L` a market or a limit order, `Q` `W` `E` `R` size the order from 25, 50 or 75 % or all of your free margin, and `+` and `-` step the leverage by 0.5x, within 1x and the market's maximum. `A` puts the cursor in the size and `O` moves the focus to the order button. No key places or cancels an order: the order goes when you press Enter on the button or click it, and with a trading session on, that is still the one step that sends it. Press `?` in the terminal for every key, and read [the app guide](https://elyratrade.io/docs/app-guide#keyboard-shortcuts). ## Order notifications While Elyra is open with your wallet connected, it tells you when something happens to your orders: a resting limit order fills in full or in part, a stop loss or take profit triggers, a position closes with no order of yours behind it, or a Uniswap range order fills. A notice names the market, the side, the size and the price (the trigger, for an exit) and links to the terminal. The app compares each read of your resting orders and positions with the one before, the same reads the terminal makes every 15 s: the first read after the page opens only sets the starting point, each event is shown once, and what you do in this tab, such as a cancel, a market order or a close, is not reported back to you. A position closed with no order of yours behind it is shown as liquidated when the last mark was at the liquidation price the venue reports, and as closed otherwise. Nothing is checked while Elyra is closed. To hear about it while the tab is in the background, turn on **Browser notifications** under **Order notifications** on [Alerts](https://elyratrade.io/alerts). ## Prices and charts Marks, 24 h change, volume, open interest and funding come from `MarketData` in the API, one cached view of every market Elyra lists, refreshed every 15 s from Hyperliquid's public API. A market with no mark is still listed, without one, and the app reads it as "no perp leg". Chart candles come from the same source and are cached for 60 s. The chart opens on the newest 1 000 bars, and scrolling to its left edge loads the 1 000 before them (`GET /candles?before=`), until an empty page marks the start of the history. When the API cannot be reached, pages stay empty and a status notice says the data is unavailable. ## Funding history Hyperliquid settles funding every hour. The funding chart shows the settled rate for each hour of the last 7 or 30 days. It sits in the `/markets` brief, beside the Hedge panel, and in the trade terminal's Funding tab. Bars above the line are hours when longs paid shorts; bars below it are hours when shorts paid longs. Above the chart are the range's average and how many hours each side paid; hover over an hour to read it. **Per hour** shows the rate as Hyperliquid settled it. **Annualised** multiplies each hour by 8,760 (24 × 365), simple and not compounded. That is what the past rate comes to over a year, not a forecast: funding changes every hour and can turn negative. The series comes from `GET /funding/history?market=&range=7d|30d`, oldest first. Each point carries `time` (unix seconds), `rate1h` (a signed fraction per hour, positive when longs paid) and `rateApr` (`rate1h` × 8,760). The API reads a market's 30 days once and serves both ranges from memory for a few minutes, with one read for every caller. When Hyperliquid rate-limits it, it serves the last series it read, marked `stale`; with nothing held it answers 503 with `Retry-After`. A market with no perp answers 404, and the chart says so. ## The simulated venue The API picks its venue from `VENUE`. The default builds `SimVenue`; the live setting builds a client for the signer. It is independent of how you sign in. SimVenue is a paper book priced from the real marks, so Trade and Portfolio work without a Hyperliquid account: - Each new account starts with 10,000 USDC. - Market orders fill 5 bps from the mark, against you. Limit orders fill when marketable, or rest until the mark crosses them. - Margin is isolated per market, maintenance is half the initial margin (a 2x long is liquidated about 25 % down), and funding accrues hourly, longs paying a positive rate. - Fills and funding settlements are kept (the last 500 of each) and served like Hyperliquid's. - Stop-loss and take-profit orders work as they do on the live venue. Nothing reaches Hyperliquid, and every write is still checked for a valid envelope. ## Keys at rest The signer keeps one file per address under `KEY_STORE_DIR` (`/data` in the Docker image). The agent wallet's private key in it is encrypted with a key derived from `KEY_ENCRYPTION_SECRET`, and the file is written under a temporary name, restricted to its owner, then renamed. The service will not start without `SIGNER_SECRET` and `KEY_ENCRYPTION_SECRET`, compares the shared secret in constant time, runs as an unprivileged user, and never logs key material. `GET /health` is its only open route. The key store must be persistent. If it is lost, no funds move, since no agent wallet can withdraw, but every address must approve a new agent wallet. Note: What the tests cover The signer's tests run against a fake Hyperliquid transport (`services/signer/test/kit.ts`) that makes no network call, and local development runs the API on the simulated venue. Response shapes are pinned at both ends: the API answers 502 `signer_bad_response` to anything that is not the recorded shape rather than show a zeroed account. ## Reference ### Signer settings Parameters: services/signer/src/config.ts - `MARKET_SLIPPAGE_FLOOR_BPS` (allowed: 100 bps): fixed in code; no market order is priced tighter - `DEFAULT_SLIPPAGE_BPS` (allowed: integer bps; default: 100): when a market order sends none - `MARKET_SLIPPAGE_CEILING_BPS` (allowed: floor to band bps; default: 1,000): more is refused, not clamped - `LIMIT_PRICE_BAND_BPS` (allowed: above 0 bps; default: 1,000): furthest a signed price may sit from the mark - `MAX_ORDER_NOTIONAL_USD` (allowed: above 0 USD; default: 250,000): size × mark per order ### Errors from `/perp/*` | Answer | Meaning | | --- | --- | | 400 `invalid_*` | a malformed field | | 401 `unauthorized` / `stale_ts`, 409 `nonce_used` | the envelope failed a check | | 401 `session_invalid` / `session_expired` / `session_ended`, 403 `session_scope` | a trading session's grant was malformed or too long, has expired or been ended, or was used beyond orders and cancels | | 404, 409, 422, 400 from the signer | no agent wallet; not approved or exits already resting; outside a bound; rejected by Hyperliquid | | 502 `signer_error` / `signer_unreachable` / `signer_bad_response` | the signer failed (a missing mark included), gave no answer within 10 s, or sent an unexpected shape | | 503 `signer_not_configured` | the API has no signer secret | Where it lives: - `services/signer/src/server.ts`: onboarding, /order and its routes - `services/signer/src/trading.ts`: the price bands and order signing - `services/signer/src/config.ts`: the floor, ceiling, band and notional cap - `services/signer/src/keyStore.ts`: encrypted key files - `apps/api/src/routes/perp.ts`: the /perp/* routes and the envelope contract - `apps/api/src/perp/auth.ts`: requirePerpAuth - `packages/core/src/perpAuth.ts`: the EIP-712 message and body hash - `apps/web/lib/perpSession.ts`: the trading session's tab key and grant - `apps/web/lib/usePerp.ts`: set-up, orders and cancels from the browser - `apps/api/src/venue/sim.ts`: SimVenue - `apps/api/src/marketdata/index.ts`: MarketData --- # Vaults Source: https://elyratrade.io/docs/vaults · Earn One-token Uniswap vaults and the DLMM and stock vaults: pricing, the price check, caps, harvest and rebalance. An Elyra vault takes your tokens, runs a liquidity position for you and gives you shares that track your part of it. This chapter covers the vaults that do only that: `LPVault`, which manages one Uniswap v3 position and takes a single token, and the two vaults on Elyra's own pools, `DlmmVault` and `StockVault`, which take both tokens of their pool. [Hedged vaults](https://elyratrade.io/docs/hedged-vaults) and [structured notes](https://elyratrade.io/docs/structured) are built on `LPVault` and have chapters of their own. In brief: - `LPVault` is an ERC-4626 vault: you bring one token, the vault's asset, and get shares priced at the pool's spot price, with the other leg valued net of the pool fee. - Every deposit, withdrawal and rebalance first checks that spot sits within `300 bps` of a mean taken over at least `10 min` of pool history, and reverts if not. During a fast move you may have to wait to exit. - A vault's cap is fixed when it is created and no key can change it. The vaults Elyra deploys and the graduated vaults have none, so they take deposits of any size. - Anyone can call `harvest`, at most every `6 h` in the vaults Elyra deploys: `10 %` of the collected fees goes to the protocol, `0.5 %` to the caller, and the rest is compounded. - After their first deposit, DLMM and stock vaults take both tokens as an exact slice of what they hold, so their shares need no price. Their withdrawals work even while the protocol is paused. ## Choosing a vault The `/earn` page lists every kind in one grid, with a filter per kind. The three in this chapter differ in what you bring and in who keeps the position centred. | | `LPVault` | `DlmmVault` | `StockVault` | | --- | --- | --- | --- | | Position | One Uniswap v3 range | `activeId ± halfWidth` bins of an Elyra DLMM pair | A base range and a one-sided limit range in a stock hook pool | | You bring | One token, the vault's `asset` | Both tokens in the vault's mix, or one token through the zap | Both tokens in the vault's mix | | Share price | Holdings valued at pool spot | Active bin price for the first deposit, then none: each deposit is an exact slice | Feed price for the first deposit, then none | | Re-centred by | Anyone, through `rebalance()` | The factory's keeper or the protocol owner | The factory's keeper or the protocol owner | | Fee to Elyra | `10 %` of harvested fees | None of its own | None of its own | | Created by | Anyone, through `VaultFactory` | The protocol owner | The protocol owner | ## Depositing one token You call `deposit(assets, receiver)` with the vault's `asset`. The vault checks its cap, if it has one, works out your shares with `previewDeposit`, runs the price check, takes the tokens and mints. Shares carry three more decimals than the asset, and the first deposit into an empty vault mints `1 000` share units per asset unit, so `2 ether` of WHYPE buys `2 000 ether` of share units, which a wallet shows as 2 shares. The offset is OpenZeppelin's defence against share inflation: an attacker who donates to a near-empty vault to round the next deposit down loses about a thousand times what they can take. Diagram: One deposit, one withdrawal. A deposit is checked against the cap (skipped when the vault has none, as every seed vault does), priced, guarded and put to work. A withdrawal is guarded, sized against what the vault can reach on chain and paid in the asset. Red chips mark where a step can revert. Your tokens do not go into the position straight away. `_deployIdle` adds the vault's idle balance only once it is worth at least the larger of `0.5 %` of `totalAssets()` and one thousandth of a unit (`0.001 WHYPE`, or `0.001 USDC`). Below that, the balance waits and still counts in the share price. Above it, a vault with no position opens one centred on the current tick, `policy.widthTicks` wide; a vault that has one adds to it. Both paths swap the part the range cannot use and mint the balanced pair through `ZapExec`. ## What a share is worth `totalAssets()` adds up everything the vault holds, in `asset`, at the pool's current price: ```text held = idle token0 + idle token1 + what the position would return if closed now value = asset leg + other leg × spot price × (1 − pool fee) ``` The other leg is discounted by the pool fee because the vault must sell it through the pool to pay anyone out. Valued gross, the last person to leave would find a shortfall of exactly the fee tier. Uncollected trading fees are left out on purpose: counting them would make a harvest lower the share price by the protocol cut and the bounty. Leaving them out means a harvest can only add value. After a harvest, a new depositor pays more than one unit per share. The fees the vault earned before you arrived belong to the people who were in it. ## Withdrawing `withdraw(assets, ...)` and `redeem(shares, ...)` run the same price check, burn your shares (spending an allowance if you act for someone else) and pull liquidity out of the position. The fraction removed is `assets / _liquidAssets()`, rounded up, so the vault takes slightly too much rather than paying one wei short; the spare stays idle. If the vault still holds too little `asset`, it sells the other leg through the pool with a floor of the spot quote less `policy.maxSlippageBps`. If even that is not enough, the call reverts `Shortfall` rather than pay less than the preview. A withdrawal does not take the protocol's cut. Fees that come out with the principal stay in the vault for the remaining holders; the cut is taken only by `harvest`, so the same fees are never billed twice. Note: The last holder out When the shares you burn are the whole supply, the vault closes the position, burns the NFT, sells the other leg and pays you its entire balance, not the previewed amount. The two differ by the price impact of that final swap. `redeem()` returns what was actually paid. ## The price check A position needs a price to be valued, and the pool's own spot price is the one an attacker can move inside a block. So `LPVault` runs `TwapGuard.check(pool)` before every deposit, withdrawal and rebalance. The same library guards a structured note's reserve pool and the swaps in a hedged vault's two margin calls, so every Elyra vault uses one definition of a sane price. Diagram: The price check. TwapGuard asks two questions and has a revert for each. The history must reach back ten minutes, because a mean over a window the attacker wrote is just spot. Then spot must sit within 3 % of the mean, compared as prices rather than ticks. The check has two parts. First, the pool's observation ring must reach back at least `MIN_TWAP_WINDOW` (`10 min`); otherwise it reverts `TwapWindowTooShort`. Second, spot must sit within `MAX_TWAP_DEVIATION_BPS` (`300`, that is `3 %` of the price) of the mean over `min(30 min, available history)`; otherwise it reverts `PriceDeviation`. The minimum window exists because a new pool's ring has one slot, rewritten in every block, so its oldest observation can be the attacker's own swap. `VaultFactory` grows each pool's ring to `900` slots when it creates a vault. A pool writes at most one observation per block timestamp, so at most one a second however fast the chain makes blocks, and `900` slots always reach back fifteen minutes once filled: no burst of swaps can shorten the window under the ten-minute minimum. Anyone can deepen the ring further with the pool's permissionless `increaseObservationCardinalityNext`. The check is skipped in one state: while the vault has no shares. Nobody can be robbed in an empty vault, and without the exception the first depositor into a vault on a fresh pool could never get in. Everyone after them waits until the ring reaches back ten minutes. Warning: A fast market can hold your exit The check guards withdrawals too. If the price jumps by more than `3 %`, spot stays outside the band until the 30-minute mean catches up, and every deposit, withdrawal and rebalance reverts until then. A vault that cannot price itself honestly does not trade at all. ## Harvest and rebalance Two calls keep an `LPVault` working, and anyone may make either. Diagram: Harvest and rebalance. Both calls are open to anyone. harvest() compounds fees and skips the price check; rebalance() moves principal, so it runs the same check as a deposit. The protocol cut and the caller’s bounty come out of fees only. `harvest()` collects every fee the position has earned and splits each token separately: `PROTOCOL_FEE_BPS` (`1000`, `10 %`) goes to the `FeeRouter`, where it all lands on the treasury because a vault never has a referrer, and `HARVEST_BOUNTY_BPS` (`50`, `0.5 %`) goes to the caller. The remainder is added back to the position; idle deposits are not. It reverts `NoPosition` before the vault has opened a range and `TooSoon` within `policy.minInterval` of the last harvest. It runs no price check: it moves no principal, its swap is bounded by `maxSlippageBps`, and a guard here would only let a manipulator stop the vault being paid. Elyra's keeper bot simulates `harvest` on each vault in the deployment manifest once per `VAULT_HARVEST_INTERVAL_MS` (`6 h`) and sends it when the simulation passes. `rebalance()` closes the position and mints a new one centred on the current tick. It needs the tick past a range edge by the hysteresis, `tick < tickLower − hysteresisTicks` or `tick ≥ tickUpper + hysteresisTicks` (otherwise `InRange`), `minInterval` since the last rebalance (otherwise `TooSoon`), and a passing price check, because it swaps and re-centres real value. The fee part of what it collects is split exactly like a harvest, and it resets the harvest clock. `shouldRebalance()` answers the same questions without reverting, including the price check, so a caller can ask before paying gas. When the vault mints, two separate bounds apply. `policy.maxSlippageBps` (`100` in the vaults Elyra deploys) limits value lost in the swap, against a spot quote. `MINT_RATIO_TOLERANCE_BPS` (`500`) limits how far the minted amounts may fall short of the balanced holdings, which drifts further the narrower the range. A narrow range with a large deposit can fail the second bound; the fix is a wider range. ## Caps and who can create a vault `cap` is set in `initialize` and has no setter. `CapUpdated` is emitted once, at creation. A mutable cap would be an admin key under another name, so a different cap means deploying a new vault. `type(uint256).max` (`NO_CAP`) means no cap: `maxDeposit()` and `maxMint()` answer `type(uint256).max` and the check is skipped. Any other value is a limit, `maxDeposit()` returns the room left under it, and the deposit drawer on `/earn` refuses an amount over it ("More than the vault cap allows") before you sign. The vaults Elyra deploys, the hedged vaults and the graduated vaults are created with no cap, and `/earn` shows them as "No cap". `VaultFactory.createV3Vault` is open to anyone, because a vault has no admin and can touch only its depositors' funds. It clones the implementation, initialises the clone in the same transaction so nobody else can, grows the pool's observation ring and emits `VaultCreated` with `kind` `0`. Being in the factory's list is therefore not an endorsement. The app shows the vaults named in the deployment manifest and those that [graduation](https://elyratrade.io/docs/graduation) created, and treats any other address as unverified. ## Vaults on Elyra pools `DlmmVault` and `StockVault` sit on [Elyra's own pools](https://elyratrade.io/docs/pools). After the first deposit, both take each deposit as an exact slice of everything the vault already holds, in both tokens and in the vault's current mix, so a share needs no price and moving the pool before you deposit cannot dilute anyone. Neither ever swaps, neither charges a fee of its own (the pool's swap fees compound), and both lock `MIN_SHARES` (`1000`) at the dead address on the first deposit to block share inflation. Deposits and rebalances stop while the protocol is paused; withdrawals never do. **DLMM vaults.** A `DlmmVault` holds bins `activeId ± halfWidth`, filled in one of three shapes: Spot (`0`, even), Curve (`1`, deepest at the active bin) or Bid-Ask (`2`, deepest at the edges). `deposit` takes `activeIdDesired` and `idSlippage` and reverts if the active bin has moved further than that; the slice goes into each bin in the vault's own proportions, and its share of the active bin is cut to that bin's own X:Y mix (what does not fit stays idle in the vault, inside the slice you paid for), so a deposit never pays the pool a composition fee. The first deposit opens the range around the active bin and is valued at that bin's price. `withdraw` burns a slice of every bin and of the idle balance, with your minimum amounts. **Stock vaults.** A `StockVault` centres a base range on the stock hook's feed price, from Elyra's keeper-updated price feed: `openHalfWidth` ticks while the market is open, and the wider `closedHalfWidth` while it is closed and the stock's price stands still. What the base cannot take at the current price waits in a one-sided limit range next to it, on the side where it only fills at or beyond the feed price. The first deposit needs a fresh feed price and a pool price within `maxDeviation` of it, and is valued at the feed price. A session change makes a rebalance due, so the range is re-laid at least twice per trading day. Diagram: When the pool vaults re-centre. Left: the DLMM keeper waits until a drift past half the range has held for two minutes, then lays every bin out again around the active one. Right: the order of the checks behind StockVault.rebalanceStatus(); only READY lets rebalance() through. Neither vault swaps. Only the factory's `keeper()` or the protocol owner can rebalance either vault, at most once per `MIN_REBALANCE_INTERVAL` (`5 min`). A DLMM vault is due once the active bin is more than `halfWidth / 2` bins from the range centre (`needsRebalance()`); Elyra's bot also waits until that drift has held for `DLMM_SUSTAIN_S` (`120 s`) and sends with an `idSlippage` of `2` bins. A stock vault reports its own readiness through `rebalanceStatus()`, and the bot sends only on `READY`. ### One token into a DLMM vault `DlmmVaultZap` turns one token, native HYPE included, into a DLMM vault deposit in a single transaction, and a withdrawal back into one token. It has no owner, holds nothing between calls and accepts only vaults the DLMM vault factory made. You choose the swap amount and the route; the contract checks that the route connects the vault's two tokens, swaps through the Elyra Router, deposits both sides with your `minShares`, and returns what the vault did not take. `zapOut` redeems your shares (they need an approval), swaps the side you do not want and enforces `minOut`. The app plans the split with `planZapIn` in `packages/agent/src/route/zapPlan.ts`. It swaps `s = A · tO / (tO + tT · r)` of an input `A`, where `tT` and `tO` are the vault's holdings of the input and the other token and `r` is the route's rate at that size, quoting three times to settle `r`. Routes use other Elyra pools between the two tokens, never the vault's own pair, whose price the split depends on. Every DLMM and stock vault write from the app carries `0.5 %` minimums and a `20 min` deadline. ## Reference ### LPVault settings Parameters: LPVault.Init - set once by VaultFactory.createV3Vault - `pool` (allowed: Uniswap v3 pool): The one pool the vault provides liquidity to. - `asset` (allowed: token0 or token1 of the pool): What you deposit and what shares are priced in. Anything else reverts NotAsset. - `name / symbol` (allowed: strings; default: set at creation): The share token. - `policy.widthTicks` (allowed: positive multiple of the spacing ticks; default: 2 × 2231, snapped): Full width of each range the vault mints: 2231 ticks (a 1.25x price factor) each side, snapped down to the spacing. - `policy.hysteresisTicks` (allowed: 0 or more ticks; default: 10 spacings): How far past an edge the tick must sit before rebalance is allowed. - `policy.minInterval` (allowed: any seconds; default: 6 h): Least time between two harvests, and between two rebalances. - `policy.maxSlippageBps` (allowed: 0 - 9999 bps; default: 100): Floor on every swap the vault makes, against a spot quote. - `policy.compound / bountyBps` (allowed: bool / bps; default: true / 50): Recorded for bots; the vault always compounds and always pays HARVEST_BOUNTY_BPS. - `cap` (allowed: asset units, or type(uint256).max; default: none (NO_CAP)): Deposit cap. Cannot change. type(uint256).max means no cap. - `feeRouter, npm, router, wrappedNative` (allowed: addresses): Where the protocol cut goes, the position manager, SwapRouter02 and WHYPE. Parameters: Pool vault settings - set by the protocol owner at creation - `halfWidth` (allowed: 1 - 50 bins; default: 10 (local seed)): DlmmVault range is activeId ± halfWidth; a rebalance is due past halfWidth / 2. - `shape` (allowed: 0, 1, 2; default: 1, Curve (local seed)): DlmmVault: Spot, Curve or Bid-Ask, for every deposit into the range and every rebalance. - `openHalfWidth` (allowed: tick spacing - 10 000 ticks; default: 120 (local seed)): StockVault half width while the market is open. - `closedHalfWidth` (allowed: tick spacing - 10 000 ticks; default: 300 (local seed)): StockVault half width while the market is closed. - `maxDeviation` (allowed: 1 - half of each half width ticks; default: 50 (local seed)): StockVault waits while the pool is further than this from the feed price. One DLMM vault exists per pair, half width and shape, and one stock vault per stock pool; the stock vault factory refuses a pool that is not the stock hook's or that quotes in native HYPE. ### Reverts | Revert | Raised by | Meaning | | --- | --- | --- | | `CapExceeded` | `LPVault` deposit, mint | The deposit would take `totalAssets()` past the cap. Never raised by a vault with no cap. | | `ZeroShares` | `LPVault` deposit, mint | The deposit would mint no shares. | | `TwapWindowTooShort` | `LPVault` deposit, withdraw, `rebalance` | Less than `10 min` of pool history. Not raised while the vault has no shares. | | `PriceDeviation` | `LPVault` deposit, withdraw, `rebalance` | Spot is more than `3 %` from the mean. | | `Shortfall` | `LPVault` withdraw | The unwind raised less than the withdrawal owes. Never on a full exit. | | `NoPosition`, `TooSoon`, `InRange` | `harvest`, `rebalance` | No range opened yet, inside `minInterval`, or the tick has not left the range by the hysteresis. | | `NotAsset`, `BadPolicy`, `AlreadyInitialized` | `initialize` | Wrong asset, a malformed policy, or a second initialisation. | | `DlmmVault__ActiveIdSlippage` | DLMM deposit, rebalance | The active bin moved more than `idSlippage` bins. | | `DlmmVault__InsufficientShares`, `__AmountSlippage` | DLMM deposit, withdraw | Below your `minShares` or minimum amounts. | | `DlmmVault__NotNeeded`, `__TooSoon`, `__NotKeeper` | DLMM rebalance | No drift past half the range, inside `5 min`, or the wrong caller. | | `StockVault__PriceDeviation`, `__StaleOracle` | stock first deposit, rebalance | The pool is too far from the feed price, or the feed is stale. | | `DlmmVaultZap__BadRoute`, `__TooLittleReceived` | `zapIn`, `zapOut` | The route does not connect the vault's tokens, or the output is under `minOut`. | ### Events `LPVault` emits `CapUpdated(cap)` once, `PositionOpened(tokenId, tickLower, tickUpper)` on each new range, `Harvest(fees0, fees1, protocolShare0, protocolShare1, bounty0, bounty1)` in pool-token units, `Rebalance(tickLower, tickUpper, tokenId)`, and the standard ERC-4626 `Deposit` and `Withdraw`, where `Withdraw` reports the amount actually paid. `VaultFactory` emits `VaultCreated(vault, pool, asset, kind, name)`. Where it lives: - `contracts/src/LPVault.sol`: totalAssets, _deposit, _deployIdle, _withdraw, _liquidate, harvest, rebalance - `contracts/src/libraries/TwapGuard.sol`: the two checks, the constants and why the window has a floor - `contracts/src/libraries/ZapExec.sol`: balanceAndMint and balanceAndIncrease, and the two bounds - `contracts/src/VaultFactory.sol`: createV3Vault, prepare at creation, vaultKind - `contracts/script/ElyraWiring.sol`: the seed policy, NO_CAP and the plain seed vaults - `contracts/src/venue/vaults/DlmmVault.sol`: deposit, withdraw, rebalance, needsRebalance, the three shapes - `contracts/src/venue/stockvaults/StockVault.sol`: the base and limit ranges, rebalanceStatus, deposit and withdraw - `contracts/src/venue/vaults/DlmmVaultZap.sol`: zapIn, zapOut and the route check - `apps/api/src/bots/keeper.ts`: the vault harvest sweep - `apps/api/src/bots/dlmmVaultRebalancer.ts`: the sustain wait before a DLMM rebalance - `packages/agent/src/route/zapPlan.ts`: how the app splits a one-token deposit - `packages/agent/src/route/twoSided.ts`: how the app sizes a two-token deposit: type one side, the other follows - `apps/web/lib/amm/zap.ts`: the routes the app quotes for a zap - `apps/web/lib/earn/view.ts`: capPct and depositBlocker, behind the cap bar and the drawer --- # Hedged vaults Source: https://elyratrade.io/docs/hedged-vaults · Earn An LP vault with a Hyperliquid short: the reporting and funding keys, margin in transit, and when it pauses. A liquidity position is long the token it holds, whether you want that exposure or not. `HedgedLPVault` is an [`LPVault`](https://elyratrade.io/docs/vaults) paired with a short perp on Hyperliquid, sized to the position's delta, so you keep the fee income and shed most of the price risk. The short lives on a venue Elysium cannot read, so the vault takes the hedge's value from reports sent by one key. This chapter covers what that key can and cannot do, how reports are checked, and where the margin lives: in a Hyperliquid account owned by the vault's funder key. In brief: - Open, with no deposit cap. Elyra's hedged vaults sit on EQX stock pools, each hedged with the stock's HIP-3 market on Hyperliquid: EQNVDA with `xyz:NVDA`, EQSPY with `xyz:SP500`. - The short runs on a Hyperliquid account owned by the vault's **funder key**, an ordinary wallet key the operator holds offline, because a contract cannot own a Hyperliquid account that trades. Whoever holds that key can withdraw the margin there. - Two keys with separate jobs. The hot hedger key can only report; the cold funder key moves margin out, as a USDC transfer to its own address, at most `10 %` of the vault's on-chain assets per call, out of an allowance of `25 %` that refills over a day. Each hedged vault has its own funder, and the funder can replace the hedger key (`setHedger`). - The hedger's figure is believed only within `15 %` an hour of an anchor and up to three times the margin ever funded, reports are at least five minutes apart, and a larger move is walked in at that rate. Exits stay open and count the hedge at the lower of the reported and believed figure, and at zero when the last report is older than `1 h`; deposits wait until the two agree and the report is fresh. - Margin on its way between the vault and Hyperliquid still counts: `fundHedge` and `returnHedge` move the stored equity in the same transaction, and the hedger reports the USDC still travelling, so the share price does not dip while margin crosses the bridge. - An exit larger than the vault's on-chain holdings reverts until the funder brings margin back with `returnHedge`. ## How the hedge is counted On chain, the hedge is a few numbers. `hedgeCollateralUsd()` is the USDC the vault has ever sent out as margin. `hedgeState()` gives the last report as said (`reportedEquityUsd`) and the figure the vault believes (`equityUsd`, 6 decimals like USDC); both carry the USDC funded and returned since (see [Margin in transit](#margin-in-transit)). The share price adds the lower of the two to the plain vault's figure: ```text totalAssets() = LP position + idle balances (as in LPVault) + min(equityUsd, reportedEquityUsd) in the vault's asset ``` When the vault's asset is not USDC, the equity is converted through Elyra's keeper-updated HYPE/USD feed. If the feed reverts, answers zero or less, or is older than `1 h` (`FeedGuard.MAX_FEED_AGE`; the keeper pushes it at least every 15 minutes), the hedge counts as zero rather than reverting, and deposits wait. Reverting would freeze withdrawals during a feed outage; under-counting only makes exits cheaper for whoever leaves then. ## Two keys, two jobs | Key | What it can do | What it cannot do | | --- | --- | --- | | Hedger (hot, on the API server) | Call `reportHedge` | Move any funds | | Funder (cold, operator-held, one per vault) | Call `fundHedge`, within its caps, and `returnHedge`. Own the vault's Hyperliquid account, so withdraw the margin there | Make the vault pay any address but its own | | Signer's agent wallet for the funder's account | Open, close and resize the perp in that account | Withdraw or transfer from the account | `initializeHedged` reverts `BadFunder` if the funder is unset or is the hedger. The agent wallet lives in the [signer](https://elyratrade.io/docs/perps); the funder approves it once for its Hyperliquid account. ### Where the margin lives A Hyperliquid account is an address, and only that address's key can approve an agent wallet or withdraw. A vault contract has no key, so it could never trade an account of its own. `fundHedge` therefore sends the margin to the vault's **funder** instead, and the funder's Hyperliquid account is the vault's hedge account: the signer holds an agent wallet for it, the hedger trades and reports it, and `fundingConfig().funderKey` names it on chain. **Whoever holds the funder key can withdraw the margin on Hyperliquid.** What bounds it is on chain: the funder can take at most `10 %` of the vault's on-chain assets per call, out of an allowance of `25 %` that refills linearly over a day (so no burst moves more than `25 %`, and no day more than twice that), measured against the position and idle balance, never against reported equity. The funder key is cold, held by the operator and used for that vault alone. Hyperliquid accounts are one per address, so one account shared by two vaults would mix their equity and net their shorts. Each hedged vault therefore gets its own funder, the deploy refuses a funder that is the deployer, the owner, the hedger or the keeper, or that two vaults share, and the hedger skips any two vaults that resolve to the same account. The manifest records them under `funders`. ### Funding the hedge `fundHedge(assetAmount)` turns vault assets into USDC margin at the funder's address. Only the funder calls it; nothing in the API does. 1. Refuse while deposits wait: `EquityJump` while the reported and believed figures differ, `HedgePaused_` on a stale report or a silent feed, so the caller can tell them apart. 2. Check the caps: At most `maxFundBpsPerCall` of the on-chain assets (LP position plus idle balance) per call, out of an allowance of `maxFundBpsPerPeriod` that refills linearly over a day. Both are measured against on-chain value, never the reported equity. Over either reverts `FundCapExceeded`. 3. Free the asset: If the idle balance is short, the vault pulls it from the LP position as a withdrawal would, with that swap floored at the LP pool's spot quote less `maxSlippageBps`. 4. Swap at a TWAP floor: When the asset is not USDC, `HedgeFunding` runs `TwapGuard.check` on the asset/USDC pool and sells with a floor of the TWAP quote less `maxSlippageBps`. 5. Transfer to the funder: The USDC goes to the funder's address on Elysium, the only recipient the function knows. From there the funder bridges it to HyperEVM and into the vault's Hyperliquid account. 6. Count it at once: The USDC delivered is added to `hedgeCollateralUsd` and to the stored equity, the crossing time is recorded, and `HedgeFunded` is emitted. The share price loses the swap's cost and nothing else. ### Bringing margin back The funder withdraws USDC from Hyperliquid with its own key (Elyra's agent wallet cannot), brings it back to Elysium, approves the vault for it and calls `returnHedge(stableAmount)`. It works in every state, deposits waiting or not, because bringing margin home is the emergency procedure. The vault takes the USDC, sells it for its asset behind the same TWAP floor as the funding swap when the asset is not USDC, keeps it as idle asset and lowers the stored equity by the same USDC, all in one transaction. The share price moves by the swap's cost only, and the next report, which no longer sees that USDC anywhere, matches what the vault already stores. Never transfer USDC straight to a vault whose asset is not USDC: `totalAssets()` does not count it, and no function can move it again. Use `returnHedge`. ## Margin in transit Margin takes time to cross either way: a withdrawal from Elysium to HyperEVM takes about 24 hours before the funder can move it into Hyperliquid. If only the Hyperliquid account counted, the share price would dip by up to a tenth while margin travelled, and anyone could deposit in the dip and redeem after the next report, taking the difference from the other holders. So the margin is counted wherever it is: Diagram: Margin in transit. Where the vault's margin is counted at each step of a round trip. The two crossings the chain sees, fundHedge and returnHedge, move the stored equity in the same transaction; every place in between is in the hedger's report. So the share price does not dip while margin travels, either way. - **The two crossings the chain sees** move the stored equity in the same transaction, in the units reports use: `fundHedge` adds the USDC it delivered, `returnHedge` takes off the USDC it received. A report dated at or before the last crossing reverts `StaleReport`, because it was read before the crossing and would undo it. - **Everything in between is the hedger's.** The report is the Hyperliquid account's equity, plus the funder's USDC that is still on its way: in the funder's wallet on Elysium, in the bridge, and on HyperEVM at the funder's address. The funder wallet belongs to its vault by construction: one per vault, used for nothing else. - **When pieces move during a read**, they are counted twice rather than not at all. The hedger reads the travelling margin before the Hyperliquid account and the chain last, so a transfer that lands mid-read appears in two places for one report. That makes the reported figure briefly high, which the band and the deposit gate keep anyone from buying against; never low, which is the sandwich. A piece that cannot be read at all stops the report: the last one stands, and after `1 h` deposits wait and exits count the hedge at zero. ### Onboarding the hedge account The funder's Hyperliquid account trades once it holds USDC and the funder has approved the signer's agent wallet for it, with the same onboard and approval steps the web makes, signed by the funder key. Until that is done the hedger skips the vault with an alert, and the app takes no deposits into a hedged vault that has never been reported on. ## The hedger bot The hedger runs inside the API process when `BOTS` includes it, once every `HEDGER_INTERVAL_MS` (`30 s`). It works on every manifest vault whose name contains "Hedged", plus any address in `HEDGED_VAULTS`. Diagram: Hedger and funder. Solid arrows are calls, dashed arrows are reads. The hot hedger key only reports. The cold funder key moves margin, capped, to its own address, and bridges it into the funder's own Hyperliquid account, which a contract could not trade. Margin comes back when the funder withdraws USDC on Hyperliquid, brings it back to Elysium and hands it to returnHedge. For each vault, one tick does this: 1. **Read the position**: `positionTokenId()`, `pool()` and `asset()` on the vault, then `positions(tokenId)` and `slot0()`. A vault without liquidity is skipped. 2. **Size the target short**: the vault's asset is the numeraire, and the other pool token, the EQX stock, is the risk asset, whichever side of the pair it sorts to. Core's `lpDelta` returns the position's current balance of the risk asset; shorting that much cancels the price exposure for now, and the balance changes as the price moves, so the bot re-sizes. 3. **Find the current short** on the vault's hedge account, `fundingConfig().funderKey`. The market comes from `VAULT_MARKETS` or the HIP-3 market for the stock (`xyz:SP500` for EQSPY). A long position counts as zero; the bot never opens longs. An account with no agent wallet approved is skipped with the `hedger.account_not_onboarded` alert: no order and no report. 4. **Decide**: drift is the gap between target and current short, in bps of the target. The tick acts if a report is due (`HEDGE_REPORT_INTERVAL_MS`, `15 min`) or drift exceeds `HEDGE_DRIFT_BPS` (`200`); otherwise it does nothing. 5. **Trade**: core's `hedgeOrders` returns at most one market order. It skips differences under `HEDGE_MIN_NOTIONAL_USD` (`$50` at the mark) and rounds down to the market's size precision. Sells grow the short; buys shrink it and are always `reduceOnly`, so the account cannot flip long by accident. 6. **Report**: it reads the hedge account back and sends `reportHedge` with signed notional (negative for a short), summed pnl, the account's equity plus the margin in transit, floored at zero, and its own clock less `10 s` as `asOf`, taken before the first read. Reporting pays no bounty; it is sent whenever the simulation passes. Three rails sit on top of the tick. `HEDGER_MODE` is the kill switch: `report-only` places no order but keeps reporting, and `off` does nothing, so after `1 h` deposits wait and exits count the hedge at zero. `HEDGE_MAX_ORDER_USD` (`$25,000`, at most the signer's `MAX_ORDER_NOTIONAL_USD`) splits a large re-hedge into one order per tick. `HEDGE_DAILY_LOSS_USD` (`$2,500`) stops orders for the rest of the UTC day once the hedges have lost that much, net of margin moved in or out; reports continue. A per-vault ceiling on the short, `HEDGE_MAX_NOTIONAL_USD`, is off by default, so a vault is hedged in full whatever its size. The vault takes one report every five minutes, so a report that would follow an order sooner waits for the next tick past it. On the vault card, the delta chip shows the residual exposure: `(LP value + notional) / LP value`, green at `5 %` or less. Until the exposure reaches the hedger's minimum order, the card shows "Not hedged yet" with the exposure and the minimum. ## When deposits wait `reportHedge` has three reverts and never rejects a number: `NotHedger` for any other caller, `StaleReport` for an `asOf` in the future, not after the previous report, or not after the last `fundHedge`/`returnHedge`, and `ReportTooSoon` within five minutes (block time) of the previous report. It is also `nonReentrant`, so a report can never land in the middle of a deposit, withdrawal or funding. Every other report is stored as said and emits `HedgeReported`, because hiding a real loss would be worse than showing it; the vault then decides how much of it to believe. Diagram: The report gate. A report that clears the three reverts is stored as said, and believed only inside the hourly band and under the ceiling. Exits count the lower figure, and zero on a stale report or a silent feed; deposits wait in those cases and while the figures differ. StructuredVault.reportSleeve runs the same code, with its band on anchor plus collateral and its ceiling at half the collateral. The believed figure follows the reports inside a band around an hourly anchor: ```text anchor = the believed equity at the first report of each hour (crossings move it too) believed = reported, clamped to anchor × (1 ± maxEquityJumpBps), and to 3 × USDC ever funded − USDC ever returned exits = min(believed, reported), or 0 when now − lastReportAt > maxHedgeAge or the feed is silent paused() = believed ≠ reported, or the report is stale, or the feed is silent (deposits wait) ``` A report beyond the band is believed up to its edge, and the next hour's anchor starts there, so a larger move is walked in at `15 %` an hour: a `40 %` drop is believed in full three hours after it is reported, a doubling four hours after. Across one hour boundary two bands can follow each other within minutes, so the worst case is about `32 %` in a few minutes and `15 %` an hour after that. Around a zero anchor nothing above zero is believed: margin arrives through `fundHedge`, never through a report, and a vault that never received margin believes nothing at all. A first report is checked against the margin funded before it. An [Income note](https://elyratrade.io/docs/structured#reporting-the-income-sleeve) runs the same code for its sleeve, with the band measured on the anchor plus the note's collateral and a ceiling of half that collateral, since its collateral never leaves the note. A drop to zero (a liquidation) counts for exits at once but is never reached by the walk, so the funder, who can see the account, calls `acceptReport()`: the believed figure and the anchor move down to the reported one. It only ever lowers the figure, since the funder already holds the margin that left the chain. `HedgePaused("jump")` (or `"ceiling"`) marks the two figures parting and `HedgeResumed` their meeting again; staleness needs no transaction. A vault that was never reported on is not stale. While `paused()` is true, `_deposit` reverts `HedgePaused_`: the vault cannot say what a share is worth, and a deposit at the lower figure would buy below value. Withdrawals never wait on it; they value the hedge conservatively instead, so a stale or broken hedge cannot freeze anyone in and cannot be inflated on the way out. A paused hedged vault also stops the deposits of a [Protected note](https://elyratrade.io/docs/structured) that holds a slice of it, not its exits. The vault card's status chip says "Deposits paused: stale report", "Deposits paused: equity jump" or "Deposits paused: price feed". ## Limits **Exits are bounded by on-chain holdings.** The hedge equity sits in a Hyperliquid account the vault cannot unwind, so a withdrawal is sized against the LP position and idle balance alone. While a large part of the value is in the hedge, an exit bigger than the on-chain holdings reverts `Shortfall` until the funder returns margin with `returnHedge`, which takes at least the bridge's time. **The bounds are a rate, not a verdict.** A dishonest or broken reporter can still move the believed figure by `15 %` an hour, up to three times the margin funded, and exits pay at that figure. What the contract buys is time: hours, not one block, for the operator to compare the on-chain figure with the Hyperliquid account (public) and rotate the hedger with `setHedger`. **The margin is in the operator's account.** The contract bounds how much can leave for Hyperliquid, not what happens to it there: a lost, stolen or misused funder key, or a failure on the bridge or on Hyperliquid, can cost the vault the margin outside it: up to a quarter of its on-chain assets at once, and no more than half in a day, as the allowance refills. Danger: What the contract bounds A hedged vault's share price includes a number one key reports, and its hedge margin sits in a Hyperliquid account another key controls. The contract believes the report at most `15 %` an hour and up to three times the margin funded, counts it conservatively for exits, values it at zero once it goes quiet, lets the funder replace the reporting key, and lets the funder take at most a quarter of the vault at once, to its own address only. It cannot tell an honest report from a dishonest one inside those bounds, and it cannot stop the funder key from withdrawing what is already on Hyperliquid. ## Reference ### Settings Parameters: HedgedLPVault.HedgedInit - deploy values from ElyraWiring - `base` (allowed: LPVault.Init): Everything a plain vault needs. - `hedger` (allowed: address; default: env HEDGER): The only caller of reportHedge. - `funder` (allowed: address, not the hedger; default: one per vault): The only caller of fundHedge and returnHedge, the only recipient of margin, and the owner of the vault's Hyperliquid account. - `maxFundBpsPerCall` (allowed: 1 - maxFundBpsPerPeriod bps; default: 1000): Largest single funding, as a share of on-chain assets. - `maxFundBpsPerPeriod` (allowed: up to 10 000 bps; default: 2500): The funding allowance, refilling linearly over a day. - `usdc / usdcPool` (allowed: token / asset-USDC pool): Margin token and the pool fundHedge sells through when the asset is not USDC. - `price feed` (allowed: Elyra's HYPE/USD feed): Converts equityUsd into the asset. Required: initializeHedged reverts NoFeed without one. - `maxHedgeAge` (allowed: uint32 seconds; default: 1 h): Report age after which exits count the hedge at zero and deposits wait. - `maxEquityJumpBps` (allowed: uint16 bps; default: 1500): The band around each hour's anchor the believed equity moves in. `hedgeConfig()` returns a vault's staleness bound, band, report window (`1 h`) and report spacing (`5 min`) and its addresses; `fundingConfig()` returns the funder, its caps and the allowance in use. The hedged vaults Elyra deploys are named in the deployment manifest, with the plain vaults' policy and no deposit cap (`NO_CAP`). ### Reverts and events | Revert | Raised by | Meaning | | --- | --- | --- | | `NotHedger` | `reportHedge` | The caller is not the hedger. | | `NotFunder` | `fundHedge`, `returnHedge` | The caller is not the funder. | | `FundCapExceeded` | `fundHedge` | Over the per-call cap or the allowance in use. | | `TwapWindowTooShort` / `PriceDeviation` | `fundHedge`, `returnHedge` (`TwapGuard`) | The asset/USDC pool has under ten minutes of history, or spot is off its TWAP. | | `EquityJump` / `HedgePaused_` | `fundHedge` | The reported and believed figures differ, or the report is stale or the feed silent. | | `HedgePaused_` | deposit | `paused()` is true. Withdrawals never raise it. | | `CapExceeded` | deposit, mint | Over the cap. Elyra's hedged vaults have none. | | `StaleReport` | `reportHedge` | `asOf` is in the future, not after the last report, or not after the last `fundHedge`/`returnHedge`. | | `Shortfall` | withdraw | The exit needs more than the on-chain holdings can raise. | | `NotAsset`, `BadFunder`, `BadFundCap`, `NoFeed` | `initializeHedged` | Wrong asset or pool, a bad funder, caps that are zero, unordered or above `100 %`, or no price feed. | The plain vault's reverts also apply; see [Vaults](https://elyratrade.io/docs/vaults#reverts). Also `ReportTooSoon` (`reportHedge` within five minutes), `NothingToAccept` (`acceptReport` with nothing lower to believe) and `BadHedger` (`setHedger` to zero or the funder). Events: `HedgeFunded`, `HedgeReturned`, `HedgeReported(notionalUsd, unrealizedPnlUsd, equityUsd, asOf)` with the figure as said, `HedgeBelieved(equityUsd, anchorUsd)` with the figure believed, `HedgePaused(reason)` when the two part, `HedgeResumed()` when they meet, and `HedgerSet(hedger)`. Where it lives: - `contracts/src/HedgedLPVault.sol`: fundHedge, returnHedge, reportHedge, paused and the hedge in the share price - `contracts/src/libraries/HedgeFunding.sol`: the band, the ceiling, the funding allowance, the TWAP-floored swaps both ways and the margin transfer - `contracts/script/ElyraWiring.sol`: MAX_HEDGE_AGE, MAX_EQUITY_JUMP_BPS, the fund caps, one funder per hedged vault - `apps/api/src/bots/hedger.ts`: one tick on the funder's account: read, size, trade, report - `apps/api/src/bots/hedgerFlows.ts`: margin in transit and the read order - `packages/core/src/hedge.ts`: lpDelta and hedgeOrders - `apps/api/src/config.ts`: the HEDGE_* settings, HEDGED_VAULTS and VAULT_MARKETS - `apps/web/lib/earn/view.ts`: the custody note, the first-report gate, hedgeStatus and hedgeDelta - `contracts/test/HedgedLPVault.t.sol`: the funding caps, the pause cases, the zero-equity report, the broken feed and the return round trip --- # Structured notes Source: https://elyratrade.io/docs/structured · Earn Income and Protected: two dated payoffs built from an LP sleeve, a perp sleeve or a reserve token. A structured note is a vault with an end date. `StructuredVault` splits each deposit between an [`LPVault`](https://elyratrade.io/docs/vaults) and a second sleeve, and after maturity it unwinds everything back to its asset. In `Income` mode the second sleeve is a long perp position run off chain, and the upside is capped; in `Protected` mode it is a reserve token bought through one Uniswap pool, which puts a floor under the downside. This chapter explains how a note is built, what it pays, how you leave it and where the floor stops protecting you. In brief: - A note has a fixed term and one asset. The notes Elyra deploys are named in the deployment manifest and listed on Earn with their split, term and maturity. - Leaving before maturity costs `50 bps`, and the previews already show the amount after the fee. After maturity there is no fee, and anyone can call `settle` once to turn the whole note back into its asset. - The Protected floor is arithmetic on a reserve sleeve bought through a Uniswap pool, measured in the note's asset, not a promise from anyone. - A Protected note's LP slice sits in a hedged vault and follows it: while that vault holds deposits, the note's deposits revert too. Exits never wait on it. - An Income note's long has no on-chain path to Hyperliquid margin, so the app lists Income notes as "Coming soon" and they take no deposits. ## Two modes, one split `sleeveBps` is the share of every deposit that goes to the mode's own sleeve. The rest goes to the other one. Diagram: Where a deposit goes. Income keeps the non-LP share idle as collateral for a long the hedger reports on; Protected buys the reserve token through a guarded pool and puts the rest in the LP vault. Leaving works the same way in both modes, along the bottom. In `Income`, the `sleeveBps` share goes into the LP vault and the rest stays in the note as idle asset, which the contract treats as collateral for a long the hedger runs off chain. In `Protected`, the `sleeveBps` share is swapped to the reserve token through the asset/reserve pool and the rest goes into the LP vault. A note can sit on a [hedged vault](https://elyratrade.io/docs/hedged-vaults) and use its ordinary `deposit` and `redeem`, so the LP vault's price check applies to the note's money too, and its pause to the note's deposits: a pool off its mean makes the note's deposit or exit revert, and a hedged vault whose deposits wait makes the note's deposit revert. The hedged vault's exits never wait, so neither do the note's. ### Income notes An Income note's long is backed by the share kept idle in the note, but nothing moves that collateral to Hyperliquid: `StructuredVault` has no funder and no funding call. Running one needs a bounded path into a dedicated funder's Hyperliquid account, like `fundHedge`, and a hedger leg that trades the long and calls `reportSleeve`. Until then an Income note is created with a cap of `0`: `maxDeposit()` reads zero and `deposit` and `mint` revert `CapExceeded`. A cap never changes, so opening an Income note means creating a new one through `VaultFactory`. ## What a note is worth `totalAssets()` is the idle asset, plus the note's LP shares at `lpVault.convertToAssets`, plus the second sleeve: the reserve token valued at the pool's TWAP for `Protected`, or for `Income` the sleeve equity at the lower of the reported and the believed figure (see [Reporting the Income sleeve](#reporting-the-income-sleeve)). A deposit checks, in order, that the note has not matured (`Matured`), that deposits are not waiting (`HedgePaused_`) and, on a `Protected` note, that the reserve pool passes its price check, and then that the cap, if any, has room (`CapExceeded`). `maxDeposit()` returns zero after maturity and while deposits wait, `type(uint256).max` for a note with no cap, and the room under the cap otherwise. Withdrawals never check the pause. ## The payoff at maturity The chart draws both payoffs per unit deposited, against `s`, the underlying's price at maturity as a multiple of its price at deposit. (An interactive payoff chart is on the web page.) Both curves value the LP sleeve as `√s`, what a full-range position is worth after a price move of `s`. ```text income = sleeve × (√s + feeYield) + (1 − sleeve) × min(s, 1.5) protected = sleeve + (1 − sleeve) × √s ``` In `Income`, the long stops gaining above `1.5x` (`PAYOFF_CAP_MULT_X18`); that cap is the price of the fee income. In `Protected`, the first term does not depend on `s` at all, which is where the floor comes from. The contract's `payoffCurve(spotMultiplierX18)` computes the same formulas as `packages/core/src/payoff.ts` with `feeYield` pinned to zero, because fees already sit in the LP sleeve's share price. The reserve sleeve is USDC, which pays no yield, so the `Protected` floor is the sleeve itself on any date. `contracts/fixtures/payoff.json` pins eight points of each curve for comparing the two. For an 80 / 20 Income note and an 85 / 15 Protected note, the contract's curve gives: | Price multiple | Income (80 / 20) | Protected (85 / 15) | | --- | --- | --- | | `0.25x` | `0.450` | `0.925` | | `0.5x` | `0.666` | `0.956` | | `1x` | `1.000` | `1.000` | | `1.5x` | `1.280` | `1.034` | | `2x` | `1.431` | `1.062` | The `Protected` floor here is `0.85`, the reserve sleeve itself. Note: The chart is a model The chart adds a `6 %` fee yield to Income, which the table leaves out. And `√s` is a full-range position, while a note's LP sleeve is usually a narrower vault. The curve is the model the contract commits to, not a forecast. ## Leaving the note You can withdraw at any time. Before maturity, `EARLY_EXIT_BPS` (`50`, `0.5 %`) goes to the `FeeRouter`, because an early exit unwinds part of a sleeve at that minute's prices and the fee keeps that cost off the holders who stay. The fee is built into the ERC-4626 views: - `previewRedeem(shares)` returns the gross value less `ceil(gross × 50 / 10 000)`. - `previewWithdraw(assets)` returns the shares for `assets + ceil(assets × 50 / 9 950)`, so `withdraw(assets)` really pays `assets` and the fee comes on top. - `maxWithdraw(owner)` is `previewRedeem` of the owner's whole balance. After maturity the fee is zero and the views say so. A partial exit pays from idle asset first, then redeems LP shares and, on a `Protected` note, sells the reserve token, each in proportion to the shortfall. The `Income` perp sleeve is off chain, so an exit larger than the rest of the note reverts `Shortfall`. If your shares are the whole supply, the note unwinds everything, takes the fee from the gross balance and pays you the rest; `redeem()` returns what was paid. ### Settling at maturity `settle()` unwinds everything once the date has passed: it redeems every LP share the note holds, sells all its reserve token under the price check and emits `Settled(assetsOut)`. Anyone can call it, once (`NotMatured` before the date, `AlreadySettled` after the first call). The note's own pause does not block it, because it prices no shares. It can still revert, for instance while the LP vault's pool or the reserve pool is off its mean, and can be retried later. After settlement the note holds only its asset, and no exit depends on the reserve pool or the LP vault again. ## The reserve pool A `Protected` note buys, sells and values its reserve token through one Uniswap pool, so that pool is treated as an oracle. Every deposit, every withdrawal while the note holds the reserve token, and every settlement first runs [`TwapGuard.check`](https://elyratrade.io/docs/vaults#the-price-check) on it: at least `10 min` of history, and spot within `3 %` of the mean. `VaultFactory` grows the pool's observation ring when the note is created. The reserve sleeve is valued at the TWAP, net of the pool fee it costs to sell, so pushing spot buys nobody a cheaper entry. Each swap's floor is `100` bps (`1 %`) under the TWAP quote, because a floor taken from a spot the caller just set bounds nothing. Once the note holds no reserve token, in practice after `settle`, the check is skipped. An `Income` note has no reserve pool. ## Reporting the Income sleeve The hedger reports the `Income` sleeve with `reportSleeve(unrealizedPnlUsd, equityUsd, asOf)`. `equityUsd` is the sleeve's excess equity, what the perp has earned on top of the collateral, because the collateral never left the note and counting it again would double it. The value is unsigned: a losing sleeve reports zero, and the loss shows up only when the collateral comes back short. The report runs the [hedged vault's](https://elyratrade.io/docs/hedged-vaults#when-deposits-wait) code, `HedgeFunding.reportSleeve`, so the hedger key moves the share price only inside the same bounds. Only the hedger may call it (`NotHedger`); `asOf` must be after the last report and not in the future (`StaleReport`); and reports come at least 5 minutes apart in block time (`ReportTooSoon`). The note keeps two figures: the equity as reported, always stored, and the equity it believes. ```text collateral = the note's idle asset, in USD through assetUsdFeed anchor = the believed equity at the first report of each hour step = (anchor + collateral) × maxEquityJumpBps / 10 000 believed = reported, clamped to anchor ± step, and to SLEEVE_CEILING_BPS (5 000) of collateral ``` The collateral in the band is what lets an excess equity of zero grow, and a drop to zero land: from the ceiling, in at most four hours. The ceiling is the upside the `1.5x` payoff cap leaves the long. `HedgePaused("jump")` or `HedgePaused("ceiling")` marks the two figures parting, `HedgeResumed()` their meeting again, and `HedgeBelieved(equityUsd, anchorUsd)` records each believed figure. Exits value the sleeve at the lower of the two figures, and at zero once the last report is older than `maxHedgeAge` or the feed does not answer, so a stale or inflated report cannot be cashed out. Deposits wait (`paused()`, `HedgePaused_` on `deposit` and `mint`) while the two figures differ, while the report is stale and while the feed is silent for a sleeve worth more than zero. Withdrawals and redeems never wait. A note never reported on is not paused and counts no sleeve; one whose last report said zero still goes stale. The note has no funder and no owner, so there is no `setHedger` and no `acceptReport`: its hedger is fixed at creation. On a `Protected` note the call reverts `BadSleeve`, so the hedger key holds no pause over it. The equity converts to the asset through `assetUsdFeed`, Elyra's price feed for the asset, or one for one when the feed is unset for a 6-decimal USD asset such as USDC; a bad or stale feed values the sleeve at zero. ## What "protected" does not cover Warning: The floor is arithmetic, not a promise The floor assumes the reserve sleeve can be sold for what the reserve token is worth, that its pool has depth on the day, and that the token holds its value. Nobody underwrites any of that. The 1 % floor bounds each sale; it does not promise the sale clears. The price check that protects a sale from manipulation also stops it, and every exit with it, while the pool is off its mean. The floor also leaves out the LP sleeve, which falls with `√s`. And the note is measured in its own asset, so it is protected in that asset's terms, not necessarily in dollars. ## Reference ### Settings Parameters: StructuredVault.Init - set once by VaultFactory.createStructuredVault - `asset` (allowed: the LP vault asset): Must equal lpVault.asset(). - `mode` (allowed: Income or Protected): Which second sleeve the note runs. - `sleeveBps` (allowed: 1 - 9999 bps): Share of each deposit for the mode’s own sleeve: the LP vault for Income, the reserve token for Protected. - `maturity` (allowed: in the future unix s): After it: no deposits, no fee, settle allowed. - `lpVault` (allowed: LPVault or HedgedLPVault): The LP sleeve. - `reserve token / pool` (allowed: token / asset-reserve pool): Protected only. - `assetUsdFeed` (allowed: Elyra's feed or zero): Converts reported sleeve equity; zero means 1:1 for a USD asset. - `hedger` (allowed: address): The only caller of reportSleeve. - `cap` (allowed: asset units, or type(uint256).max): Deposit cap. Cannot change. 0 for an Income note. - `maxHedgeAge` (allowed: uint32 seconds; default: 1 h): Report age after which exits value the sleeve at zero and deposits wait. - `maxEquityJumpBps` (allowed: uint16 bps; default: 1500): The band each hour's believed equity moves in, in bps of the anchor plus the collateral. `sleeveConfig()` returns `(maxAge, maxJumpBps, reportWindow, minReportInterval)`: the staleness bound, the band, the hour the anchor rolls over and the 5 minutes between reports. `sleeveState()` returns `(unrealizedPnlUsd, equityUsd, asOf, isPaused, reportedEquityUsd, anchorUsd, anchorAt)`, with `equityUsd` the believed figure. `SLEEVE_CEILING_BPS` (5 000) is a constant. ### Reverts and events | Revert | Raised by | Meaning | | --- | --- | --- | | `Matured` | `initialize`, `deposit`, `mint` | A maturity not in the future, or a deposit on or after the date. | | `HedgePaused_` | `deposit`, `mint` | Deposits wait: the reported and believed sleeve figures differ, the report is stale or the feed is silent. | | `CapExceeded`, `ZeroShares` | `deposit`, `mint` | Over the cap, or no shares to mint. | | `Shortfall` | `withdraw`, `redeem` | The on-chain sleeves cannot raise the amount. | | `NotMatured`, `AlreadySettled` | `settle` | Before the date, or a second call. | | `NotHedger`, `StaleReport` | `reportSleeve` | Wrong caller, or an `asOf` in the future or not after the last report. | | `ReportTooSoon` | `reportSleeve` | Less than 5 minutes of block time since the last report. | | `BadSleeve` | `initialize`, `reportSleeve` | A `sleeveBps` of 0 or 10 000 and up, or a report on a Protected note. | | `NotAsset`, `AlreadyInitialized` | `initialize` | The LP vault or reserve pool does not match the asset, or a second initialisation. | | `TwapWindowTooShort`, `PriceDeviation` | Protected entry, exit, `settle` | The reserve pool failed its price check. | Events: `CapUpdated(cap)` once, `SleeveReported(unrealizedPnlUsd, equityUsd, asOf)` with the figure as reported, `HedgeBelieved(equityUsd, anchorUsd)` with the figure believed, `HedgePaused(reason)` and `HedgeResumed()` (the hedged vault's signatures, so the indexer tracks every vault's pause from one pair), `Settled(assetsOut)`, and ERC-4626 `Deposit` and `Withdraw`, which reports the net paid. The factory's `VaultCreated` has `kind` `2` and the reserve pool as `pool`, zero for an Income note. Where it lives: - `contracts/src/StructuredVault.sol`: _deposit, _withdraw, _raise, settle, reportSleeve, payoffCurve, _requireOpen - `contracts/src/libraries/HedgeFunding.sol`: reportSleeve, the band, the ceiling and what exits and deposits count - `packages/core/src/payoff.ts`: incomePayoff, protectedPayoff and the full-range approximation - `contracts/fixtures/payoff.json`: eight pinned points per curve - `contracts/script/ElyraWiring.sol`: the note splits, term and caps - `apps/web/components/docs/PayoffDemo.tsx`: the chart in this chapter - `apps/web/lib/earn/view.ts`: payoffPointsFor, withdrawFeeNote, countdown - `contracts/test/StructuredVault.t.sol`: both splits, the report bounds, the reserve guard, the fee before and after maturity, settle --- # Elyra pools Source: https://elyratrade.io/docs/pools · Pools DAMM, DLMM and stock pools: how each prices a swap, what it charges, and how bin orders rest. Elyra pools are the venue Elyra runs itself on Elysium. DAMM pools and stock pools are Uniswap v4 pools behind an Elyra hook, on the official Uniswap v4 deployment; DLMM pairs keep liquidity in fixed-price bins. Anyone can open a pool or provide to one, and how a swap is routed across them is in [Swaps and routing](https://elyratrade.io/docs/swaps). In brief: - Every swap fee is split: 2 000 bps of it (20 %, `ProtocolConfig.protocolFeeShareBps`) goes to the `FeeCollector`, the rest to liquidity providers. The owner can raise the share to 5 000 bps. - A DAMM fee is a 5-100 bps base, plus a surcharge for recent price movement, capped at 500 bps outside an anti-snipe window. - A stock pool must end each swap inside a band around Elyra's keeper-updated price feed, ± 200 bps while the market is open and ± 50 bps otherwise at deploy, unless the swap moved the price toward the feed price. - Only you can take your liquidity out. The venue pause stops swaps and deposits, never a withdrawal. - A DLMM limit order must be executed once the price has crossed its bin, or it trades back. ## Choosing a pool type | Pool | Price moves | Fee per swap | Good for | | --- | --- | --- | --- | | DAMM | along v4 ticks | base fee, optional anti-snipe schedule, volatility surcharge | new tokens, volatile pairs | | DLMM | bin to bin, fixed inside a bin | bin-step preset plus a volatility term | shaped liquidity, limit orders | | Stock | v4 ticks inside a feed-price band | set by the market session | EQX stock tokens | Each is opened in one permissionless transaction from the create form on the Pools page: `DammHook.createPool`, `DlmmFactory.createPair` or `StockHook.createPool`. ## Where each swap fee goes A hook works out the total fee, gives the LP part to the pool as that swap's LP fee, and charges the protocol part on the input token: in `beforeSwap` for exact-input swaps, in `afterSwap` for exact-output ones. It is paid straight to the `FeeCollector`, or held as an ERC-6909 claim that anyone can `sweep` there when the `PoolManager` is short of that token mid-swap. A DLMM pair charges its fee in each bin it crosses, sends the protocol share to the `FeeCollector` at the end of the swap and leaves the rest in the bins. The share is read on every swap. What the `FeeCollector` does with it is in [Buyback and burn](https://elyratrade.io/docs/protocol). ## DAMM pools The fee in pips (100 pips = 1 bp) has three parts: 1. **Schedule.** `baseFeeBps`, or during an anti-snipe window a fee that falls in a straight line from `snipeStartFeeBps` to the base over `snipeSeconds`. 2. **Surcharge.** `variableFeeControl × vol² / 100 000`, where `vol` adds up the ticks recent swaps moved the price and decays to zero over 600 s. At a control of 10 000, 100 ticks of movement adds 10 bps. 3. **Cap.** 500 bps, or the schedule itself while it is higher. `currentFee(id)` returns the LP part and the total right now. `createPool(key, sqrtPriceX96, params)` needs the dynamic-fee flag and the `DammHook` in the key; the form offers tick spacings 10, 60 and 200. Launched tokens use the same pools, see [Launch a token](https://elyratrade.io/docs/launch). Parameters: DammHook.createPool parameters - `baseFeeBps` (allowed: 5 - 100 bps; default: 30 in the form): The fee outside any anti-snipe window. - `snipeStartFeeBps` (allowed: base - 5 000 bps; default: 2 000 in the form): Where the window starts. Ignored when snipeSeconds is 0. - `snipeSeconds` (allowed: 0 - 3 600 s; default: off, or 600): Length of the window. 0 means none. - `variableFeeControl` (allowed: uint32; default: 10 000 in the form): Scales the surcharge. 0 switches it off. ## DLMM pairs Bin `id` trades at `(1 + binStep / 10 000)^(id − 2^23)` of token Y per token X, in raw units. Inside a bin the price is constant, so a swap fills at exactly that price until the bin is empty, then moves on to the next bin with liquidity. Diagram: Bins on either side of the active one. Token X sits in the active bin and above it, token Y in the active bin and below it. A deposit spreads across a range of bins in one of three shapes; a limit order sits in a single bin past the active one. `createPair(tokenX, tokenY, binStep, activeId)` makes one pair per token pair and bin step, ERC-20 only (use WHYPE for HYPE). A pair copies its bin step's fee preset when it is created: | Bin step (bps) | 1 | 5 | 10 | 25 | 50 | 100 | | --- | --- | --- | --- | --- | --- | --- | | Base fee (bps) | 2 | 5 | 10 | 20 | 40 | 80 | A variable fee grows with the square of how far, in bins, the price has recently travelled. With the default presets it tops out near 1 %, and the pair caps the total at 10 %. ### Providing to a pair `DlmmPositionNFT.mint` gives you one ERC-721 over a range of bins, with a weight per bin. The pool page builds the weights from a shape: **Spot** spreads evenly, **Curve** concentrates near the active bin, **Bid-Ask** weights the edges to buy dips and sell rallies. The deposit is guarded: it reverts if the active bin has moved more than `ceil(50 / binStep)` bins (at least 1), if less than 99.5 % of what you typed lands, or after the deadline. A deposit into the active bin with a different X/Y mix pays the swap fee on the part that amounts to a swap. Fees accrue into the bins. `decrease` withdraws a share of every bin and `burn` all of it; both take minimum amounts and never check the pause. ## Stock pools A stock pool pairs an `AssetRegistry` asset, an EQX stock token bridged from HyperEVM with 8 decimals, with USDC (priced at $1), native HYPE or WHYPE. Elysium has no third-party oracle network, so every price the registry reads comes from Elyra's own feed: an AggregatorV3-compatible contract per asset that Elyra's feed keeper, a key of its own, updates. Each push moves the price at most 10 %, comes at least 60 s after the last and stays within 15 % of the price that stood at the start of the hour, so the key moves a feed at most 15 % an hour; a larger genuine gap is written by the owner (`setAnswer`). The registry calls a stock's feed stale an hour after its last push while the session is open (`heartbeat`) and four days after it while closed (`closedHeartbeat`), so the close stands over a weekend unpushed and the feed reads stale at the open until the first session price lands. A quote's feed (HYPE/USD) goes stale an hour after its last push, at any time. Only the EQX addresses the registry lists count; other tokens with stock names do not. `createPool(key, 0)` starts the pool at the feed price. Before every swap the hook reads the session's fee and band; these are the deploy values, tunable per asset by the owner up to a 1 000 bps fee: | Session | When | Fee | Band | | --- | --- | --- | --- | | Open | Monday to Friday, 13:30-20:00 UTC, except holidays | 30 bps | ± 200 bps | | Closed | any other time | 150 bps | ± 50 bps | | Stale | the asset's feed is older than its bound for the session (1 h open, 4 days closed), or the quote's is older than 1 h | 500 bps | ± 50 bps | The owner shifts the hours for daylight saving and marks holidays. After a swap the price must sit inside the band, or be strictly closer to the feed price than before, so anyone can pull a drifted pool back. While the feed is stale only such toward-feed swaps pass (`PriceOutOfBand`, `StaleAwayFromOracle`). `oracleState(id)` returns what the Stocks page shows. ## Limit orders in a bin `DlmmLimitOrders.place(pair, id, sellX, amount, to, deadline)` rests your tokens in one bin past the active one: X above it to sell, Y below it to buy, `WrongSide` otherwise. Orders in the same bin and side share a batch. As the price moves through the bin the order fills at that bin's exact price and earns swap fees. Once the price has crossed the whole bin, anyone may `execute` the batch. Elyra's limit-order bot executes every batch `readyBooks()` lists, and `claim` executes a filled batch itself. Before execution, `cancel` returns whatever the bin holds for you. The contract has no owner and no fee, takes and returns HYPE for a WHYPE side, and only `place` needs the venue unpaused. Uniswap range orders are a separate product, see [Limit orders](https://elyratrade.io/docs/range-orders). Warning: Execute a filled order promptly A filled batch still sits in the bin. If the price crosses back before it is executed, the order trades back into the token you started with. The bot acts on its next tick and retries a failed batch after 60 s; you can call `execute` yourself. ## Risks - Liquidity is exposed to the pair's price, and bins or ranges the price has left earn nothing. - Outside the session a stock's feed price stops moving, so a pool can sit far from where the stock reopens. - The `ProtocolConfig` owner can pause swaps and deposits, raise the protocol share, change presets for new pairs and change a stock's feed, fees, band and hours. It cannot move liquidity; see [Security model](https://elyratrade.io/docs/security). - The feed is as current as Elyra's feed keeper keeps it. A late update widens the gap between pool and stock until it lands, and a feed past its age bound (1 h in session, 4 days closed) switches the pool to its stale fee and band, at the open too until the first session price lands. A wrong push moves a feed at most 15 % an hour. ## Reference | Error | When | | --- | --- | | `OnlyViaCreatePool`, `NotDynamicFee`, `WrongHook` | a hooked pool initialised outside `createPool`, or a key with the wrong fee or hook | | `BadParams` | a DAMM parameter out of range | | `Paused`, `DlmmPair__Paused` | a swap or deposit while the venue is paused | | `NotRegisteredPair` | a stock pool for an asset or quote the registry does not list | | `DlmmFactory__BinStepNotAllowed`, `DlmmFactory__PairExists` | no preset for the bin step, or the pair exists | | `DlmmPair__OutOfLiquidity` | a swap that runs out of bins | | `DlmmPair__ZeroShares` | a bin in the deposit range would get nothing | | `DlmmPositionNFT__ActiveIdSlippage`, `DlmmPositionNFT__AmountSlippage` | the deposit guard | | `DlmmLimitOrders__NotFilled`, `DlmmLimitOrders__AlreadyExecuted` | an execute before the bin is crossed, a cancel after execution | Where it lives: - `contracts/src/venue/hooks/ElyraHookBase.sol`: the fee split, the protocol charge, sweep - `contracts/src/venue/hooks/DammHook.sol`: createPool, the schedule, the surcharge and the cap - `contracts/src/venue/hooks/StockHook.sol`: the feed start price, the band and the toward-feed rule - `contracts/src/venue/core/AssetRegistry.sol`: assets, quotes, feeds, the open and closed heartbeats, sessions and riskParams - `contracts/src/oracle/PushFeed.sol`: the feed keeper bounds, the hourly window and setAnswer - `contracts/src/venue/core/ProtocolConfig.sol`: the protocol share, the fee collector, the pause - `contracts/src/venue/dlmm/DlmmFactory.sol`: createPair and the presets - `contracts/src/venue/dlmm/DlmmPair.sol`: bins, swap, mint, burn, _feeRate - `contracts/src/venue/dlmm/DlmmPositionNFT.sol`: the position NFT and its deposit guard - `contracts/src/venue/periphery/DlmmLimitOrders.sol`: place, execute, claim, cancel - `contracts/script/venue/VenueWiring.sol`: deploy-time stock fees and bands - `packages/core/src/dlmm.ts`: bin prices, shapes and their weights --- # One-token deposits Source: https://elyratrade.io/docs/zap · Pools Enter a range with a single token: the swap it makes for you, the checks on it, and the refund. A concentrated position needs both tokens of a pair, in a ratio set by where the price sits inside your range. A one-token deposit does the balancing for you. You send one token or HYPE, and Elyra's zap contract sells the share your range does not want on the same pool, mints the position to your wallet and sends back whatever is left, all in one transaction. You reach it from the Liquidity mode of the ticket on the Trade page; it works with Uniswap v3 pools (`ElyraZapV3`) and Uniswap v4 pools (`ElyraZapV4`). In brief: - The zap charges 25 bps of what you send, in that token. The pool's own fee applies to the part that is swapped. - One slippage figure (default 100 bps) limits both the swap's output and how far the mint may stray from the balanced amounts. A separate floor, `minLiquidity`, is the least liquidity you accept. - Everything is priced at the pool's spot price, not a TWAP. The app will not build the transaction until the pool's price agrees with the quoted price within your slippage. - Leftovers go back to the wallet that paid, in the same transaction. The contract keeps no balance between calls and has no owner, admin or upgrade path. - A large deposit into a narrow range can revert at the default slippage. Widen the range, deposit less, or raise the slippage. ## One transaction, start to finish You choose the token, the amount and a range. The app turns the range into two ticks, shows the expected split and sends `zapMint`. The contract then runs these steps in order and reverts at the first one that fails, so a failed deposit costs gas and nothing else. 1. Check the request: A passed `deadline` is `Deadline`, a zero `amountIn` is `ZeroAmount`, and a `tickLower` that is not below `tickUpper` is `BadRange`. On v3 the pool is looked up with `factory.getPool(token0, token1, fee)`, in either token order; no pool is `NoPool`. 2. Take the input: An ERC-20 is pulled with `transferFrom`, so the zap needs an approval first; the app asks for exactly the amount. On v3, HYPE must arrive as `msg.value` equal to `amountIn` and is wrapped to WHYPE, which must be one of the pool's tokens. A token outside the pool, or HYPE sent alongside an ERC-20, is `BadTokenIn`. 3. Take the fee: `ZAP_FEE_BPS` (25) of `amountIn` goes to the `FeeRouter`, booked against your address so that a referrer you have bound earns 20 % of it. The rest is what gets deposited. 4. Size the swap: `ZapMath` reads the price from `slot0`, decides which token the range has too much of and how much of it to sell. If the answer is zero, the swap is skipped. 5. Swap on the same pool: One `exactInputSingle` on the pool you are entering, with a minimum output `maxSlippageBps` below the spot quote. The router's allowance is set to the exact amount and cleared straight after. 6. Mint to you: `npm.mint` offers the balanced amounts, accepts as little as `maxSlippageBps` below each, and makes `recipient` the owner of the new NFT. 7. Check the result: Less liquidity than `minLiquidity` is `Slippage`. 8. Return the rest: The contract reads its own balance of both tokens and sends all of it to `msg.sender`. On v3, if you paid in HYPE, the WHYPE side is unwrapped first; a wallet that refuses HYPE gets `NativeTransferFailed`. Last, `ZapMint` is emitted. Diagram: A one-token deposit, step by step. Everything happens in one transaction, and any revert undoes all of it. The swap and the mint are each checked against your slippage figure, and the result against minLiquidity. `ElyraZapV3.zapIncrease` adds to a v3 position you already hold by the same steps. It reads the pool and the ticks from the position itself, and only the owner, the address approved for that NFT, or an operator may call it (`NotOwner` otherwise). The app does not use it today. ## How the swap is sized Two cases need no search. If your range sits wholly above the price, the position holds only token0, so all token1 is sold; if it sits wholly below, the position holds only token1, so all token0 is sold. When the price is inside the range, the position needs both. Selling more of the excess token lowers the liquidity that leg can support and raises what the other leg can support, and the mint gets the smaller of the two, so the best amount is where they meet. `ZapMath.optimalSwapAmountFrom` finds it with a binary search of 32 halvings (`ITERATIONS`), which pins the amount to better than one part in four billion. The search assumes the whole swap fills at the current price, less the pool fee: `amount × (1 − fee) × price`. A real swap moves the price, so it returns slightly less, the two legs end up slightly out of balance, and the mint leaves a remainder behind. That remainder is the refund in the last step; it comes back in whichever token it sits in and is not swapped again. The Liquidity mode shows its expected size as a share of your input. `previewZap` is a view that returns the exact swap amount `zapMint` would use against the current pool state, with the holdings the model expects after it. The app computes the same split locally with `zapPreview` from `@elyra/core`, which is tested against fixtures generated from the Solidity library (`contracts/fixtures/zap.json`). ## Picking a range The contract only sees two ticks. The shapes in the Liquidity mode come from `@elyra/core` (`shapes.ts`) and are turned into ticks before anything is signed: | Shape | Band around the current price | | --- | --- | | `SPOT` | 5 % below to 5 % above | | `CURVE` | 25 % below to 25 % above | | `WIDE` | 50 % below to 50 % above | | Custom | the prices you type or drag | For a preset, each edge becomes a tick with `ln(1 ± pct) / ln 1.0001` and is rounded outward to the pool's tick spacing, down for the lower tick and up for the upper, so the band covers at least what the preset promises. Ticks are logarithmic, so ±5 % is about 488 ticks up and 513 down. Custom prices snap to the nearest usable tick instead. Either way the range keeps at least one spacing of width. Diagram: From a shape to two ticks. A preset is a band around the current tick. For a stock token it doubles while the NYSE is closed, then each edge is rounded outward to the pool spacing. Custom prices snap to the nearest tick. The contract receives only the two ticks. For an EQX stock token, presets double both edges (`AFTER_HOURS_MULT` = 2) while the NYSE is closed: outside 09:30 to 16:00 New York time on weekdays, after 13:00 on early-close days, and on the exchange holidays listed for 2026 and 2027. The panel then reads "Doubled while the NYSE is closed.", and the terminal's market bar shows "NYSE is shut · ranges doubled until" the next open. The stock token keeps trading on chain while its reference price stands still, then jumps at the next open; a band sized for the trading day would be left behind. Custom ranges are never widened. ## The three checks on your deposit `maxSlippageBps` drives two of the three checks, and they measure different things. - **Swap output.** The router refuses to fill below the spot quote less `maxSlippageBps`. This bounds what your own swap loses to price impact. On v3 it surfaces as the router's "Too little received", on v4 as `Slippage`. - **Mint amounts.** On v3 the mint must take at least the balanced amounts less `maxSlippageBps`; the position manager reverts with "Price slippage check" otherwise. On v4 the same figure caps what the mint may take (see below). This measures how far the holdings sit from the ratio the range wants after the swap has moved the price, and it tightens as the range narrows. - **Liquidity floor.** `minLiquidity` is what the whole deposit must produce. The app sets it to the previewed liquidity less your slippage. Like the contract, the preview takes the 25 bps fee off your input before it splits it, so the whole margin is left for the price moving. Both zaps tie the mint check to the swap figure. A large deposit into a narrow range near the edge of the price can therefore move the price far enough that the mint check fails at 1 %. If that happens, widen the range, deposit less or raise the slippage. Elyra's vaults, which mint into narrow ranges for you, keep a separate mint tolerance of 500 bps (`MINT_RATIO_TOLERANCE_BPS`). Both zaps refuse a slippage above 5 000 bps (`MAX_SLIPPAGE_BPS`) with `SlippageTooHigh`, so no call can switch the two checks off. In the app the default is 100 bps (`DEFAULT_SLIPPAGE_BPS.zap`) with presets of 50, 100 and 200. Above 500 bps (`MAX_SLIPPAGE_WITHOUT_ACK_BPS`) you must acknowledge the risk before the button unlocks. The app sets the deadline 600 s ahead. Warning: Spot price only The zap has no TWAP guard. Its swap and mint checks are computed from the pool's `slot0` at the moment your transaction runs, and someone may have moved that price; only `minLiquidity` is fixed when you sign. Before it builds the transaction, the Liquidity mode reads the pool's own `slot0` and refuses while it differs from the quoted price by more than your slippage (`poolWriteBlock` in `lib/trade/poolState.ts`), so a pool that is already off is caught before your wallet opens. If you call the contract directly, derive `minLiquidity` from a price you trust. [Position automation](https://elyratrade.io/docs/keeper), which moves other people's funds, does run behind a TWAP guard. ## Cost You pay 25 bps of the input, in the input token, and nothing on the way out. The `FeeRouter` passes 20 % of it to your referrer if you have bound a code; the rest goes to the `FeeCollector`, which turns it into HYPE for the $ELYRA buyback (see [Fees and referrals](https://elyratrade.io/docs/fees)). The pool charges its usual fee on the swapped part only: on a 0.30 % pool, a deposit that swaps half its input pays about 0.15 % of the input to the pool. ## On Uniswap v4 `ElyraZapV4.zapMint` gives the same result through v4's plumbing: one `PoolManager` for every pool, swaps inside an `unlock` callback, and a `PositionManager` that pulls ERC-20s through Permit2. Diagram: The v4 path: unlock, then one batch. On v4 the swap happens inside the pool manager's unlock callback, and the mint is a single PositionManager batch: MINT_POSITION and SETTLE_PAIR, plus SWEEP when one side is native HYPE. Dashed: the standing Permit2 approvals the batch draws on. - **The pool** is named by its full `PoolKey` (currencies, fee, tick spacing, hooks), and `hookData` is passed to the hooks on both the swap and the mint. The zap does not look the pool up; a key for a pool that does not exist fails inside Uniswap. - **HYPE** is never wrapped. It is accepted only when one side of the pool is native HYPE, and its fee goes through `feeRouter.takeNative`. - **The fee the model uses** comes from `slot0` when the pool has a dynamic fee, and from the key otherwise. - **The swap** runs inside `poolManager.unlock`. The callback only answers the pool manager (`NotPoolManager`), sells exact input at the widest price limit, and reverts `Slippage` if the output is below the minimum. - **The mint** is a `MINT_POSITION` then `SETTLE_PAIR` batch, plus `SWEEP` when one side is native so unspent HYPE comes back. v4 mints a liquidity figure against maximum amounts, so the tolerance works upward: each maximum is the amount that liquidity needs plus `maxSlippageBps` and 1 wei, never more than the contract holds. Holdings that support no liquidity revert `Slippage`. - **Approvals.** `approveOnce(token)` sets a standing ERC-20 approval to Permit2 and a Permit2 allowance to the position manager. Anyone may call it, and calling it twice changes nothing. A standing approval reaches nothing here because the contract never holds a balance between calls. The v3 zap sets every allowance per call and clears it afterwards. - **No top-up.** There is no `zapIncrease` on v4. The contract's empty balance is checked by invariant tests: `invariant_zapHoldsNothing` and `invariant_zapKeepsNoStandingApprovals` for v3, `invariant_zapV4HoldsNothing` for v4. ## Reference ### Call parameters Parameters: ZapMintParams (ElyraZapV3.zapMint) - `tokenIn` (allowed: token0, token1 or address(0)): The token you send. address(0) is HYPE, wrapped to WHYPE on the way in. - `amountIn` (allowed: above 0 wei of tokenIn): Before the fee. Must equal msg.value when paying in HYPE. - `token0, token1` (allowed: the pool tokens, any order): With fee, find the pool through the factory. - `fee` (allowed: 100 · 500 · 3000 · 10000 hundredths of a bip): The pool fee tier, also paid on the swap. - `tickLower, tickUpper` (allowed: lower below upper, on the spacing ticks): The range. Ticks off the spacing are rejected by the position manager. - `minLiquidity` (allowed: 0 or more liquidity; default: preview less slippage): The least liquidity the mint may produce. - `maxSlippageBps` (allowed: 0 - 10 000 bps; default: 100): Bound on the swap output and on the mint amounts. 10 000 turns both off. - `deadline` (allowed: unix seconds; default: now + 600): Latest block time; also passed to the position manager. - `recipient` (allowed: any address): Owner of the new NFT. Leftovers go to msg.sender, not here. `ZapIncreaseParams` keeps only what the position does not already fix: `tokenId`, `tokenIn`, `amountIn`, `minLiquidity`, `maxSlippageBps`, `deadline`. `ZapMintV4Params` replaces `token0`, `token1` and `fee` with `key` (the `PoolKey`) and adds `hookData`. ### Reverts | Revert | Cause | | --- | --- | | `Deadline` | The block is later than `deadline`. | | `ZeroAmount` | `amountIn` is zero, or HYPE was chosen and `msg.value` differs from `amountIn`. | | `BadRange` | `tickLower` is not below `tickUpper`. | | `NoPool` | v3: no pool for the pair and fee. | | `BadTokenIn` | `tokenIn` is not a pool token, or HYPE came with an ERC-20 deposit. | | `Slippage` | Less liquidity than `minLiquidity`. On v4 also a swap below its minimum, or holdings that support no liquidity. | | `NotOwner` | v3 `zapIncrease` from an address that is not the owner, approved or an operator. | | `NativeTransferFailed` | Your wallet refused the HYPE refund. | | `NotPoolManager` | v4: the unlock callback was called by anything but the pool manager. | Two more come from Uniswap: the router's "Too little received" when the swap check fails, and the position manager's "Price slippage check" when the mint check fails. The app simulates every write before it opens your wallet, so a deposit that would revert normally stops there, at no cost. ### Emitted events `ZapMint(recipient, tokenId, liquidity, amount0, amount1, feePaid)` on v3 and `ZapMintV4` with the same fields on v4; `ZapIncrease(tokenId, liquidity, amount0, amount1, feePaid)` for a top-up. `amount0` and `amount1` are what the mint took, not what you sent, and `feePaid` is the 25 bps in the input token. The indexer does not watch the zap contracts. A zapped position reaches Portfolio through Uniswap's own position events, like any other position. Where it lives: - `contracts/src/ElyraZapV3.sol`: zapMint, zapIncrease, previewZap, the intake and the refund - `contracts/src/ElyraZapV4.sol`: zapMint, approveOnce, unlockCallback and the PositionManager batch - `contracts/src/libraries/ZapExec.sol`: balance, balanceAndMint, balanceAndIncrease and floorBps: the swap and mint checks - `contracts/src/libraries/ZapMath.sol`: optimalSwapAmountFrom, the 32-step search and quoteAtSpot - `packages/core/src/zapMath.ts`: zapPreview, the TypeScript port the app previews with - `packages/core/src/shapes.ts`: SHAPE_PCT, rangeForPct and the after-hours widening - `packages/core/src/slippage.ts`: DEFAULT_SLIPPAGE_BPS, MAX_SLIPPAGE_WITHOUT_ACK_BPS, minOut - `apps/web/lib/trade/provide.ts`: rangeForProvide, rangeFromPrices and providePreview - `contracts/test/invariants/ZapHoldsNothing.t.sol`: the v3 holds-nothing and no-standing-approvals invariants - `contracts/test/invariants/ZapV4HoldsNothing.t.sol`: the v4 holds-nothing invariant --- # Position automation Source: https://elyratrade.io/docs/keeper · Pools Let anyone harvest or re-centre your position under limits only you set, for a bounty you choose. A concentrated position earns only while the price is inside its range, and its fees sit in the position until someone collects them. `PositionKeeper` lets anyone do both chores on a Uniswap v3 position you own: `harvest` collects the fees, and `rebalance` moves the position to a fresh range around the current price. You set the rules and the reward for whoever does the work; the NFT never leaves your wallet. You enrol a position from Portfolio. In brief: - The NFT stays in your wallet. The keeper acts through an operator approval you can revoke at any time, and a rebalance mints the new position straight to you. The contract has no owner, admin or upgrade path. - Every cut comes from earned fees: 10 % to the protocol and your chosen bounty (at most 300 bps) to the caller. Principal is never cut. - A rebalance runs only when spot is within 3 % of the 30-minute TWAP, and only if the round trip keeps your value within your slippage, measured at that TWAP. After a sharp move it can wait up to half an hour. - If the NFT changes hands, the enrolment stops working and every action reverts. A new owner enrols again. - A narrow width with a tight slippage may fail to mint, and then the rebalance reverts. ## Enrolling a position 1. Approve the keeper: Call `setApprovalForAll(positionKeeper, true)` on the Uniswap v3 position manager. This operator approval covers every v3 position you own, not just the one you enrol; the keeper only touches enrolled ids. Approving a single NFT is not enough: `enroll` checks for the operator approval and reverts `NotApproved` without it. 2. Enrol with a policy: `enroll(tokenId, policy)` from the NFT's owner (`NotOwner` otherwise). The policy is validated, the enrolment records you as owner and starts its clock, so the first action can come no sooner than `minInterval` later. Enrolling an id again replaces its enrolment and restarts the clock. 3. Change or stop: `updatePolicy` swaps the rules without resetting the clock. `unenroll` stops all actions at once. Both are owner-only. Revoking the operator approval also stops the keeper, with a less readable revert. On Portfolio, the Automate drawer offers both steps and skips the first when the approval exists; Harvest, Re-centre now and Stop keeper buttons sit beside your positions. Between calls the keeper holds no NFT and no tokens, and it pays only the enrolment's owner, the caller and the `FeeRouter`. ## Your rules The `Policy` struct is the same one Elyra's vaults run under, and `@elyra/core` mirrors it field for field in `policy.ts`. Parameters: Policy, with the Automate drawer's defaults - `widthTicks` (allowed: above 0, a multiple of the pool tick spacing ticks; default: 1200): Total width of the range a rebalance mints. Presets: 1000, 4500 and 8100 for SPOT, CURVE and WIDE, rounded to the nearest multiple of the spacing. - `hysteresisTicks` (allowed: 0 or more ticks; default: 120): How far beyond the range edge the tick must be before a rebalance is allowed. - `minInterval` (allowed: 0 or more seconds; default: 3600): Time since enrolment or the last action before the next one. - `maxSlippageBps` (allowed: 0 - 9 999 (app: 1 - 500) bps; default: 100): Bounds the swap, the mint ratio and the rebalance round trip. - `compound` (allowed: true · false; default: true): Harvest puts your share back into the position, or pays it to you. - `bountyBps` (allowed: 0 - 300 bps of fees collected; default: 50): Paid to whoever calls harvest or rebalance. `enroll` and `updatePolicy` reject a bounty above `MAX_BOUNTY_BPS` (300), a slippage of 10 000 or more, negative hysteresis, and a width that is zero, negative or off the pool's spacing, all as `BadPolicy`. The spacing comes from the position's own pool, so the Automate drawer rounds each preset to the nearest multiple of it: SPOT becomes 1020 on a 0.30 % pool (spacing 60), CURVE and WIDE become 4600 and 8200 on a 1 % pool (spacing 200). A width you type off the grid is flagged before you sign. Hysteresis keeps a position that hovers on its edge from being rebalanced again and again, each time paying a bounty and a swap. Nothing but `minInterval` stops a caller from harvesting crumbs repeatedly to collect bounties. The contract will harvest a single wei once the interval is up, so choose an interval that makes each harvest worth having. ## What every action checks first `harvest` and `rebalance` share three gates. The enrolment must be active (`NotEnrolled`), `minInterval` must have passed (`TooSoon`), and the position's current `ownerOf` must still be the address that enrolled it (`OwnerChanged`). Diagram: Checks before a keeper action. Both actions pass the same three gates. A harvest then splits the collected fees. A rebalance checks the TWAP before unwinding, swaps under the router bound, and compares value at the TWAP before and after. Two views answer the same questions without gas. `shouldHarvest` adds "are there any uncollected fees", including fees already owed to the position. `shouldRebalance` adds non-zero liquidity, a tick outside the range by the hysteresis, and a passing TWAP check, so a bot is never offered a rebalance the guard would refuse. ## Collecting fees `harvest` moves the clock first, then collects every fee the position has earned and none of its liquidity. Each token is split on its own: - 10 % (`PROTOCOL_FEE_BPS` = 1000) to the `FeeRouter`, booked to you so that your referrer earns 20 % of it; - `bountyBps` to the caller; - the rest is yours. With `compound` on, your share is swapped to the range's ratio on the same pool and added back with `increaseLiquidity` (`ZapExec.balanceAndIncrease`); whatever the ratio could not take is sent to you. With it off, your share is sent to you as collected. `Harvested` reports the totals before the split, the two bounties and whether it compounded. Diagram: Where harvested fees go. Each cut is a share of the fees collected, never of the position. What is left goes back into the position or to the owner, as the policy says. Compounding is bounded only by `maxSlippageBps`, on the swap and on the add. A harvest has no TWAP check: one interval's fees are at stake, and a guard that refused on every real move would cost more than it saved. ## Re-centring a position 1. Confirm it is out of range: The tick must be below `tickLower − hysteresisTicks` or at or above `tickUpper + hysteresisTicks` (`Ranges.outOfRange`), or `InRange`. The upper test includes equality because a Uniswap range stops short of `tickUpper`. 2. Check the price: `TwapGuard.check`: spot within 300 bps of the TWAP, or `PriceDeviation`; at least 10 minutes of oracle history, or `TwapWindowTooShort`. The TWAP is kept for the value check. 3. Unwind: All liquidity is removed, everything collected and the old NFT burned. The fee portion is split exactly as in a harvest; the principal is not. What remains is valued in token1 at the TWAP. 4. New range: `Ranges.centred` puts the lower edge about half the width below the current tick, on the spacing, and the upper edge exactly `widthTicks` above it, so the price always sits inside. Both edges stay within the widest ticks the spacing allows. 5. Swap and mint to you: `ZapExec.balanceAndMint` sells the excess side on the same pool and mints the new position with you as owner. Anything left over is sent to you. 6. Value after: The minted amounts plus what was sent back, valued at the same TWAP, must be at least the value before less `maxSlippageBps`. Otherwise the whole transaction reverts with `Slippage`, unwind included. 7. Move the enrolment: Your policy is copied to the new token id with a fresh clock and the old enrolment is deleted. Your operator approval already covers the new NFT. `Rebalanced` names the old id, the new id, the caller and the new ticks. ## Price protection on a rebalance Rebalancing hands a stranger a swap of your principal. Three checks stand between that and a bad price. **Before anything moves**, the TWAP guard refuses while spot is more than 3 % from the mean price over the last 30 minutes, or over the history there is if that is shorter (`TWAP_WINDOW`, `MAX_TWAP_DEVIATION_BPS`). Without it, someone could push the pool, knock your position out of range and rebalance it at the price they created. The guard also needs at least 10 minutes of history (`MIN_TWAP_WINDOW`). A fresh pool's oracle keeps a single observation that every new block overwrites, so its "average" would just be the latest swap. Anyone can deepen it with Uniswap's `increaseObservationCardinalityNext`; 900 slots (`MIN_OBS_CARDINALITY`) always reach back 15 minutes, because a pool writes at most one observation a second. Elyra's vault factory does this for its vault pools; the keeper cannot, because it does not know which pools you will enrol. **During the swap**, the router refuses to fill below the spot quote less `maxSlippageBps`, which bounds the swap's own price impact. **After the mint**, the value check compares the round trip at the TWAP, not at spot. Valuing at spot would use the very price the swap filled at, so a manipulated spot would look fine. Inside the 3 % band a wrong spot can still cost you up to half the gap: the tests move spot about 2.7 % above the mean and show a loss near 1.35 % that only a TWAP valuation sees. The same check also covers rebalances that needed no swap, or that minted far less than they were offered. The price of this is delay: after a genuine move, spot runs ahead of the 30-minute mean, so a position can take up to half an hour to qualify, and `shouldRebalance` says no until then. Warning: Narrow widths and tight slippage The keeper also uses `maxSlippageBps` as the mint's ratio tolerance, as the [one-token deposit](https://elyratrade.io/docs/zap) does. A narrow range may not mint inside a tight tolerance (the tests note that a 400-tick range cannot mint inside 1 %), and then every rebalance reverts. Widen `widthTicks` or raise `maxSlippageBps`, knowing that a higher slippage also loosens the swap and value checks. ## If you sell the position An enrolment pays the address that created it. If you transfer an enrolled NFT without unenrolling, and the new owner has also approved the keeper, a harvest would send their fees to you and a rebalance would mint their whole position to you. So both actions compare the live `ownerOf` with the enrolment and revert `OwnerChanged` on a mismatch, and both views return false. The new owner enrols the position again to resume. ## Who calls the keeper Anyone can. In practice Elyra's keeper bot does. Every minute by default it reads `shouldHarvest` and `shouldRebalance` for every active enrolment in one Multicall3 batch. It values the bounty as `bountyBps` of the position's uncollected fees in USD, converts that to wei at the HYPE price, and sends only when the bounty is at least three times the estimated gas (`GAS_BOUNTY_MULTIPLE`). A bounty it cannot price is skipped, not sent blind; the fees stay in the position. After a success it leaves that action alone for 5 minutes; after a skip or a failure, for 15 (see [Indexer, API and bots](https://elyratrade.io/docs/offchain)). ## Reference ### Reverts | Revert | Cause | | --- | --- | | `NotOwner` | `enroll` by anyone but the NFT's owner; `updatePolicy` or `unenroll` by anyone but the enrolment's owner. | | `NotApproved` | `enroll` without `setApprovalForAll(keeper, true)`. | | `BadPolicy` | Bounty above 300, slippage of 10 000 or more, negative hysteresis, or a width that is not a positive multiple of the spacing. | | `NotEnrolled` | Any action, `updatePolicy` or `unenroll` on an inactive enrolment. | | `TooSoon` | `minInterval` has not passed. | | `OwnerChanged` | The NFT's current owner is not the address that enrolled it. | | `InRange` | `rebalance` while the tick is inside the range widened by the hysteresis. | | `TwapWindowTooShort` | `rebalance` while the pool has less than 10 minutes of oracle history. | | `PriceDeviation` | `rebalance` while spot is more than 300 bps from the TWAP. | | `Slippage` | The rebalance round trip lost more than `maxSlippageBps` at the TWAP. | A swap or mint that misses its bound reverts inside Uniswap instead, as "Too little received" or "Price slippage check". ### Emitted events | Event | Emitted by | Carries | | --- | --- | --- | | `Enrolled` | `enroll`, `updatePolicy` | `tokenId`, `owner`, `policy` | | `Unenrolled` | `unenroll` | `tokenId` | | `Harvested` | `harvest` | `tokenId`, `keeper`, `fees0`, `fees1` (before the split), `bounty0`, `bounty1`, `compounded` | | `Rebalanced` | `rebalance` | `oldTokenId`, `newTokenId`, `keeper`, `tickLower`, `tickUpper` | The indexer stores them in `keeperEnrollment` and `keeperAction`, which feed the enrolments shown on Portfolio and the bot's list of positions to check. Where it lives: - `contracts/src/PositionKeeper.sol`: enroll, updatePolicy, unenroll, harvest, rebalance and the two should views - `contracts/src/libraries/Policy.sol`: the Policy struct shared with the vaults - `contracts/src/libraries/Ranges.sol`: centred and outOfRange - `contracts/src/libraries/TwapGuard.sol`: the 30-minute window, the 10-minute minimum, the 300 bps band - `contracts/src/libraries/ZapExec.sol`: balanceAndIncrease and balanceAndMint, with the swap and mint bounds - `contracts/test/PositionKeeper.t.sol`: the split, the interval, the hysteresis, the TWAP cases and OwnerChanged - `packages/core/src/policy.ts`: the mirrored Policy the app uses - `apps/web/app/[lang]/(app)/portfolio/EnrollDrawer.tsx`: approval then enroll, with DEFAULT_POLICY from lib/portfolio/view.ts - `apps/api/src/bots/keeper.ts`: sweepEnrollments: the views in one batch and the bounty in wei - `apps/api/src/bots/chain.ts`: GAS_BOUNTY_MULTIPLE and the skip rule --- # Launch a token Source: https://elyratrade.io/docs/launch · Launch A token and its locked pool in one transaction, and pooled buying before launch. The Launch a token tab on `/launch` creates a new ERC-20 together with its own Elyra pool in one transaction, so no one can hold or trade the token before its market exists. If you would rather gather buyers first, a launch vault collects HYPE ahead of time and buys at launch for everyone at one price. Launches use Elyra's own launch pools only. In brief: - One call to `LaunchPools.launch` deploys a fixed-supply token (no owner, no mint, no transfer tax), creates its HYPE/token DAMM pool and seeds part of the supply into it, one-sided. - The seeded liquidity is locked for good. Its LP fees go to a fee recipient, the creator at first: anyone can trigger a payout to the recipient, and only the recipient can hand the right on. - Every launch has an anti-snipe window: the fee starts at up to 5,000 bps and falls linearly to the base fee over up to 3,600 s. - A buy inside the launch transaction gets the LP part of its fee back. Only the protocol share stays charged, 20 % of the fee by default, so a 2,500 bps start fee costs a launch buyer 500 bps. - A launch vault has no owner and charges no fee. If nobody launches within 3 days after deposits close, every depositor can take the whole deposit back. ## What one launch does You choose a name, a symbol, a supply, a start price and a fee schedule, and can attach HYPE to buy at launch. `LaunchPools.launch(p)` then does all of this in one transaction: 1. Check: The parameters must pass `preview(p)` (see Reference). The form runs the same checks before you sign. 2. Deploy the token: A `LaunchToken`: a plain 18-decimal ERC-20 whose whole supply is minted once. No owner, no further minting, no fee or limit on transfers, no address treated differently. 3. Create and seed the pool: A DAMM pool of native HYPE against the token, tick spacing 60, opened at your start price. The seed is one range from the lowest usable tick up to that price, so it holds only the token and sells it to buyers at every higher price. 4. Buy, if you sent HYPE: The HYPE buys the token as the pool's first swap, in the same transaction, so nobody can trade ahead of it. 5. Hand out the rest: Tokens bought and any HYPE paid back go to you. The supply the pool did not take goes to the creator you named. Diagram: A launch, direct or through a vault. Left: one transaction. Right: a vault gathers HYPE first, and its launch() calls the same function with the whole balance as the first buy, so every depositor pays one price. The token's address, and with it the pool id, is unknown until the launch lands: it is deployed with CREATE2 under a salt of the caller, the launch count and the block number. The pool manager accepts any address as a currency, so a predictable address would let someone create the pool first and block the launch. If a same-block front-run still takes it, the launch reverts `LaunchPools__PoolTaken` and works from the next block. A launch cannot go through while the venue is paused, because the pool's hook refuses new liquidity and swaps until it resumes. The pool's tick counts tokens per HYPE; the form works in HYPE per token. You type a start price or a starting market cap in HYPE, and the form rounds it to the nearest multiple of 60 ticks. | Field | Form default | Decides | | --- | --- | --- | | Supply | 1,000,000,000 tokens | the whole supply, minted once | | Seed | 100 % of supply | how much the pool can sell; the rest goes to the creator | | Start | a market cap in HYPE | the price of the first token sold | | Base fee | 100 bps | the fee after the anti-snipe window | | Anti-snipe | 2,500 bps over 600 s | the fee at the first second, and how long it takes to fall to the base | | Volatility control | 10,000 | the size of the volatility surcharge; 0 turns it off | ## The anti-snipe fee and a launch buy A DAMM fee is a schedule plus a surcharge. During the anti-snipe window the schedule falls in a straight line from the start fee to the base fee. The surcharge grows with recent tick movement and fades over 10 min; outside the window the total is capped at 500 bps. [Elyra pools](https://elyratrade.io/docs/pools) covers DAMM pricing in full. Each swap fee has two parts. The protocol share, `protocolFeeShareBps` of the fee (20 % at deploy, at most 50 %), comes off the input and goes to the fee collector, which funds [buyback and burn](https://elyratrade.io/docs/protocol). The LP part goes to the liquidity the swap trades against. A buy inside the launch transaction pays the full start fee, because no time has passed. But the launch position is then the pool's only liquidity, so the whole LP part is its own: `LaunchPools` collects it right after the swap and pays it back to the buyer with the tokens. Only the protocol share stays charged. With the form's defaults that is 500 bps of the buy. The form quotes your buy this way before you sign. ## Fees from the launch position `LaunchPools` itself holds the seeded position and has no function that removes it, no owner and no upgrade path. It can only collect the position's LP fees: - `collectFees(id)` is open to anyone and pays both currencies straight to the launch's fee recipient, even while the venue is paused. - `setFeeRecipient(id, to)` lets the current recipient, and only them, hand the fees to another address. - `pendingFees(id)` shows what a collect would pay now. The recipient starts as the creator. The tab lists, among the latest 200 launches, those whose fees go to your wallet, with a collect button. ## Pooled buying with a launch vault A launch vault lets a group buy at launch without racing each other: everyone's HYPE goes into one first buy, so every depositor pays the same average price. 1. Open: `LaunchVault.open(p, depositEnd)` checks the launch parameters as `preview` does and stores them for good. `depositEnd` must be in the future and at most 7 days away; the form defaults to 24 h. 2. Deposit: Until `depositEnd` anyone can deposit HYPE and withdraw any part of their own deposit. 3. Launch: From `depositEnd` until 3 days after, anyone can call `launch(id)`, which launches with the vault's whole balance as the first buy. 4. Claim, or refund: After a launch, each depositor claims a share of the tokens and of the HYPE paid back, in proportion to their deposit and rounded down. If nobody launched in time, for example because the venue stayed paused, each depositor refunds the whole deposit. The vault takes nothing. The unseeded supply and the launch position's fees go to the creator named in the parameters, which the opener chooses. A depositor's one cost is the protocol share of the start fee on the vault's buy, which the vault drawer prints before you deposit. The buy has no price limit, so the more HYPE the vault holds, the higher up the curve it buys. ## Reference ### Launch checks Parameters: LaunchParams, as preview checks them - `name / symbol` (allowed: 1 to 64 / 1 to 16 bytes): LaunchPools__BadName - `supply` (allowed: 1 wei to 1e33 wei): at most 10^15 whole tokens; LaunchPools__BadSupply - `seedAmount` (allowed: 1 wei to supply): LaunchPools__BadSeed, also when it rounds to zero liquidity - `creator` (allowed: non-zero): gets the unseeded supply and the fee right - `startTick` (allowed: above −887,220, up to 887,220): a multiple of 60; LaunchPools__BadTick - `baseFeeBps` (allowed: 5 to 100 bps): LaunchPools__BadFees for any fee field - `snipeStartFeeBps` (allowed: above base, up to 5,000 bps): the anti-snipe window is required - `snipeSeconds` (allowed: 1 to 3,600 s): linear decay to the base fee - `variableFeeControl` (allowed: 0 to 2^32 − 1): 0 turns the surcharge off ### Reverts | Error | When | | --- | --- | | `LaunchPools__Bad*`, `__ZeroAddress` | a parameter out of range, in `preview`, `launch` or `LaunchVault.open` | | `LaunchPools__PoolTaken` | the pool was created earlier in the same block; retry | | `LaunchPools__NotFeeRecipient` | `setFeeRecipient` from anyone but the current recipient | | `LaunchVault__BadWindow` | `depositEnd` in the past or more than 7 days ahead | | `LaunchVault__DepositsClosed` / `DepositsOpen` | a deposit or withdrawal after `depositEnd`; a launch before it | | `LaunchVault__LaunchExpired` / `AlreadyLaunched` | a launch after the 3-day window, or a second one | | `LaunchVault__NotLaunched` / `NotRefundable` | a claim before the launch; a refund before expiry or after a launch | | `LaunchVault__NothingToClaim` | no deposit, or already claimed or refunded | `Launched` records each launch (token, creator, amounts seeded and bought, HYPE spent after the payback); `FeesCollected` and `FeeRecipientSet` track the fee right. The vault emits `VaultOpened`, `Deposited`, `Withdrawn`, `VaultLaunched`, `Claimed` and `Refunded`. The app finds launches through `getLaunches` and these events, never in the deployment manifest, since a launch token's address is not known in advance. Where it lives: - `contracts/src/venue/launch/LaunchPools.sol`: launch, preview, the launch position and its fees - `contracts/src/venue/launch/LaunchToken.sol`: the fixed-supply token - `contracts/src/venue/launch/LaunchVault.sol`: open, deposit, withdraw, launch, claim, refund - `contracts/src/venue/hooks/DammHook.sol`: the fee schedule, its bounds and createPool - `apps/web/lib/amm/launch.ts`: startTickFor, quoteFirstBuy, launchProblem, vaultStatus --- # Graduation and pre-market perps Source: https://elyratrade.io/docs/graduation · Launch How a token earns a managed vault after three days and real depth, and perps on a virtual AMM for tokens no venue lists. A token that already trades can get two more things on Elyra: a managed vault over its deepest pool, and a perpetual market before any order book lists it. `LaunchPipeline` deploys the vault once the token has aged and its pools have held real depth. `PreMarketPerp` runs the perp on a virtual curve, where the contract's own USDC is the only thing that can pay a winner. Both live on the Graduation tab of `/launch`: the graduation queue next to a Start a clock panel, and the pre-market markets next to a List this token panel. Neither contract has an owner, an allow-list or an undo. In brief: - A token graduates when two on-chain facts hold: at least 3 days since someone called `track`, and at least `10 ether` of liquidity, averaged over the last 30 min and summed across its token/WHYPE pools. - Seasoned (pool at least 3 days old, market cap above $1,000,000, at least 100 trades in 24 h) is a screener label computed off chain. It tells the graduator bot which tokens to work on. No contract reads it. - A pre-market perp takes USDC, isolated per position, at 1x to 3x. It charges 30 bps of notional on entry and on exit, and caps open interest at 5x the market's virtual depth. - A winning close can be paid less than it earned: first cut by any outstanding bad debt, then limited to the USDC the contract holds free, with the rest owed to you as a deferred claim. - `Graduated` and `MarketCreated` mean someone paid gas. They are not endorsements. ## Graduation Graduation is two permissionless calls with a wait between them. The graduator bot makes both for Seasoned tokens; the Graduation tab lets you make them for any token. `track(token)` needs a token/WHYPE pool on one of the four Uniswap v3 fee tiers (100, 500, 3,000 and 10,000). It grows each such pool's observation ring to 900 slots, so its depth can be averaged later, and stores the block time in `firstSeen[token]`. An empty pool still counts; depth is tested only at graduation. `graduate(token)` then runs the gate: 1. No vault yet: A token graduates once. There is no way to remove its vault. 2. Old enough: At least 3 days (`MIN_AGE`) since `firstSeen`. A token nobody tracked is too young forever, so the first call for a new token is always `track`. 3. Deep enough, over time: For each tier, the pool's harmonic-mean in-range liquidity over the last 30 min, or over as much history as its ring holds. A pool with less than 10 min of history counts as zero. The sum must reach `MIN_LIQUIDITY`. 4. Vault deployed: On the single deepest pool by the same measure, because a vault holds one position. `VaultFactory.createV3Vault` deploys a clone with no admin and `Graduated` is emitted. Diagram: Tracking and graduating a token. Anyone can make both calls. Red chips are reverts, in the order the contract checks them; the dashed arrow is the 3-day wait between the calls. Depth is averaged over 30 minutes, and market cap and trade count are never read. The average is what makes the depth test hard to fake. Liquidity added in the graduation block has existed for no time, so it weighs nothing: a flash-loaned position can neither clear the threshold nor choose the pool. `MIN_LIQUIDITY` is a constructor value and the deploy sets `10 ether`, roughly 10 WHYPE of full-range depth for an 18-decimal token near parity. It is a floor against dust pools, not a valuation. `canGraduate(token)` runs the same tests as a view and returns the selector of the error `graduate` would raise; the Graduation tab turns it into a short reason on the token's row. The tab's button state is an estimate from indexer data. The contract re-checks everything when you send. ### The vault you get Every graduation produces the configuration the deploy uses for its own plain vaults. Only the pool, the range snap and the name differ. Parameters: What _initFor passes to createV3Vault - `asset` (allowed: WHYPE): deposits and withdrawals are in WHYPE - `widthTicks` (allowed: curveWidth(spacing) ticks; default: 4,440 at spacing 60): ±25 % (2,231 ticks a side), floored to the spacing - `hysteresisTicks` (allowed: 10 × spacing ticks; default: 600 at spacing 60): how far price must leave the range before a rebalance counts - `minInterval` (allowed: 6 h): minimum gap between two keeper actions - `maxSlippageBps` (allowed: 100 bps): swap bound on every rebalance - `compound / bountyBps` (allowed: true / 50): fees go back into the range; a harvest pays its caller 50 bps of the fees - `cap` (allowed: none; default: type(uint256).max): no deposit cap, fixed once the vault exists - `name / symbol` (allowed: "Elyra SYM Vault" / "elySYM"; default: SYM = TOKEN): from symbol(); a token that reverts or answers empty gets TOKEN The vault starts empty and appears on Earn. How it prices deposits, harvests and rebalances is in [Vaults](https://elyratrade.io/docs/vaults); the bots that service it are in [Position automation](https://elyratrade.io/docs/keeper). ## The Seasoned screen The screener's Seasoned label is `isEstablished` in `@elyra/core`: pool age of at least 3 days, market cap strictly above $1,000,000, and at least 100 trades. The indexer applies it per pool, counting trades over the trailing 24 h and refreshing the flag on the first swap of each hour. A token with no known supply has no market cap and is never Seasoned. `LaunchPipeline` can check only age, and its clock starts at `track`, not at pool creation. Market cap and trade count need an indexer, so the Graduation tab shows them next to each tracked token as checks that pass or fail. The graduator bot (`apps/api/src/bots/graduator.ts`) joins the two. Each tick (60 s by default) it takes the indexer's Seasoned pools, keeps the side that is not WHYPE or USDC, skips graduated tokens and reads `firstSeen` for the rest in one batch. It sends `track` when `firstSeen` is zero, `graduate` once 3 days have passed, and nothing in between. Neither call pays a bounty, so each is sent only if it simulates. `ThinPool` and `TooYoung` are the usual answer and are logged as quiet skips; a token whose attempt failed is left alone for 15 min. The tracked list comes from `GET /launch`: the indexer's `graduation` table plus Seasoned token/WHYPE pools nobody has tracked yet, up to 50 rows, joined with live reads of `firstSeen` and `MIN_LIQUIDITY`. See [Indexer, API and bots](https://elyratrade.io/docs/offchain). ## Pre-market perps `PreMarketPerp` is a constant-product virtual AMM. It has no liquidity providers and no counterparty: the curve quotes both sides, and the contract's USDC balance pays every winner. Four rules bound what that can cost. Leverage stops at 3x and open interest at 5x the advertised depth. A third of every fee goes to an insurance fund. Bad debt the fund cannot cover is paid by the next profitable closers. And no payout ever touches another open position's collateral or the insurance fund. ### Two prices The **index** is the token's dollar price from the spot market: the mean tick of the market's token/WHYPE pool over 30 min (less if the ring holds less history), converted to WHYPE per token, times HYPE/USD from Elyra's keeper-updated price feed, in 6 decimals. It is unreadable when the ring holds less than 10 min of history, the pool cannot be observed, or the feed reverts, answers zero or less, or has not updated for 1 h. The **mark** is the curve's own price, `quoteReserve × 1e18 / baseReserve`. | Use | Price | | --- | --- | | Every fill, open or close | the curve, so the mark moves with each trade | | Funding | the gap between mark and index, capped at ±1 % an hour | | Liquidation | below maintenance at the mark and at the index; none while the index is unreadable | No trade on this contract moves the index, so pushing the mark cannot liquidate anyone by itself. A manipulated index can push funding to its cap and can liquidate only a position the mark already shows below maintenance. A feed outage pauses liquidations; `close` keeps working. Diagram: Two prices and funding. The index comes from the spot pool and the keeper-pushed HYPE/USD feed; the mark is the curve. Funding follows the gap between them, capped at ±1 % an hour. A liquidation must hold at both prices, so one trade on the curve cannot trigger it. ### Opening a market `createMarket(token, fee, virtualLiquidityUsd)` is open to anyone. It needs a depth of at least 10,000 USDC, a token/WHYPE pool on that fee tier whose ring has 900 slots and at least 10 min of history, and a readable index. `prepare(token, fee)` grows the ring as a separate, idempotent transaction anyone can pay for. The curve is seeded at the index, with the depth as its quote reserve, and its `k` is fixed for life. The reserves are virtual and the creator pays nothing for them, which is why open interest (the sum of open positions' entry notionals) is capped at 5x the depth: a market can never owe more than a known multiple of what it advertised. ### A position from open to close `open(token, isLong, collateral, leverageX, limitPrice)` takes a whole-number leverage from 1 to 3 and accrues funding first. The notional, collateral times leverage, must fit under the open interest cap. The entry fee, 30 bps of the notional, comes out of your collateral before the position exists, and only the remainder is stored. The curve then fills the full notional; a short also cannot reach the curve's quote reserve. The average fill price must not cross `limitPrice` (a maximum for a long, a minimum for a short, zero for none). Because the fee comes out first, a 3x open is about 3.03x on the collateral that remains. The trade box on the Graduation tab mirrors that arithmetic and prints a liquidation price from the 6.25 % maintenance margin, without funding: a 3x long is liquidatable roughly 28.6 % below entry, a 3x short roughly 25.2 % above. Its default limit is the mark plus or minus 1 % against you. `close(id, limitPrice)` is for the position's trader only. It accrues funding, pushes the position back through the curve, realises PnL net of funding and checks the exit price against your limit. The exit fee is 30 bps of the exit notional, capped at what the position is worth and zero when it is worth nothing, since a fee charged into bad debt would only deepen the hole. `liquidate(id)` is open to anyone once equity (collateral plus unrealised PnL minus funding owed) is at or below zero, or below 6.25 % of notional, at both prices. It unwinds and charges the exit fee like `close`. The caller gets 1 % of the remaining margin, capped at the USDC the contract holds free, and the insurance fund gets the rest. The liquidated trader keeps nothing: with no order book, liquidating has to be worth someone's gas. Diagram: A position on the vAMM. The entry fee leaves the collateral before the position exists. A close is paid only from USDC the contract holds free, and the rest is owed as a deferred claim. Red chips are reverts. ### Hourly funding `pokeFunding(token)` is public and idempotent, and every open, close and liquidation calls it first. Once a whole hour has passed it adds `(mark − index) / index`, clamped to ±1 %, to the market's running sum once per whole hour, at the rate seen at poke time. One poke charges at most 24 hours; a longer gap is forgiven rather than billed at today's rate. If the index is unreadable it returns without moving the clock, so an outage never blocks an exit. A position owes the change in the running sum since it opened, times its entry notional: longs pay when the sum is positive (the mark has run above the index), shorts receive it. Funding settles at close. ### Bad debt and the insurance fund Every fee is split: 3,333 bps of it, about 10 bps of notional, goes to the insurance fund, and the rest to the `FeeRouter`, which credits a referrer with 20 % when there is one ([Fees and referrals](https://elyratrade.io/docs/fees)). A close or liquidation that ends below zero is bad debt. The insurance fund pays first, down to zero; anything left becomes `deficit`. Nothing is taken from anyone at that moment. Instead, the next profitable close has its profit cut by the smaller of its profit and the deficit, and the deficit shrinks by the same amount. Only profit is cut; your collateral never pays for someone else's loss. The cost lands in full on whoever closes at a profit first after the loss, until the deficit is gone. `haircutBps()` reports the deficit as a share of open collateral, a gauge of how unfunded the venue is. ### When a profit is paid late A vAMM has no auto-deleveraging, so a profit can also be paid late. The contract pays out only free USDC: its balance minus all open collateral and the insurance fund. Say a long closes at a profit while the short on the other side is still open. The short's loss is real at the mark, but its USDC is still that short's collateral. The long is paid what is free and the rest is recorded in `deferred[trader]`. Claims already recorded come first: a later close is paid only from what is free after `totalDeferred` is set aside, so USDC a realised loss frees goes to the traders already waiting. `claimDeferred()` pays as much of your claim as is free at the time, in as many calls as it takes; among waiting traders it is first come, first served. `invariant_perpCoversItsObligations` states the design in one line: the contract's USDC balance is at least `totalCollateral + insuranceFund − deficit`. The fuzzer drives four traders through random opens, closes, liquidations, claims and time jumps, and a second invariant checks that positions really do close, so the first cannot pass on an idle book. Danger: Before you open a pre-market position The index is a short TWAP of a pool that is new and thin by construction. Fills follow the curve, which anyone with USDC can move. A liquidation that arrives late is paid by the insurance fund first and then by whoever closes at a profit next, and a profit you close may be paid in part as a deferred claim. ## Reference ### Perp constants Parameters: PreMarketPerp - `MAX_LEVERAGE_X` (allowed: 1 to 3 x): whole numbers only - `MAINT_MARGIN_BPS` (allowed: 625 bps): of notional, at the mark and at the index - `TAKER_FEE_BPS` (allowed: 30 bps): of notional, on entry and on exit - `INSURANCE_SHARE_BPS` (allowed: 3,333 bps): of each fee - `LIQ_BOUNTY_BPS` (allowed: 100 bps): of the remaining margin, to the liquidator - `TWAP_WINDOW / MIN_INDEX_WINDOW` (allowed: 30 min / 10 min): index window, and the least history it accepts - `MIN_OBS_CARDINALITY` (allowed: 900): ring size a pool needs to back a market - `MIN_VIRTUAL_LIQ_USD` (allowed: 10,000 USDC): smallest market depth - `OI_MULTIPLE` (allowed: 5 x): open interest cap over depth - `FUNDING_CAP_X18 / MAX_FUNDING_HOURS` (allowed: ±1 % / 24): hourly rate cap, and the most hours one poke charges ### Reverts | Error | Raised when | | --- | --- | | `AlreadyTracked` / `AlreadyGraduated` | a second `track`, or a token that already has a vault | | `NoPool` | no token/WHYPE pool on any tier (`LaunchPipeline`) or on the given tier (`PreMarketPerp`) | | `TooYoung` | untracked, or less than 3 days since `firstSeen` | | `ThinPool` | summed time-weighted liquidity below `MIN_LIQUIDITY` | | `MarketExists` / `NoMarket` | a second market for a token, or none at all | | `LowCardinality` / `NoHistory` | the ring has under 900 slots, or under 10 min of history | | `BadOracle` | the index cannot be read | | `Leverage` / `ZeroAmount` | leverage of 0 or above 3; zero collateral or a fill that rounds to nothing | | `OiCap` | the open interest cap, or a short as large as the quote reserve | | `TooSmall` | depth under 10,000 USDC, or an entry fee that reaches the collateral | | `Slippage` | the average fill or exit price crossed `limitPrice` | | `NotOpen` / `NotTrader` / `NotLiquidatable` | a closed position, a caller who is not its trader, a position above maintenance at either price | | `NothingToClaim` | no deferred claim, or no free USDC to pay it | ### Events and indexed data `LaunchPipeline` emits `Tracked` and `Graduated`. `PreMarketPerp` emits `MarketCreated`; `Opened`, `Closed` and `Liquidated` over a position's life; `Funding` with each accrual; `InsuranceChanged` on every movement of the fund; and `Socialised` and `DeferredClaimed` for cut or delayed profits. The indexer keeps these in `graduation`, `perpMarket`, `perpPosition`, `perpGlobal` (insurance fund, deficit, total deferred) and `perpEvent`. `GET /launch` adds live mark, index, open interest and insurance reads, your positions' equity, and a `funding1h` column computed off chain from the same formula. Where it lives: - `contracts/src/LaunchPipeline.sol`: track, graduate, canGraduate, _scanOverTime, _initFor - `contracts/script/ElyraWiring.sol`: MIN_LIQUIDITY = 10 ether and the seed vault policy - `contracts/src/PreMarketPerp.sol`: createMarket, open, close, liquidate, pokeFunding, _payOut, claimDeferred - `contracts/test/invariants/PerpSolvency.t.sol`: the solvency invariant and its handler - `packages/core/src/established.ts`: isEstablished, the Seasoned test - `apps/api/src/bots/graduator.ts`: the bot that tracks and graduates - `apps/api/src/launch/build.ts`: how GET /launch joins indexer rows and chain reads - `apps/web/lib/launch/view.ts`: launchAction, establishedChecks, tradeEstimate --- # Buyback and burn Source: https://elyratrade.io/docs/protocol · Protocol Fees become HYPE, HYPE buys $ELYRA, $ELYRA is burned: each step, its guard and who can call it. Elyra has one use for its protocol revenue: buying $ELYRA and burning it. A `FeeCollector` swaps fees to HYPE, and `BuybackV2` spends the HYPE on $ELYRA and sends it to `0x…dEaD`. Every call on the way is open to anyone, and the [Protocol page](https://elyratrade.io/protocol) has a button for each. In brief: - Elyra pools send 20 % of each swap fee to the FeeCollector. Other fees pass through the FeeRouter, which first credits 20 % to the payer's referrer, if any. - Every step is a public call: `flush`, `convert`, the collector's unwrap and forward calls, `buyback`, `poke`. - One `buyback()` spends at most `maxNativePerCall` of HYPE, runs at most once a minute (`minInterval`, owner-set between 30 s and a day; ten blocks a second would otherwise mean ten buybacks a second) and pays its caller 0.5 %. - A buyback will not buy while $ELYRA trades above a 10 % band over a slow reference price. A falling price never blocks it. - $ELYRA is launched by its owner. Until BuybackV2 is configured with the token's pool, `buyback()` and `poke()` revert and converted HYPE waits in BuybackV2. ## The path of one fee A fee reaches the FeeCollector by one of two roads. An Elyra pool swap pays its protocol share straight in; every other fee is booked in the FeeRouter until someone calls `flush(token)` (see [Fees and referrals](https://elyratrade.io/docs/fees)). The FeeCollector turns what it holds into HYPE for BuybackV2, and `buyback()` spends that HYPE on $ELYRA in the HYPE/ELYRA Uniswap v4 pool, which pays the tokens directly to `0x…dEaD`. Diagram: From fee to burn. Elyra pools pay their protocol share to the FeeCollector directly. Every other fee is reported to the FeeRouter, which credits 20 % to the payer’s referrer. From the FeeCollector on, each arrow is a call anyone can make. The accent arrow is the burn. ## The protocol share of pool fees LPs keep most of an Elyra pool's swap fee. `ProtocolConfig.protocolFeeShareBps` (2000, so 20 % of the fee, at most 50 %) goes to the FeeCollector, always in the token you pay with. - DAMM and stock pools are Uniswap v4 hooks and send it with `poolManager.take`. If the PoolManager is short of that token mid-swap, the hook mints itself an ERC-6909 claim, and anyone can call the hook's `sweep(currency)` to pay it out to the FeeCollector. - DLMM pairs transfer it on every swap, and on the composition fee a deposit into the active bin pays. How each pool sets its fee is in [Elyra pools](https://elyratrade.io/docs/pools). ## Converting fees to HYPE The owner gives each fee token a route: Router hops ending in native HYPE, a cap per call, and the oracle price floor for every token the `AssetRegistry` prices (`setRoute` refuses such a route without it; only an unpriced token converts with none). Then anyone can convert. - `convert(token, 0)` converts the balance up to the cap. An explicit amount above the cap reverts `OverCap`. - With the floor on, `minNativeOut` prices the input from the `AssetRegistry` feed against the HYPE/USD feed, both Elyra's keeper-updated price feeds, and accepts at most `maxSlippageBps` (3 %) less. A stale feed reverts `StaleOracle`. - WHYPE needs no route: it is unwrapped 1:1. HYPE fees are forwarded to BuybackV2 as they are. A production deploy has no routes until the owner adds them, so a token without one waits in the FeeCollector. A local deploy seeds routes for USDC and its seeded stock token. ## Buying and burning `buyback()` takes BuybackV2's HYPE balance, including any HYPE sent with the call, up to `maxNativePerCall`. It keeps `callerRewardBps` (0.5 %) of that budget for the caller and spends the rest; a partial fill pays a proportional reward. Unspent HYPE waits for the next call. Warning: Sending your own HYPE HYPE you send with `buyback()` joins the HYPE already waiting. Anything above the per-call cap stays in BuybackV2 for later buybacks. You get it back only if the call reverts. ### The price guard $ELYRA has no external price feed, so BuybackV2 checks the pool against a reference price that follows it slowly. - The reference moves at most `driftBpsPerHour` (30 %) per hour since its last update, and at most `maxDeviationBps` (10 %) per update. With no time elapsed it cannot move, so a pump inside one block does not shift it. - `buyback()` catches the reference up, then reverts `PriceAboveBand` if $ELYRA is above the band: 10 % on the pool price ($ELYRA per HYPE), about 11.1 % on $ELYRA's HYPE price. - A cheaper $ELYRA never blocks a buyback, however old the reference. - The swap stops at the tighter of the reference band edge and 10 % above its own starting price. A reverted buyback also undoes its catch-up, so `poke()` exists to move the reference on its own. It pays nothing. The API's optional `buybackPoker` bot pokes when the reference is at least 1 % off the pool price and 600 s old. After `PriceAboveBand`: poke, wait, retry. ## Burned and circulating supply A burn is a transfer to `0x…dEaD`, so circulating supply is `totalSupply()` − `balanceOf(0x…dEaD)`, checkable by anyone on the [explorer](https://elysium.kinetiq.xyz/explorer). BuybackV2 also counts `totalNativeSpent` (in HYPE) and `totalBurned`. The indexer keeps every `Converted` and `BoughtBack` event for `GET /protocol`, and the Protocol page reads the live state on chain every 20 s. Note: Which token is $ELYRA $ELYRA is the token whose address BuybackV2 is configured with, once, through `configure`, and that the app names in one config constant. The Protocol page shows that address as soon as it is set. Anyone can launch another token called ELYRA, on the Launch page or elsewhere; Elyra marks every one of them as not the official $ELYRA. A local deploy configures a test $ELYRA in its own pool. ## What the owner controls One cold key owns `ProtocolConfig`, `FeeCollector` and `BuybackV2`; ownership changes in two steps, propose then accept. | Contract | The owner can | Limit | | --- | --- | --- | | ProtocolConfig | set the protocol share; name another FeeCollector | share at most 50 % | | ProtocolConfig | pause | stops swaps and new liquidity, never withdrawals | | FeeCollector | set or clear routes; set `maxSlippageBps`; name another buyback | slippage at most 20 % | | FeeCollector | `sweep` a token | only a token with no route, never HYPE or $ELYRA | | BuybackV2 | `configure` the pool | once | | BuybackV2 | set `maxNativePerCall`, `callerRewardBps`, `minInterval`, the guard; `resetReference()` | reward at most 5 %, interval 30 s to 1 day, band 1 to 2000 bps, drift at most 10 000 bps per hour | So the owner can redirect revenue that has not reached BuybackV2: by naming another collector or buyback, or by clearing a token's route and sweeping it. It cannot take HYPE from BuybackV2, and none of these contracts reaches a user's position or deposit. The other keys are in [Security model](https://elyratrade.io/docs/security). ## Reference ### Calls and reverts | Call | Can revert with | | --- | --- | | `FeeRouter.flush(token)` | `NothingToClaim` | | `sweep(currency)` on a hook | `NothingToSweep` | | `FeeCollector.convert(token, amount)` | `NoRoute`, `OverCap`, `StaleOracle`, `ZeroAmount`, or the Router's `TooLittleReceived` on a dust amount | | The collector's unwrap and forward calls | `ZeroAmount` | | `BuybackV2.buyback()` | `NotConfigured`, `TooSoon`, `NothingToSpend` (no HYPE, or nothing the band allows), `PriceAboveBand` | | `BuybackV2.poke()` | `NotConfigured` | ### Parameters Parameters: Deploy values - `protocolFeeShareBps` (allowed: 0 to 5000 bps of the fee; default: 2000): ProtocolConfig: Elyra pool fee share sent to the FeeCollector - `maxSlippageBps` (allowed: 0 to 2000 bps; default: 300): FeeCollector: the price floor on convert - `maxNativePerCall` (allowed: any HYPE): BuybackV2: spend per buyback, set at deploy - `callerRewardBps` (allowed: 0 to 500 bps; default: 50): BuybackV2: the caller reward - `minInterval` (allowed: 30 to 86 400 seconds; default: 60): BuybackV2: the smallest gap between two buybacks - `maxDeviationBps` (allowed: 1 to 2000 bps; default: 1000): BuybackV2: the band, and the largest step the reference takes - `driftBpsPerHour` (allowed: 0 to 10 000 bps per hour; default: 3000): BuybackV2: how fast the reference follows the pool Where it lives: - `contracts/src/venue/periphery/FeeCollector.sol`: routes, the price floor, convert, sweep - `contracts/src/venue/periphery/BuybackV2.sol`: buyback, poke, the reference and the band - `contracts/src/venue/core/ProtocolConfig.sol`: the protocol share and pause - `contracts/src/venue/hooks/ElyraHookBase.sol`: how the hooks pay their share - `contracts/script/venue/VenueWiring.sol`: deploy values and ownership - `contracts/script/venue/VenueSeed.sol`: local routes and the test $ELYRA pool - `apps/web/lib/amm/buyback.ts`: the guard reading and circulating supply on the page --- # Fees and referrals Source: https://elyratrade.io/docs/fees · Protocol What each action costs, where the money goes, the referral share, bounties and points. This chapter lists what Elyra charges, who receives it and how a referrer earns a share. Elyra charges on what you put in or what a position earns, not on what you take out, with one exception for structured notes. Bounties, which pay for public upkeep calls, come last. In brief: - A zap costs 25 bps of what you put in. A spot trade on the Trade page's Uniswap path costs 25 bps of the output. An Elyra Router swap pays only the pools' own fees. - On perps, Elyra's fee is a Hyperliquid builder fee you approve once, at most 0.1 % of notional by Hyperliquid's rule. - Managed positions pay 10 % of the swap fees they earn and nothing on principal. The only fee on principal is 50 bps for leaving a structured note before maturity. - Elyra pools send 20 % of each swap fee to the FeeCollector and leave the rest to their LPs. - If you were referred, your referrer earns 20 % of every FeeRouter fee you generate. The link is permanent. Vault and note fees never pay a referrer. - Points are an off-chain ledger. Nothing is promised about them. ## What you pay | Action | Fee | Taken from | Referrer credited | | --- | --- | --- | --- | | Swap in an Elyra pool | the pool's fee, 20 % of which is the protocol share | your input | none: the share goes straight to the FeeCollector | | Swap through the Elyra Router | no Elyra fee beyond the pools' | - | - | | Spot trade on the Uniswap path (Trade) | 25 bps | the output | the trader's, once booked (see below) | | Zap into a Uniswap range | 25 bps | the input | yours | | Keeper harvest or rebalance | 10 % | the fees collected | the position owner's | | Range order fill or cancel | 10 % | the fees the order earned | the order owner's | | LP or hedged vault harvest or rebalance | 10 % | the fees collected | none: the vault names itself | | Structured note exit before maturity | 50 bps | the gross amount withdrawn | none: the note names itself | | Pre-market perp open, close or liquidation | 30 bps | the notional | the trader's | | Perp order on Hyperliquid | Elyra's builder fee, the rate the ticket shows, never above what you approved | the trade, in USDC | the trader's, once booked (see below) | Elyra pool fees depend on the pool. A DAMM pool charges a base fee of 5 to 100 bps plus a volatility surcharge, at most 500 bps in total, and a new pool may add an anti-snipe fee that starts as high as 5000 bps and falls to the base fee within an hour. Stock pools charge 30 bps while the market is open, 150 bps while it is closed and 500 bps when the price feed is stale (deploy values; the owner can set each asset up to 1000 bps). A DLMM pair charges a base fee plus a variable fee, capped at 10 %. [Elyra pools](https://elyratrade.io/docs/pools) has the detail. Some actions pay no Elyra fee at all: a deposit into any vault, a withdrawal from an LP, hedged, DLMM or stock vault, a DLMM limit order, and a launch's pre-launch vault. Some fees are not Elyra's: Hyperliquid charges its own trading fees on every perp order, and bridging USDC between Elysium and HyperEVM costs gas on both sides. ## Fees come out of earnings When a keeper, a vault or a range order closes or re-centres a Uniswap position, the contract compares two numbers: `decreaseLiquidity` reports the principal alone, and `collect` pays out principal plus fees. The 10 % and any bounty apply only to the difference, so a position that has earned nothing pays nothing and no harvest reaches the liquidity itself. Inside one split the order is fixed: the protocol share first, then the caller's bounty, then everything left to the owner. ## How a fee is booked Every fee except the Elyra pools' protocol share passes through `FeeRouter`, a contract with no owner and two fixed addresses: the `ReferralRegistry` it reads and the treasury it pays, which is the FeeCollector. 1. The paying contract transfers the fee to the router, then reports it with `take(token, amount, user)`. A fee paid in native HYPE arrives with `takeNative(user)` instead; a v4 zap paid in HYPE uses it. 2. `take` is public, so the router checks the report against its balance. It accepts the fee only if the balance covers everything already owed plus the new amount, and reverts `FeeNotReceived` otherwise. 3. If `user` is bound to a referrer, 20 % (`REFERRAL_BPS`) is credited to that referrer and the rest to the treasury. The router emits `Taken`. 4. A referrer calls `claim(token)` to pull their own balance (the Claim buttons on the Portfolio page's Referrals tab). Anyone can call `flush(token)` to push the treasury's balance to the FeeCollector, where [buyback and burn](https://elyratrade.io/docs/protocol) takes over. Diagram: Where each fee goes. A Elyra contract transfers each fee to the FeeRouter, then reports it with take(). A report counts only if the router’s balance covers it. The user named in the report decides whose referrer earns the 20 %. Bounties go straight to the caller and never pass through the router. ### The Uniswap-path skim On the Trade page, a spot trade that goes through the Uniswap Universal Router includes a `PAY_PORTION` step that sends 25 bps of the output to the FeeRouter as a plain transfer; the minimum you receive is net of it. A transfer reports nothing by itself, so Elyra's `spotFeeBooker` bot books it with `take(token, amount, trader)`: 1. Every 5 minutes it reads, for WHYPE, USDC and each EQX stock token, the FeeRouter's balance less `accounted(token)`. When nothing is unbooked it stops there. 2. Otherwise it reads that token's transfers from the Universal Router to the FeeRouter over about the last day, and the FeeRouter's `Taken` events over the same blocks. A transfer followed by a `Taken` of the same token and amount is already booked. 3. The trader is the address that sent the transaction, and only when that transaction called the Universal Router itself. A trade sent through another contract, such as a smart-contract wallet, names nobody, and its fee stays unbooked. 4. It books a fee once it is worth more than its configured minimum (WHYPE at the HYPE price, USDC as a dollar, a stock token at its market's mark) and three times the gas of booking it, while the unbooked balance still covers it. If you were referred, your referrer is then credited 20 %, as with any FeeRouter fee, and the rest is the treasury's: the fee sweeper flushes it to the FeeCollector and converts it once the FeeCollector has a route for that token (WHYPE needs none). Until a fee is booked it is an unbooked balance that neither `claim` nor `flush` can move; `take` is public, and whoever calls it names the `user`. When the Elyra Router pays more on a live quote, the trade goes through it instead and no skim applies. A build with no FeeRouter in its manifest turns the skim off. ### Perp builder fees Hyperliquid pays builder fees to Elyra's builder account there, not on Elysium. An owner-run sweep withdraws them, brings the USDC to Elysium and books it through the FeeRouter with `take(token, amount, trader)`, one row per trader in proportion to the builder fees their fills paid, so the amounts add up to exactly what was withdrawn. From then on it is an ordinary FeeRouter fee: 20 % to the trader's referrer, the rest to the treasury. Fees wait on Hyperliquid between sweeps. ## Referrals `ReferralRegistry` holds two write-once links and has no owner. - **Your code.** On the Portfolio page's Referrals tab, register 1 to 8 letters or digits; the app upper-cases the code and stores it as `bytes8` with `register`. An address owns one code for life, and a code belongs to one address. - **Your referrer.** Opening `/ideas?ref=CODE` on this site offers a one-click `bind` if you have no referrer yet. A binding never changes, and you cannot refer yourself. - **Who counts as the user.** Each contract names the user behind a fee: the zapper, the position owner rather than the bot that harvested, the order owner rather than the keeper that filled, the trader. A vault or a note names itself and can never bind, so its fees go to the treasury in full. A vault depositor is not referred through the vault. - **Earnings.** The indexer adds each `Taken` referrer share to the referrer's per-token total, and `GET /referral/:address` prices those totals into one dollar figure and lists the tokens. The Referrals tab of the Portfolio page reads `FeeRouter.claimable(token, you)` on chain for each of those tokens, plus HYPE and every listed token, and shows a **Claim** button next to each balance. Claim sends `FeeRouter.claim(token)` from the referrer wallet: one token per transaction, paid straight to that wallet. ## Bounties A bounty pays the gas of a public call nobody else is paid to make. The contract pays it to `msg.sender` before the owner's share, and it never passes through the FeeRouter. | Call | Bounty | Paid from | | --- | --- | --- | | `PositionKeeper.harvest`, `rebalance` | the owner's `bountyBps`, at most 3 % | the fees collected, after the 10 % | | `LPVault.harvest`, `rebalance` | 0.5 % | the fees collected, after the 10 % | | `RangeOrders.fill` | 1 % | the order's output | | `PreMarketPerp.liquidate` | 1 % | the margin left after the loss and the fee; the rest goes to the insurance fund | Seed and graduated vaults write `bountyBps` 50 into their policy, matching what the vault pays. Elyra's keeper bot sends a bounty-paid call only when the bounty is at least 3 times the gas, and skips it when it cannot price the bounty. An untaken bounty costs nothing; the fees stay in the position. ## The pre-market perp fee `PreMarketPerp` charges 30 bps of the notional on open, and reverts `TooSmall` if that fee would reach the collateral. It charges again on close and on liquidation, capped at collateral plus PnL and zero when that is zero or less, so a fee never deepens bad debt. `INSURANCE_SHARE_BPS` (3333) sends one third of each fee to the insurance fund and two thirds to the FeeRouter in the trader's name. [Graduation and pre-market perps](https://elyratrade.io/docs/graduation) covers the market. ## Points Points live in the API's Postgres, not on chain: 1 point per dollar of volume, 5 per dollar of fees earned, and volume counts double for 7 days after you post an idea. Totals are recomputed from the `points_events` ledger rather than incremented. `GET /points/:address` returns the total and its parts (volume, fees, `thesisBonus`); `POST /points/recompute` rebuilds every total behind `ADMIN_SECRET`. A background job reads indexed Elyra activity every few minutes and writes it to the ledger: swaps through the Elyra Router, pre-market perp opens and voluntary closes (liquidations earn nothing) count as volume; keeper harvests, range-order fills, vault harvests (split by share) and the 20 % referral share count as fees earned. Each row's id comes from its on-chain event, so a re-read never counts twice, and amounts are priced in USD when the job reads them. Plain Uniswap fee collections are not Elyra activity and earn nothing. `rank` is your place among the stored totals. Nothing is promised about points. ## Reference ### Constants | Constant | Value | Where | | --- | --- | --- | | `ZAP_FEE_BPS` | 25 | `ElyraZapV3`, `ElyraZapV4` | | `SPOT_FEE_BPS` | 25 | `apps/web/lib/trade/spot.ts` | | `PROTOCOL_FEE_BPS` | 1000 | `PositionKeeper`, `LPVault`, `RangeOrders` | | `EARLY_EXIT_BPS` | 50 | `StructuredVault` | | `TAKER_FEE_BPS`, `INSURANCE_SHARE_BPS`, `LIQ_BOUNTY_BPS` | 30, 3333, 100 | `PreMarketPerp` | | `REFERRAL_BPS` | 2000 | `FeeRouter` | | `MAX_BOUNTY_BPS`, `HARVEST_BOUNTY_BPS`, `KEEPER_BOUNTY_BPS` | 300, 50, 100 | `PositionKeeper`, `LPVault`, `RangeOrders` | | `protocolFeeShareBps` | 2000, at most 5000 | `ProtocolConfig` | ### FeeRouter and ReferralRegistry errors | Error | When | | --- | --- | | `FeeNotReceived` | `take` with the zero address as token, or a balance that does not cover the report | | `NothingToClaim` | `claim` or `flush` with nothing owed | | `NativeTransferFailed` | the HYPE recipient refused the payment | | `ZeroCode`, `CodeTaken`, `AlreadyRegistered` | `register` with an empty code, someone else's code, or a second code | | `UnknownCode`, `SelfReferral`, `AlreadyBound` | `bind` to a code nobody owns, to your own code, or a second time | Where it lives: - `contracts/src/FeeRouter.sol`: take, takeNative, claim, flush, the balance check - `contracts/src/ReferralRegistry.sol`: register and bind - `contracts/src/PositionKeeper.sol`: fees-only split: protocol, bounty, owner - `contracts/src/LPVault.sol`: the vault as its own user - `contracts/src/RangeOrders.sol`: the 10 % on earned fees and the fill bounty - `contracts/src/PreMarketPerp.sol`: the taker fee, the insurance third, the liquidation bounty - `apps/web/lib/trade/universalRouter.ts`: the PAY_PORTION skim - `apps/api/src/bots/spotFeeBooker.ts`: books the skim for the trader - `apps/web/app/[lang]/(app)/ideas/ReferralPanel.tsx`: register, the ?ref= bind - `apps/api/src/points.ts`: the points rules - `apps/api/src/points/job.ts`: the job that writes the ledger from indexed activity - `apps/api/src/bots/chain.ts`: the bounty-to-gas rule --- # Security model Source: https://elyratrade.io/docs/security · Protocol Every key and what it can do, what each contract can and cannot do, and the price checks before funds move. This chapter lists every key that can do something the public cannot, what each contract can and cannot do, and the checks that stand between a pool price and your funds. In brief: - No contract can be upgraded, and the LP-management contracts (vaults, zaps, range orders, the keeper, the launch pipeline, the pre-market perp, the fee router) have no owner and no pause switch. - Elyra's own pools have one owner, a cold key behind `ProtocolConfig`. It can pause swaps and deposits, set the protocol share up to 50 % of the swap fee and tune stock feeds and fees. It cannot move liquidity or block a withdrawal. - Stock and HYPE prices on chain come from Elyra's own feeds, which a feed keeper key updates. That key moves prices, not funds, and each feed at most 15 % an hour. - The hedger key can move a hedged vault's share price through its reports: at most 15 % of the hedge an hour, and never past three times the margin funded. Exits count the lower of what was reported and what the vault believes, and zero on a report older than 1 h; deposits wait meanwhile, exits never do. - A hedged vault's margin sits on Hyperliquid in an account owned by that vault's funder key, which the operator holds. That key can withdraw the margin there; the vault lets at most 25 % of its on-chain assets leave at once, refilling over a day, to the funder's address only. - Perp orders are signed by agent wallets that Hyperliquid does not let withdraw or transfer. ## Who holds a key Diagram: Who can call what. Every gated call, grouped by the key that holds it; "Anyone" means permissionless. The frame on the right lists actions with no code path at all, so no key can perform them. The deploy names its roles up front, with one funder per hedged vault, and refuses to run if any of them is the deploying key, if a funder is a hot key, if the owner is a funder or a hot key, if two hedged vaults share a funder, or if two of the three hot roles share a key. The API signs each bot role with its own key and, in production, refuses a shared one. After the deploy the deploying key is an ordinary address. | Key | Kept | Holds | | --- | --- | --- | | Owner | cold | the venue's admin calls: `ProtocolConfig`, `AssetRegistry`, `FeeCollector`, `BuybackV2`, the eight price feeds, and through `ProtocolConfig` the DLMM factory and the two venue vault factories | | Hedger | hot, on the API server, its own key | hedge and sleeve reports | | Vault keeper | hot, on the API server, its own key | rebalancing the DLMM and stock vaults | | Price feed keeper | hot, on the API server, its own key | pushing stock and HYPE prices to Elyra's feeds, within their bounds | | Funder, one per hedged vault | cold, never a hot key | taking margin from its vault to its own address, within caps; naming the vault's hedger; believing a reported drop at once; and, off chain, the vault's Hyperliquid account itself, including withdrawing from it | | Builder account | owner-held | receiving Elyra's builder fees on Hyperliquid | | Deployer | used once | nothing after the hand-over | ### The venue owner The four venue contracts and the eight feeds use OpenZeppelin `Ownable2Step`: the deploy proposes the owner and the owner must call `acceptOwnership`. The owner can: - **Pause the venue** (`ProtocolConfig.setPaused`). This stops swaps and liquidity adds on DAMM and stock pools, DLMM swaps, deposits and new pairs, deposits and rebalances in the DLMM and stock vaults, and new DLMM limit orders. It never gates an exit: the hooks have no remove-liquidity callback, and `DlmmPair.burn`, the position NFT's `decrease` and `burn`, the venue vaults' `withdraw` and the limit orders' `cancel` and `claim` do not read the flag. - **Direct protocol revenue.** Set the protocol share of every swap fee, at most 5 000 bps; replace the fee collector; set the `FeeCollector`'s conversion routes, its slippage bound (at most 20 %) and where it sends HYPE; sweep tokens that have no conversion route; tune `BuybackV2`'s price guard, caller reward and interval (30 s to a day). - **Curate stock pools.** List or delist an EQX asset, choose its price feed and its heartbeats in and out of session, its fees (at most 1 000 bps) and its band, and set the session hours and holidays. - **Run the feeds.** Name each feed's keeper, set its bounds (`setBounds`: the step, the interval, the distance from the window's anchor, the window) and write an answer itself (`setAnswer`, emitting `AnswerSet`) for a genuine gap larger than the keeper may push. - **Curate the rest.** Enable DLMM bin steps and their fee presets (new pairs only), create DLMM and stock vaults, name their keeper and rebalance them itself. None of these calls can take a liquidity provider's tokens. Two of them still matter to you: a wrong feed or answer for a stock moves that pool's band, and providers would trade at it; and delisting an asset stops swaps in its pools until it is listed again. The LP-management contracts read nothing the owner controls. ### The price feed keeper Elysium has no third-party oracle network, so every feed price the contracts read comes from Elyra's own AggregatorV3-compatible feeds, updated by Elyra's feed keeper. Stock pools band their swaps around it, stock vaults centre on it, the fee collector's price floor and the pre-market perp's index use it, and a hedged vault and an Income note convert reported equity with it. The keeper key cannot move funds. Each push moves a feed at most 10 %, at least a minute after the last, and within 15 % of the answer that stood at the first push of the hour, so a wrong price moves a feed at most 15 % an hour (about 32 % where two hours meet); a genuine larger gap is the owner's `setAnswer`. A wrong price can move a stock pool's band and what feed-priced reads value; a late one ages until each reader's limit (HYPE/USD an hour after its last push, a stock an hour while its session is open and four days while it is closed) and then counts as stale, which switches stock pools to their stale fee and band and values a hedge or sleeve at zero. ### The hedger and the funder A hedged vault cannot see its Hyperliquid position, so it believes the hedger's `reportHedge(notionalUsd, unrealizedPnlUsd, equityUsd, asOf)` and adds `equityUsd` to `totalAssets()`. An `Income` note does the same with `reportSleeve`, under the same rules, with a band measured on its anchor plus its collateral and a ceiling of half that collateral; a `Protected` note refuses it. Danger: The hedger key can move the share price Reports come at least 5 minutes apart (`ReportTooSoon`). The vault keeps the figure as reported and the figure it believes: the believed equity moves at most `maxEquityJumpBps` (1 500 bps at deploy) from an anchor that rolls once an hour, so a larger move is walked in at 15 % an hour (about 32 % across one hour boundary), and it never passes three times the margin funded less the margin returned. Exits value the hedge at the lower of the two, and at zero on a report older than `maxHedgeAge` (1 h at deploy) or a silent feed; deposits wait while the two differ, the report is stale or the feed is silent. `asOf` must move forward, cannot be in the future and must come after the last `fundHedge`/`returnHedge` (`StaleReport`). What the bounds leave: a leaked hedger key can still misprice shares inside them, and the hedged vaults have no deposit cap. It cannot freeze exits. The funder replaces it with `setHedger`, and believes a real drop at once with `acceptReport`, which only ever lowers the figure. `fundHedge(assetAmount)` belongs to the funder alone. It can only send USDC to the funder's own address; it moves at most `maxFundBpsPerCall` (1 000 bps) of the vault's on-chain assets per call, out of an allowance of `maxFundBpsPerPeriod` (2 500 bps) that refills linearly over a day, both measured against the position and idle balance rather than the reported equity; it sells at a floor taken from the USDC pool's TWAP; and it is refused while deposits wait. No bot calls it. The USDC it delivers is added to the stored equity in the same transaction, and `returnHedge` (the funder again) takes the USDC it brings home off it, so margin on its way to or from Hyperliquid never drops out of the share price; the hedger reports what is still in flight (see [Margin in transit](https://elyratrade.io/docs/hedged-vaults#margin-in-transit)). Danger: The funder key holds the hedge margin Hyperliquid accounts are addresses, and only an address's own key can approve an agent wallet or withdraw. So each hedged vault's margin goes to its funder's Hyperliquid account, and the signer's agent wallet for that account trades and never withdraws. The funder key itself can withdraw whatever margin is on Hyperliquid. The bounds are the funding caps (10 % of on-chain assets per call, 25 % at once, refilling over a day), one dedicated funder per vault, and that the key is cold and held by the operator. Margin comes back as USDC the funder hands to `returnHedge`; the function can only add to the vault. The vault keeper's key may rebalance DLMM and stock vaults only when the contracts allow it: a DLMM vault once the active bin has drifted more than half its half-width, a stock vault on a session change or a large feed move and only while the pool sits near the feed price; at most every 5 minutes, and never with a swap. ## Contracts with no admin The LP-management contracts (the three vault kinds and `VaultFactory`, both zaps, `RangeOrders`, `PositionKeeper`, `LaunchPipeline`, `PreMarketPerp`, `FeeRouter` and `ReferralRegistry`) have no owner, no pause switch and no upgrade path. Every address they call (Uniswap, WHYPE, Permit2, price feeds) is a constructor immutable or, for the vault clones, written once in `initialize`. On the venue side the Router, the DLMM pairs, position NFT and limit orders, `LaunchPools` and `LaunchVault` have no owner of their own either; the pools among them follow the venue pause and protocol share described above. The vaults are EIP-1167 clones of three implementations. Each implementation locks itself in its constructor, and `VaultFactory` clones and initialises in one transaction, so no stranger can configure a fresh clone. What that leaves: - A vault pays out only to whoever redeems its shares. A vault's cap and policy are set once, at creation, and never change. - `PositionKeeper` mints a rebalanced position to its owner and pays only the owner, the caller's bounty (capped by the owner, at most `MAX_BOUNTY_BPS`, 300) and the `FeeRouter`. A position that changed hands since enrolment reverts `OwnerChanged`. - `FeeRouter.take` believes a reported fee only if the router's balance covers it (`FeeNotReceived`), and referral links are write-once. - No contract can withdraw from Hyperliquid, and neither can the signer's agent wallets. The one key that can is a hedged vault's funder, for that vault's margin (see above). - `LaunchPools` locks each launch's seed liquidity for good; only the right to its fees can change hands. Outside the Router and the hooks, functions that move tokens carry OpenZeppelin `ReentrancyGuard`. The two report functions carry it too, though they make no external call, so a report can never land in the middle of a deposit, exit or funding and move the share price under it. The Router keeps nothing between calls, and the hooks run inside the `PoolManager`'s lock. The v3 zap approves exact amounts and clears them, while the v4 zap keeps standing Permit2 approvals and never holds a balance between calls. ## Price checks Diagram: Checks in front of every value-moving path. Each row is one check: what it tests, the revert it raises, and the paths that run behind it. A path that moves value at a pool or oracle price passes at least one row; the note at the foot lists the deliberate exceptions. The threat is the same everywhere: move a pool, get Elyra to act at that price, move it back. `TwapGuard.check` is the shared answer. It reads spot and the mean tick over `TWAP_WINDOW` (30 minutes), compares them as prices, and reverts `PriceDeviation` when they are more than 300 bps apart. A new pool's observation ring holds one slot, so its "average" is the last swap; the guard therefore refuses to answer (`TwapWindowTooShort`) until the ring reaches back 10 minutes. `VaultFactory`, `LaunchPipeline.track` and `PreMarketPerp` grow each ring to 900 slots. A pool writes at most one observation a second, so 900 slots always reach back 15 minutes, over the 10-minute minimum, and no burst of swaps can shorten the window enough to stop deposits or withdrawals. Anyone can deepen a ring further. The cost is availability: on a fresh pool, deposits, withdrawals and rebalances wait until its history reaches back 10 minutes. The guard is waived three times, on purpose. A vault with no shares skips it, so the first depositor into a freshly graduated pool can get in. `harvest` skips it, since it only compounds fees under a slippage bound and blocking it would let a manipulator stop a vault being paid. A `Protected` note stops checking its reserve pool once it holds no reserve token, which is what `settle` is for. Inside the 300 bps band, more checks apply: - `PositionKeeper.rebalance` values what it unwound and what it minted at the TWAP, and reverts `Slippage` if the round trip lost more than the owner's `maxSlippageBps`. This catches what the swap floor cannot see. - Swap floors: the vaults and the keeper quote at spot after the guard; a zap quotes at spot and also enforces the `minLiquidity` the app derives from the price you saw; `fundHedge` and the reserve leg quote at the TWAP. - Mint minimums: the vaults allow 500 bps between the minted and the balanced amounts, the zaps your slippage. A zap refuses a slippage above 5 000 bps (`MAX_SLIPPAGE_BPS`, `SlippageTooHigh`), so no call can switch its floors off. - Feed reads need a positive, complete answer younger than the reader's limit. A bad read values a hedge or sleeve at zero rather than freezing exits, and makes the perp's index unreadable. - Stock pools end every swap inside their feed band or closer to the feed price, and DLMM deposits carry an active-bin and minimum-amount guard; see [Elyra pools](https://elyratrade.io/docs/pools). - Graduation measures pool depth as a 30-minute average, so liquidity added in the graduating block counts for nothing. ## The pre-market perp's balance `PreMarketPerp` has no counterparty; its USDC balance is all a winner can be paid from. Leverage is capped at 3x and a market's open interest at 5 times its virtual depth, which is at least 10 000 USDC. A third of each 30 bps taker fee feeds an insurance fund that absorbs bad debt first; what it cannot absorb becomes a deficit that the next profitable closers pay out of their profit, never their collateral. A payout never touches another position's collateral or the fund: whatever the contract cannot pay now becomes a `deferred` claim, collected with `claimDeferred`. Claims already waiting are set aside before any later close is paid; among themselves they are paid first come, first served. The index, a 30-minute TWAP times Elyra's HYPE/USD feed, drives funding, capped at 1 % per hour and at most 24 hours charged at once. A liquidation must hold at both the mark and the index, so with the index unreadable liquidations wait while `close` stays open. Details are in [Graduation and pre-market perps](https://elyratrade.io/docs/graduation). ## Off-chain keys Perp orders go through a signer service that holds a per-user agent wallet, encrypted at rest, which your wallet approves on Hyperliquid. Hyperliquid does not let an agent wallet withdraw or transfer. The signer fails closed without a current mark, refuses a signed price more than `LIMIT_PRICE_BAND_BPS` (1 000 bps by default) from it or an order above `MAX_ORDER_NOTIONAL_USD` ($250 000 by default), and gives a market order at least 100 bps of slippage while rejecting requests above 1 000 bps. Every perp write to the API carries an EIP-712 signature from your wallet, at most 300 s old and with a fresh nonce. With an opt-in trading session, a key held by one browser tab signs orders and cancels instead, under a grant your wallet signed for at most 24 h; it can never withdraw or approve anything. Elyra's builder fee is charged only up to the maximum your wallet approved. See [Perpetuals](https://elyratrade.io/docs/perps#trading-sessions). ## Limits - **Hedge margin in an operator account.** Margin outside a hedged vault depends on the funder key and on the bridge and Hyperliquid while it is there. The Income note takes no deposits: its long has no funding path on chain. - **Withdrawal size.** A hedged vault sizes exits against its on-chain holdings, so a withdrawal larger than them reverts `Shortfall` until margin comes back from Hyperliquid, which takes at least the bridge's time. - **The first depositor** into a vault with no shares prices themselves, with no TWAP check. Shares carry three more decimals than the asset (1 000 virtual shares per virtual asset unit), so donating to a near-empty vault to round the next depositor down costs about a thousand times what it can take. - **Deferred perp profits** are paid after the deficit haircut and only from realised losses. - **A frozen feed** that keeps a positive answer is believed until it passes its reader's age limit. ## Reference Parameters: Constants and deploy values - `TWAP_WINDOW` (allowed: constant; default: 30 min): Window TwapGuard averages over, when the ring allows. - `MIN_TWAP_WINDOW` (allowed: constant; default: 10 min): Shortest history TwapGuard accepts. - `MAX_TWAP_DEVIATION_BPS` (allowed: constant bps; default: 300): Spot against the mean, compared as prices. - `MIN_OBS_CARDINALITY` (allowed: constant; default: 900): Ring size the factory, the pipeline and the perp grow pools to: 15 minutes at one write a second. - `MAX_FEED_AGE` (allowed: constant; default: 1 h): Oldest HYPE/USD answer the vaults, the note and the perp accept. - `heartbeat / closedHeartbeat` (allowed: per asset, owner-set; default: 1 h / 4 days): Feed age after which a stock pool counts as stale, in and out of session. A quote has the first only. - `maxDeviationBps / minInterval` (allowed: per feed, owner-set bps; default: 1 000 / 60 s): Largest move of one push, and the least time between two. - `maxWindowMoveBps / window` (allowed: per feed, owner-set bps; default: 1 500 / 1 h): Largest distance from the window's anchor, and the window's length. - `maxHedgeAge` (allowed: per vault, fixed; default: 1 h): Report age after which a hedged vault or Income note values it at zero for exits and holds deposits. - `maxEquityJumpBps` (allowed: per vault, fixed bps; default: 1 500): Band around the hour's anchor the believed equity moves in (an Income note: of anchor plus collateral). - `MIN_REPORT_INTERVAL / REPORT_WINDOW` (allowed: constant; default: 5 min / 1 h): Least time between two reports, and how often the anchor rolls. - `VALUE_MULTIPLE / SLEEVE_CEILING_BPS` (allowed: constant; default: 3 / 5 000): Ceiling on the believed figure: times the margin funded less returned (hedged vault), bps of the collateral (Income note). - `maxFundBpsPerCall / PerPeriod` (allowed: per vault, fixed bps; default: 1 000 / 2 500): fundHedge cap per call, and the allowance that refills linearly over a day. - `cap` (allowed: per vault, fixed; default: none): Deposit limit, set once at creation. The vaults Elyra deploys have none; an Income note is created at 0. - `MAX_SLIPPAGE_BPS` (allowed: constant bps; default: 5 000): Highest maxSlippageBps a zap accepts. - `SHARE_DECIMALS_OFFSET` (allowed: constant; default: 3): Extra share decimals on the ERC-4626 vaults: 1 000 virtual shares per virtual asset unit. - `MAX_PROTOCOL_SHARE_BPS` (allowed: constant bps; default: 5 000): Highest protocol share of a swap fee the owner can set. - `MAX_BOUNTY_BPS` (allowed: constant bps; default: 300): Highest bounty a kept position can offer. Where it lives: - `contracts/src/libraries/TwapGuard.sol`: the price guard, its window and its verdicts - `contracts/src/libraries/HedgeFunding.sol`: the band, the ceilings, the funding allowance and what exits and deposits count - `contracts/src/oracle/PushFeed.sol`: the feed bounds, the window and setAnswer - `contracts/src/venue/core/ProtocolConfig.sol`: the venue owner, the pause and the protocol share - `contracts/src/venue/core/AssetRegistry.sol`: stock feeds, heartbeats, fees, bands and sessions - `contracts/src/venue/periphery/FeeCollector.sol`: the owner-set fee routes - `contracts/src/PreMarketPerp.sol`: the perp bounds, payouts and deferred claims - `contracts/script/ElyraWiring.sol`: roles, hand-over and every deploy value above - `services/signer/README.md`: the signer and its bands --- # Architecture Source: https://elyratrade.io/docs/architecture · Reference The contracts and services, which one calls which, and how a write travels from the app to the chain. This chapter is the map for engineers: every contract Elyra deploys, the programs that run around them, and the two paths data takes, a write from your wallet to a contract and a read from the chain back to a page. Every other chapter zooms into one part of it. Every name in `code` can be found with a search of the repository. In brief: - `contracts/src` holds the liquidity-management layer (position tools, vaults, launch tracking, pre-market perps, fees), and `contracts/src/venue` holds Elyra's own pools, routing and the $ELYRA buyback. One call, `ElyraWiring.deployAll`, deploys the fixed contracts; factories make the rest later: DLMM pairs, pool vaults, launch tokens and vault clones. - Your browser sends your transactions itself, through one hook (`useWrite`) that simulates each call before your wallet opens. No Elyra server sends a transaction for you. - Pages read from the API. The API reads the indexer over GraphQL, Elysium over RPC, Hyperliquid's public market data and its own database. The browser never queries the indexer. - Operator keys are named at deploy: an owner (cold, owns four venue admin contracts and Elyra's price feeds), three hot bot keys with one role each (a hedger, a vault keeper and a price feed keeper; the deploy refuses two roles on one key), and one funder per hedged vault (cold; takes that vault's margin to Hyperliquid, owns the account it lands in and names the vault's hedger). The signer also holds one Hyperliquid agent wallet per account, which can trade and cannot withdraw. - The maths every page shows is written once, in `@elyra/core`. ABIs, addresses and the deployment manifest are written once, in `@elyra/abi`. ## The map Diagram: How the pieces connect. Solid arrows are calls or transfers; dashed arrows are reads and event streams. Nothing off chain touches a contract except through the RPC: the browser sends your own transactions, the bots send theirs, and the indexer reads the logs. Hover a box to see only its links. Read it from the top. The browser, the API and its bots, the indexer and the signer sit off chain; all of them reach the contracts through Elysium's RPC, and the signer and the hedger also talk to Hyperliquid. On chain, the contracts fall into two families. The liquidity-management contracts in `contracts/src` work on top of the official Uniswap v3 and v4 deployments on Elysium. The venue in `contracts/src/venue` is Elyra's own set of pools, router and fee path. They meet at one point: `FeeRouter` collects the fees of the first family and names the venue's `FeeCollector` as its treasury, so whatever referrers do not earn joins the pools' protocol fees on the way to the $ELYRA buyback. Nothing in `contracts/src` is behind a proxy, and nothing can be upgraded. The liquidity-management contracts have no owner and no admin function. In the venue, `ProtocolConfig`, `AssetRegistry`, `FeeCollector` and `BuybackV2` are `Ownable2Step`, and so is each of Elyra's price feeds (`PushFeed`). Their owner can tune parameters, steer fees, set a feed's bounds or write its answer, and pause swaps and new liquidity. Withdrawals never check the pause. [Security model](https://elyratrade.io/docs/security) lists every power that key has. Elysium is an Arbitrum Orbit chain that settles to HyperEVM, with blocks about every 100 ms. Inside a contract, `block.number` returns the HyperEVM block number, so Elyra's contracts measure time with timestamps. ## Contracts by job Each table names who creates the contract, what it is for and what it calls. "deployAll" means the contract is deployed once by `ElyraWiring.deployAll`. "deployVenue" means the venue half of that same call. ### Position tools | Contract | Created by | What it does | Calls | | --- | --- | --- | --- | | `ElyraZapV3` | deployAll | Takes one token, skims 25 bps, swaps the excess side, then mints or tops up a v3 position. Holds nothing between calls. | NPM, SwapRouter02, `FeeRouter` | | `ElyraZapV4` | deployAll | The same over the v4 `PoolManager`, hooks included. | PoolManager, v4 PositionManager, Permit2, `FeeRouter` | | `RangeOrders` | deployAll | Holds a one-sided v3 position as a limit order that earns fees until the price crosses it. Anyone may `fill`; only the owner may `cancel`. | NPM, `FeeRouter` | | `PositionKeeper` | deployAll | Lets anyone `harvest` or `rebalance` an enrolled v3 position under the owner's policy, for a bounty of at most 300 bps. | NPM, SwapRouter02, `FeeRouter` | Details: [One-token deposits](https://elyratrade.io/docs/zap), [Limit orders](https://elyratrade.io/docs/range-orders), [Position automation](https://elyratrade.io/docs/keeper). ### Vaults | Contract | Created by | What it does | Calls | | --- | --- | --- | --- | | `VaultFactory` | deployAll | Clones the three vault implementations (EIP-1167) and initialises each clone in the same transaction. Anyone may create a vault, so the factory's list is not a recommendation. | the implementations | | `LPVault` | `VaultFactory` | ERC-4626 shares over one v3 range, priced behind a TWAP guard, harvested and rebalanced by anyone. | NPM, SwapRouter02, `FeeRouter` | | `HedgedLPVault` | `VaultFactory` | An `LPVault` whose price exposure is shorted on Hyperliquid, in its funder's account. The hedger reports the short; the funder moves margin. | USDC (through `HedgeFunding`), Elyra's price feed | | `StructuredVault` | `VaultFactory` | A dated note: an `LPVault` sleeve plus an off-chain long (`Income`) or a reserve token (`Protected`), unwound at maturity. Leaving early costs 50 bps. | its `LPVault`, the reserve pool, Elyra's price feed, `FeeRouter` | Details: [Vaults](https://elyratrade.io/docs/vaults), [Hedged vaults](https://elyratrade.io/docs/hedged-vaults), [Structured notes](https://elyratrade.io/docs/structured). ### Launch tracking and pre-market perps | Contract | Created by | What it does | Calls | | --- | --- | --- | --- | | `LaunchPipeline` | deployAll | `track` records when a token's WHYPE pool was first seen. `graduate` clones an `LPVault` over it once the token is 3 days old and its pools hold `MIN_LIQUIDITY`. | v3 factory, `VaultFactory` | | `PreMarketPerp` | deployAll | A virtual-AMM perp for tokens no venue lists: USDC margin, 3x, an index price from a 30 min v3 TWAP times Elyra's HYPE/USD feed. Anyone may open a market. | v3 pools, Elyra's price feed, `FeeRouter` | Details: [Graduation and pre-market perps](https://elyratrade.io/docs/graduation). ### Elyra pools and routing | Contract | Created by | What it does | Calls | | --- | --- | --- | --- | | `ProtocolConfig` | deployVenue | The venue's switches: pause, the protocol share of every pool fee (2 000 bps at deploy, at most 5 000) and the `FeeCollector` address. | none | | `AssetRegistry` | deployVenue | The curated list of feed-priced assets (the EQX stock tokens) and the quotes they may pair with. USDC is $1; HYPE and WHYPE use Elyra's HYPE/USD feed. | Elyra's price feeds | | `DammHook` | deployVenue, at a mined CREATE2 address | Permissionless dynamic-fee v4 pools: a 5 to 100 bps base fee, an optional anti-snipe start fee and a volatility surcharge, capped at 500 bps outside the snipe window. | PoolManager, `ProtocolConfig` | | `StockHook` | deployVenue, at a mined CREATE2 address | v4 pools for registry assets. The fee follows the market session, and a swap must end inside the feed band or move the price toward it. | PoolManager, `AssetRegistry`, `ProtocolConfig` | | `DlmmFactory`, `DlmmPair` | deployVenue; pairs by anyone | Discrete-bin pools with a fixed price per bin, one pair per token pair and bin step. | `ProtocolConfig` | | `DlmmPositionNFT` | deployVenue | ERC-721 positions over a contiguous range of bins. | `DlmmPair` | | `DlmmLimitOrders` | deployVenue | Limit orders as single-bin liquidity, batched per bin. Anyone may `execute` a filled batch. | `DlmmPair` | | `Router` | deployVenue | Exact-in, multi-hop swaps across v4 pools (Elyra hooks and others) and DLMM pairs. Holds nothing and charges nothing. | PoolManager, `DlmmPair` | Both hooks and every DLMM pair send the protocol share of each fee straight to `FeeCollector`. Details: [Elyra pools](https://elyratrade.io/docs/pools), [Swaps and routing](https://elyratrade.io/docs/swaps). ### Pool vaults and launches | Contract | Created by | What it does | Calls | | --- | --- | --- | --- | | `DlmmVaultFactory`, `DlmmVault` | deployVenue; vaults by the owner | ERC-20 shares over the bins around the active one. Only the factory's keeper (or the owner) rebalances, at most every 5 min. | `DlmmPair` | | `DlmmVaultZap` | deployVenue | One-token deposits into, and withdrawals out of, a DLMM vault. | `Router` | | `StockVaultFactory`, `StockVault` | deployVenue; vaults by the owner | Passive liquidity in one stock pool, centred on the feed price and wider while the market is closed. | PoolManager, `StockHook` | | `LaunchPools`, `LaunchToken` | deployVenue; tokens by `launch` | A fixed-supply token and its locked native-HYPE DAMM pool in one transaction, with an optional first buy. | PoolManager, `DammHook` | | `LaunchVault` | deployVenue | Pools HYPE before a launch, buys the token as the pool's first swap and shares it pro rata. | `LaunchPools` | Details: [Elyra pools](https://elyratrade.io/docs/pools), [Launch a token](https://elyratrade.io/docs/launch). ### Fees and $ELYRA | Contract | Created by | What it does | Calls | | --- | --- | --- | --- | | `FeeRouter` | deployAll | The sink for every protocol fee of the position tools, vaults, pre-market perps and the booked perp builder fees. 20 % is credited to the user's referrer; the rest belongs to the treasury, and anyone can `flush` it there. | `ReferralRegistry`, `FeeCollector` | | `ReferralRegistry` | deployAll | Write-once referral codes and write-once user-to-referrer links. | none | | `FeeCollector` | deployVenue | Receives the pools' protocol share and `FeeRouter`'s flushes. Anyone can `convert` a token to HYPE along the owner's route; the HYPE goes to `BuybackV2`. | `Router`, `AssetRegistry` | | `BuybackV2` | deployVenue | Spends up to its per-call cap of HYPE on $ELYRA in its native-HYPE v4 pool, burns every token bought and pays the caller 50 bps. `poke` moves its reference price. | PoolManager | Details: [Buyback and burn](https://elyratrade.io/docs/protocol), [Fees and referrals](https://elyratrade.io/docs/fees). ## Who holds a key | Role | Set from | Can | Cannot | | --- | --- | --- | --- | | Owner | `OWNER`, proposed by `handOver`, accepted with `acceptOwnership` | pause the venue, tune fees and price guards, list stocks and their feeds, set fee routes, sweep `FeeCollector`, create pool vaults, name their keeper; name each feed's keeper, set its bounds and write its answer (`setAnswer`) | touch a liquidity-management contract or a user position; block a withdrawal | | Hedger | `HEDGER`, the address of the API's `HEDGER_PRIVATE_KEY` | `reportHedge` on hedged vaults and `reportSleeve` on Income notes, at most every 5 min; the vault believes a report only within 15 % of its hourly anchor | move vault funds; hold exits | | Vault keeper | `KEEPER`, the address of the API's `BOT_PRIVATE_KEY` | rebalance DLMM and stock vaults as their factories' keeper | move vault funds | | Price feed keeper | `FEED_KEEPER`, the address of the API's `FEED_KEEPER_PRIVATE_KEY` | update Elyra's price feeds: at most 10 % an update, a minute apart, within 15 % of the hour's anchor | move any funds | | Funder, one per hedged vault | the deploy, one key per vault, never a hot key or each other | `fundHedge`: take margin to its own address, at most 10 % of on-chain assets per call out of an allowance of 25 % that refills over a day; `returnHedge`; name the vault's hedger (`setHedger`); believe a reported drop at once (`acceptReport`); off chain, withdraw that margin from Hyperliquid | report equity; raise the believed figure | | Agent wallets | generated by the signer, one per account, approved by the account's wallet | place and cancel Hyperliquid orders | withdraw or transfer from Hyperliquid | The deploy refuses to put two of the three bot roles on one key, and the API in production refuses a shared key. ## The programs off chain | Program | Code | Runs on | Job | Holds | | --- | --- | --- | --- | --- | | Web app | `apps/web` | Next.js 15, wagmi, viem; Privy for email login, or browser wallets when no Privy app id is set | Every page and every user transaction | nothing; your wallet signs | | API | `apps/api` | Fastify on `:8796`; Postgres, or memory when `DATABASE_URL` is unset | The routes pages read, the perp proxy, Ideas and points | `SIGNER_SECRET`, `ADMIN_SECRET` | | Bots | `apps/api/src/bots` | inside the API process, only when enabled | feed keeper, keeper, hedger, graduator, the pool duties and the fee path | `BOT_PRIVATE_KEY`, `FEED_KEEPER_PRIVATE_KEY`, `HEDGER_PRIVATE_KEY` | | Indexer | `apps/indexer` | Ponder on `:42074`; Postgres, or PGlite | Logs of Elyra's own contracts into tables, served as GraphQL to the API alone | nothing | | Signer | `services/signer` | Node (TypeScript) on `:8797`, signing with `@nktkas/hyperliquid` | Hyperliquid agent wallets and order signing, with no code path that withdraws | agent wallet keys, encrypted | [Indexer, API and bots](https://elyratrade.io/docs/offchain) covers the first four in depth; [Perpetuals](https://elyratrade.io/docs/perps) covers the signer. ## A write, from click to block Every button that changes chain state calls `useWrite().run(...)` in `apps/web/lib/tx.ts`. There is no second path. 1. Gate: `canWrite` checks for a connected wallet, chain 99901 (development builds also allow a local chain) and a deployment manifest. If one is missing, the button says which. 2. Simulate: The hook runs `simulateContract`, an `eth_call` from your address. A revert stops here: it costs nothing and your wallet never opens. 3. Sign and send: Your wallet signs the simulated request and sends it through the RPC. A toast links the transaction on the explorer. 4. Refresh: The query keys the write affects are refetched at 1.5 s, 4 s and 10 s, the time the indexer needs to see the new logs. For anything a transaction must get exactly right, the browser reads the chain directly instead of asking the API: balances, allowances, vault previews, router quotes, the active DLMM bin. The API never sends a transaction for a user. Its POST routes store a signed Idea, forward a signed perp request to the signer, return a mirror plan for your wallet to send, record the contact form or, with the admin secret, recompute points. ## A read, from chain to page 1. A page hook in `apps/web/lib/data.ts` calls a typed fetcher in `apps/web/lib/api.ts` against `NEXT_PUBLIC_API_URL`, with a 15 s stale time and no retry. 2. The API route answers from the indexer (GraphQL documents in `src/indexer/queries.ts`), from chain reads batched through Multicall3, from Hyperliquid's market data or from its database. A cached route keeps its answer for 15 to 60 s. 3. The route maps its own model to the exact shape `api.ts` declares (`routes/wire.ts`), and a test fails if either side renames a field. 4. If the API does not answer, the page shows its empty state and a status notice. The indexer is fed by the chain alone. It subscribes to the Elyra contracts in the manifest and folds their logs into tables; Uniswap pools and positions outside them are read from the chain when a route needs them. ## Shared packages ### `@elyra/core` Pure TypeScript with no I/O, imported by the web, the API and the indexer. It holds tick maths and range shapes, zap maths, impermanent loss, fee APR, the Seasoned screen (`isEstablished`), Carry (`basis.ts`), LP delta and hedge sizing (`hedge.ts`), keeper policy predictions (`policy.ts`), note payoffs, DLMM bin maths, the perp request message (`perpAuth.ts`), slippage, market hours, position sizing and backtests. A number on a card and the number a bot acts on come from the same function. Two Foundry tests write fixtures when run with `WRITE_FIXTURES=true`: `contracts/fixtures/zap.json`, which `packages/core/src/zapMath.test.ts` asserts the TypeScript port against, and `contracts/fixtures/payoff.json`, eight points of each `StructuredVault.payoffCurve` mode that `payoff.ts` mirrors. ### `@elyra/abi` and the manifest - `src/generated/` holds the compiler ABIs of every contract with an off-chain caller. `contracts/export-abis.sh` writes them, and they are committed, so no package needs Foundry to build. - `src/addresses.ts` holds the fixed facts: chain 99901, the public RPC, the official Uniswap contracts, WHYPE, USDC, the EQX stock tokens, Elyra's price feeds and Multicall3. `contracts/script/ElysiumAddresses.sol` holds the same addresses for the deploy scripts. - `src/manifest.ts` types the deployment manifest and validates it with `loadManifest`, which names the bad key when it throws. The manifest is the one file that says where a deployment lives: `chainId`, `deployBlock`, the owner, treasury, hedger, keeper, feed keeper and funder, each hedged vault's funder (`funders`), the three vault implementations, `addresses` (with seed vaults by name) and `venue`. The API reads it from `MANIFEST_PATH`, the indexer from `PONDER_MANIFEST`, the web from `apps/web/deployments/manifest.json` or `NEXT_PUBLIC_MANIFEST_URL`. Without one, writes are disabled, the bots stay off, the manifest routes answer empty and the indexer has nothing to follow. ### Deployed addresses Read from the manifest this site loaded, so the table is always the deployment you are using: Core: - FeeRouter: 0xa6afd56e140cd51f631aD62D3cb79b31971F62b0 · https://elyratrade.io/abi/FeeRouter.json - ReferralRegistry: 0x982d834bBa4afc2875eC67Ed378C14E0b417105d · https://elyratrade.io/abi/ReferralRegistry.json - ElyraZapV3: 0x43e76A0874057692FD80DaD587de506F96F70e1c · https://elyratrade.io/abi/ElyraZapV3.json - ElyraZapV4: 0x3ab6f98A7C3539ECDD5ecA41e1c0AAB3fd0f15F8 · https://elyratrade.io/abi/ElyraZapV4.json - RangeOrders: 0x18661148654361D245357aC5dc598efC5047e53b · https://elyratrade.io/abi/RangeOrders.json - PositionKeeper: 0x011d0A6194534B652b8120440678cF188F20E94F · https://elyratrade.io/abi/PositionKeeper.json - VaultFactory: 0x61b855aAe7Bdec53F257FA0087E2bAf628D90911 · https://elyratrade.io/abi/VaultFactory.json - LaunchPipeline: 0x078bDD252270861da1aD54C4D3dDc6999Acc4dfA · https://elyratrade.io/abi/LaunchPipeline.json - PreMarketPerp: 0xC75AC919C8B8A14DAb7B5e0b99C2925C67e9455D · https://elyratrade.io/abi/PreMarketPerp.json Vaults: - HYPE Vault: 0x28C6C0abC1C6a1A81bd09261dC8e8d249A408569 · https://elyratrade.io/abi/LPVault.json - Income NVDA: 0xB4531F3336e0583Aa6b933c93a5D5f746Af367a7 · https://elyratrade.io/abi/StructuredVault.json - NVDA Hedged: 0x4C2093c94334A283C736b72cd97C22A1E18a2989 · https://elyratrade.io/abi/HedgedLPVault.json - Protected SPY: 0xFEDA1D261AAC50543c512C32b7684068b428C8fB · https://elyratrade.io/abi/StructuredVault.json - SPY Hedged: 0xAA04586C7a79cF5421CaFD4cb036D70B98279Db0 · https://elyratrade.io/abi/HedgedLPVault.json - USDC Vault: 0x00C14dB62a37996f927AB208C1C578416a8B7C63 · https://elyratrade.io/abi/LPVault.json Elyra pools and router: - ProtocolConfig: 0xCeF328DcEaafc0F07C198Eb6562782F9bF5A69Bc · https://elyratrade.io/abi/ProtocolConfig.json - AssetRegistry: 0x41dD7a985701746CB4918e73b031aeD2E594f4CF · https://elyratrade.io/abi/AssetRegistry.json - DammHook: 0xFA7177b795d4b60d5397664F761c1F75917768Cc · https://elyratrade.io/abi/DammHook.json - StockHook: 0xe4a414f1E91FeC01FC3bbB40d49ccBdA3bB5e8CC · https://elyratrade.io/abi/StockHook.json - DlmmFactory: 0x6f499c3Db8f02F3c8DBD5CDC732B284AcC1E68c3 · https://elyratrade.io/abi/DlmmFactory.json - DlmmPositionNFT: 0x8A063A385e2D848E2cE53B02eCe5891FB8D346E0 · https://elyratrade.io/abi/DlmmPositionNFT.json - Router: 0xDA6B9DcFb519714F62Dc945Ee4e07695003d82Df · https://elyratrade.io/abi/Router.json - FeeCollector: 0xE91c916e4b813A35b015Bcaf7B2b31b02Cb05Ca3 · https://elyratrade.io/abi/FeeCollector.json - BuybackV2: 0x6Fa7A28e49D46994D1F6f74AccD6211C2B2efDC5 · https://elyratrade.io/abi/BuybackV2.json - DlmmLimitOrders: 0x864fd8C0f504D854b9CdD8d03321E4F8462BbC31 · https://elyratrade.io/abi/DlmmLimitOrders.json - DlmmVaultFactory: 0x2a61D5A547C057BE9B5bDEE9DFbDD1A07ac9841e · https://elyratrade.io/abi/DlmmVaultFactory.json - DlmmVaultZap: 0x986ce670ba037aCA417bB8C103335f4E4Ba12298 · https://elyratrade.io/abi/DlmmVaultZap.json - LaunchPools: 0xFE9782298b321B6E9aEeE3168a04cC394724fB3B · https://elyratrade.io/abi/LaunchPools.json - LaunchVault: 0xF34676D47E21665AdD5497946A4945b050E61813 · https://elyratrade.io/abi/LaunchVault.json - StockVaultFactory: 0xaD6CBacC3D110E9B3Ae4171AcDe70d8402Ce4915 · https://elyratrade.io/abi/StockVaultFactory.json Vault implementations (every vault clone delegates to one): - HedgedLPVault implementation: 0x1AF2d539F5f4619927be4c94c954A315d5E24557 · https://elyratrade.io/abi/HedgedLPVault.json - LPVault implementation: 0xe45c42EA63f290EfbCA89B13C55Bed0D750F52d4 · https://elyratrade.io/abi/LPVault.json - StructuredVault implementation: 0xd5C93d066691FF05ed2eeC60973FAc0477f88aB1 · https://elyratrade.io/abi/StructuredVault.json Price feeds (Elyra's keeper-pushed PushFeeds, AggregatorV3 reads, 8 decimals): - AAPL/USD: 0x05FA7227A7cDf2C41813acf75c7cd644B0a868c4 · https://elyratrade.io/abi/PushFeed.json - HYPE/USD: 0xA3659C451c9E40D8869341ffd5Fe296dE24C0373 · https://elyratrade.io/abi/PushFeed.json - META/USD: 0x4C7DD932d3211D18a9A3BD8C977862ff39f88CcF · https://elyratrade.io/abi/PushFeed.json - NVDA/USD: 0x4AcA0125bb977904b5b6da6C60Be1EC1f32A2925 · https://elyratrade.io/abi/PushFeed.json - QQQ/USD: 0x745b132ac749125B18De81b5a5c041cA8F5b47D7 · https://elyratrade.io/abi/PushFeed.json - SPCX/USD: 0x98a54968367720bE4418Ef334FE54c55F065aE22 · https://elyratrade.io/abi/PushFeed.json - SPY/USD: 0x2059AB180054E0A9d4EA4865bF0e83BcFafAA173 · https://elyratrade.io/abi/PushFeed.json - TSLA/USD: 0xD9B80933C2d2A3888ec8b9c3c49BE31bE9Ee8109 · https://elyratrade.io/abi/PushFeed.json ## Deploying the stack The Elysium deploy script and `DeployLocal.s.sol` both call `deployAll` in `contracts/script/ElyraWiring.sol`. It never starts a broadcast and never reads the environment, so the same sequence runs under a broadcast, a dry run and a fork test. 1. The venue: `VenueWiring.deployVenue` deploys `AssetRegistry`, `BuybackV2`, `Router`, `FeeCollector` and `ProtocolConfig`, then both hooks at CREATE2 addresses whose low bits are their permission flags, then the DLMM, launch and stock-vault contracts. It sets the quotes, lists every EQX stock with default risk parameters and names the vault keeper as keeper of both vault factories. 2. Fees: `ReferralRegistry`, then `FeeRouter` with the venue's `FeeCollector` as its treasury. 3. Position tools: Both zaps, `RangeOrders` and `PositionKeeper`. 4. Vaults and launches: The three vault implementations, then `VaultFactory`, which takes them as constructor arguments because their combined creation code is over the initcode limit. Then `LaunchPipeline` and `PreMarketPerp`. 5. Seed vaults: Best effort: the plain, hedged and note vaults the wiring names. A missing pool logs a line and skips that vault. 6. Hand over: `handOver` proposes the owner for the four venue admin contracts, and `_handOverFeeds` for every price feed. Until the owner calls `acceptOwnership`, the deployer still holds them. `writeManifest` then records the result. `DeployLocal` also runs `VenueSeed`, which seeds pools, a deposit, a resting DLMM limit order and a launch on a local fork. `Canary.s.sol` is the post-deploy smoke test: a tiny zap, a range order placed and cancelled, and a harvest on a seed vault's pool. ## Reference ### Deploy values Parameters: contracts/script/ElyraWiring.sol and script/venue/VenueWiring.sol - `CURVE_HALF_TICKS` (allowed: ticks; default: 2231): Half-width of every seed vault range (about ±25 %), snapped to the pool spacing. - `HYSTERESIS_SPACINGS` (allowed: spacings; default: 10): Seed vault hysteresis, as a multiple of tick spacing. - `MIN_INTERVAL` (allowed: seconds; default: 6 h): Least time between two keeper actions on a seed vault. - `MAX_SLIPPAGE_BPS` (allowed: bps; default: 100): Swap bound on a seed vault rebalance. - `BOUNTY_BPS` (allowed: bps; default: 50): Bounty the seed vault policy advertises to bots. - `NO_CAP` (allowed: asset units; default: type(uint256).max): The cap of the plain and hedged seed vaults: none. - `MAX_HEDGE_AGE` (allowed: seconds; default: 1 h): A hedge or sleeve report older than this counts as zero for exits and holds deposits. - `MAX_EQUITY_JUMP_BPS` (allowed: bps; default: 1500): The band around the hour's anchor the believed equity moves in; an Income note's band is the same share of its anchor plus its collateral. - `MAX_FUND_BPS_PER_CALL / PER_PERIOD` (allowed: bps; default: 1000 / 2500): fundHedge caps: 10 % of on-chain assets per call, out of an allowance of 25 % that refills over a day. - `FEED_MAX_DEVIATION_BPS / FEED_MIN_INTERVAL` (allowed: bps / seconds; default: 1000 / 60): A feed update moves the answer at most 10 %, a minute after the last. - `FEED_MAX_WINDOW_MOVE_BPS / FEED_WINDOW` (allowed: bps / seconds; default: 1500 / 1 h): A feed answer stays within 15 % of the hour's anchor. - `FEED_HEARTBEAT / FEED_CLOSED_HEARTBEAT` (allowed: seconds; default: 1 h / 4 days): Feed age the AssetRegistry accepts: HYPE always and a stock in session, and a stock while closed (ElysiumAddresses.sol). - `MIN_LIQUIDITY` (allowed: liquidity; default: 10 ether): In-range liquidity LaunchPipeline needs before a graduation, summed over four fee tiers. - `STOCK_OPEN / CLOSED / STALE_FEE_BPS` (allowed: bps; default: 30 / 150 / 500): Default stock pool fee by session; the owner can tune each asset. - `STOCK_OPEN / CLOSED_MAX_DEV_BPS` (allowed: bps; default: 200 / 50): Default feed band of a stock pool, open and closed. ### Ports and environment | Program | Local port | Points at | | --- | --- | --- | | Local chain (anvil fork of Elysium) | 8549 | the fork RPC | | API | 8796 | `INDEXER_URL`, `RPC_URL`, `MANIFEST_PATH`, `SIGNER_URL` | | Signer | 8797 | `SIGNER_SECRET`, shared with the API | | Indexer | 42074 | `PONDER_RPC_URL`, `PONDER_MANIFEST`, `DATABASE_URL` | | Web | 3034 | `NEXT_PUBLIC_API_URL`, `NEXT_PUBLIC_RPC_URL`, `NEXT_PUBLIC_CHAIN_ID`, `NEXT_PUBLIC_PRIVY_APP_ID` | | Landing | 3035 | built into the web app's `public/landing/` | Where it lives: - `contracts/src/`: the liquidity-management contracts and their libraries - `contracts/src/venue/`: pools, router, pool vaults, launches and the fee path - `contracts/script/ElyraWiring.sol`: deployAll, the seed vaults and writeManifest - `contracts/script/venue/VenueWiring.sol`: deployVenue and handOver - `apps/web/lib/tx.ts`: useWrite, the one write path - `apps/web/lib/data.ts`: page hooks and the fixture rule - `packages/core/src/`: the shared maths - `packages/abi/src/manifest.ts`: the manifest type and loadManifest - `contracts/export-abis.sh`: how the generated ABIs are written --- # Indexer, API and bots Source: https://elyratrade.io/docs/offchain · Reference Events into tables, the routes the app reads, and the bots that keep positions, hedges and pools current. Three programs sit between the chain and the page. The indexer turns Elyra's contract logs into tables. The API turns those tables, live chain reads, Hyperliquid's market data and its own database into the JSON every page reads. Bots inside the API process send the routine transactions that keep positions, hedges and pools current. None of them holds your funds or can sign for you, and of everything the bots send, only three kinds of call need a role key, each its own. In brief: - The indexer (Ponder, `:42074`) reads the logs of Elyra's own contracts on Elysium. The API is its only reader; the browser never queries it. - The API (Fastify, `:8796`) maps every answer to the exact types `apps/web/lib/api.ts` declares. No route sends a transaction for you: the writes store a signed Idea, forward a signed perp request, return calldata for your wallet or record a message. - Bots start only when `BOTS`, `BOT_PRIVATE_KEY` and `MANIFEST_PATH` are all set. Every send is simulated first, and a send paid by a bounty goes out only when the bounty is at least 3 times its gas cost. - The hedger reports each hedged vault every 15 min, and the vault takes at most one report every 5 min. A report over 1 h old (`maxHedgeAge`) counts the hedge as zero for exits and holds deposits, with no transaction needed; exits never wait. - The feed keeper pushes HYPE/USD on a 30 bps move and a stock on a 50 bps move in its session, and each at least every 15 min. On chain a push moves a feed at most 10 %, a minute after the last, within 15 % of the hour's anchor. - Only `reportHedge`, a feed's `update` and the rebalance of DLMM and stock vaults need a role key: the hedger's, the feed keeper's and the vault keeper's, three different keys. Every other bot action is a public function that pays whoever calls it, or nobody. ## The indexer `apps/indexer` is a Ponder app. One handler per event writes Postgres (or the bundled PGlite under `.ponder/` when `DATABASE_URL` is empty), and the tables are served as GraphQL on port 42074. Every GraphQL document the API sends lives in `apps/api/src/indexer/queries.ts`, so the indexer's schema can change without any browser noticing. Diagram: From logs to tables. Left: the logs the indexer subscribes to, by source. Middle: the tables they fold into (ponder.schema.ts). The API is the only reader of the GraphQL endpoint; the browser never queries it. Every Elyra source starts at the manifest deployBlock, and with no manifest it is capped at block 0 and fetches nothing. ### Sources | Family | Contracts | Writes | | --- | --- | --- | | Elyra contracts | `FeeRouter`, `ReferralRegistry`, `RangeOrders`, `PositionKeeper`, `VaultFactory`, every vault clone, `LaunchPipeline`, `PreMarketPerp` | `rangeOrder`, `keeperEnrollment`, `keeperAction`, `vault`, `vaultShare`, `vaultEvent`, `graduation`, `perp*`, `referral` | | Elyra pools | `DammHook`, `StockHook`, `DlmmFactory` and every pair it creates, `Router`, `FeeCollector`, `BuybackV2` | `ammPool`, `ammSwap`, `routerSwap`, `feeConversion`, `buyback`, `ammStat` | Every source starts at the manifest's `deployBlock` and takes its addresses from `PONDER_MANIFEST` and its ABIs from `@elyra/abi`. With no manifest the sources are still declared, at the zero address and capped at block 0, so they fetch nothing while the generated event types stay the same. Vault clones are one source over `VaultFactory.VaultCreated`, using the union of the three vault ABIs. Uniswap pools and positions outside Elyra's contracts are not indexed; the API reads them from the chain when a page needs them. ### How derived fields are computed Handlers stay thin; anything with an edge case is a pure function in `src/logic/`, tested from `test/`. Tests cannot sit next to the code, because Ponder runs every file under `src/` except `src/api/` as an indexing file. - **Prices.** USDC is $1 by definition, HYPE and WHYPE follow the HYPE price, and an EQX stock token follows its market. Volume is counted on the quote side only, so a pushed pool price cannot inflate it. - **APR and Seasoned.** Hourly rollups give the 24 h window. `apr24hPct` is `feeAprFromPool` from `@elyra/core`, and `established` is `isEstablished`: at least 3 days old, market cap above $1M and at least 100 trades in 24 h. - **Loss against holding.** The entry amounts at the first deposit's price, compared with the position now plus everything withdrawn. Collected fees are left out on purpose. Every address and hash is stored in lowercase. Token amounts, liquidity and timestamps are `bigint` and travel through GraphQL as strings. USD figures and percentages are `double precision`, for display and ranking only. ### Rows that look wrong but are not | What you see | Why | | --- | --- | | A keeper enrollment changes its key | `PositionKeeper.Rebalanced` mints a new NFT. The old `keeperEnrollment` row gets `succeededBy`, the new one `succeeds`, and the lifetime totals carry over. | | A perp is `liquidated`, never `closed` | `Liquidated` fires before `Closed` in the same transaction, and the close handler keeps the liquidated status. | | `vault.paused` is false, yet deposits wait | The column mirrors the `HedgePaused` and `HedgeResumed` events, which mark the believed and the reported figure parting and meeting again. A stale report or a silent price feed holds deposits with no transaction and no log, so compare `hedgeAsOf` with the vault's `maxHedgeAge`, or call `paused()`. | | `referral.earned` holds strings | Raw token amounts routinely exceed 2^53. A `Taken` with no referrer writes nothing. | ### Running it Ponder reserves `/health`, `/ready`, `/status` and `/metrics`. `src/api/index.ts` adds `/healthz`, the GraphQL endpoint at `/` and `/graphql`, and Ponder's read-only SQL client at `/sql/*`. Gate traffic on `/ready`: it turns 200 only once the historical backfill is done. Every deploy indexes into a schema of its own, so a new build backfills beside the old one, which keeps serving until the new one's `/ready` passes; a restart of the same build resumes from its last checkpoint. In production the indexer stops at start without Postgres, an explicit `PONDER_RPC_URL` or chain 99901. Note: RPC limits The public Elysium RPC keeps full history, but it rate-limits parallel calls (HTTP 429), has no WebSocket and stops an `eth_getLogs` at 10,000 results. The indexer polls it with a request-rate cap and splits log ranges, and a production deploy can put a capped paid provider behind it. ## The API `apps/api` is one Fastify process. `loadConfig` parses the environment once into a `Config`, and `buildApp(config, deps)` takes every dependency injected, so no module reads `process.env` on its own and the tests run the real routes against fakes. Optional pieces degrade instead of failing: no `DATABASE_URL` means in-memory storage, an unreachable indexer means empty answers and `indexer: 'down'` on `/health`, no manifest means empty vault, launch and pool answers, and `VENUE` defaults to the simulated book. Diagram: Routes and where their answers come from. Dashed arrows are reads; the long-dash stream is the response. Every route maps its own model to the shape apps/web/lib/api.ts declares before it answers, and web.types.test.ts fails when a field is renamed on either side. ### Routes | Route | Serves | Answers from | Cache | | --- | --- | --- | --- | | `GET /radar` | Markets | the chain pool snapshot, indexer pools, Elyra pool rows, market data | 15 s | | `GET /markets`, `GET /candles?market=&tf=&limit=&before=` | Trade, charts | Hyperliquid market data; `tf` is one of `1m 5m 15m 1h 4h 1d`; `before` (unix seconds) answers the bars older than it, `[]` at the start of the history | 15 s, 60 s | | `GET /book`, `GET /trades`, `GET /funding/history` | Trade, Markets | Hyperliquid's order book, recent trades and funding | short | | `GET /portfolio/:address` and `/performance/…` | Portfolio | indexer vault shares, range orders and enrollments; Uniswap positions, pending fees and pool prices read from the chain; the perp venue | none | | `GET /vaults` | Earn | manifest and graduated vaults, chain reads, the indexer's harvest log, market data | 30 s | | `GET /launch?address=` | Launch | indexer graduations, chain reads of `LaunchPipeline` and `PreMarketPerp`; your positions read fresh | 30 s for the shared part | | `GET /pools?kind=`, `/pools/:id`, `/stocks`, `/protocol`, `/amm/vaults` | Pools, Stocks, Protocol, Earn | indexer pool tables and live pool state, priced with market data; stock feeds and buyback state read per request | 15 s | | `GET /theses`, `/theses/:id`, `/theses/leaderboard`, `POST /theses`, `POST /theses/:id/mirror` | Ideas | the database, plus indexer fees and PnL for the leaderboard | none | | `GET /referral/:address` | Portfolio, Lounge | the indexer's `referral` row, each token priced at its mark | none | | `GET /points/:address`, `/points/leaderboard`, `POST /points/recompute` | Lounge, Portfolio | points events and Ideas in the database | none | | `POST /perp/onboard`, `/order`, `/modify`, `/cancel`, `/session/end`; `GET /perp/account/:address`, `/positions/:address`, `/orders/:address`, `/fills/:address`, `/funding/:address` | Trade | the perp venue | none | | `POST /contact` | contact form | the database | none | | `GET /health` | status banner | a 1 s probe of the indexer's `/ready`, reused for 15 s | 15 s | Cursors ride in the `x-next-cursor` header, so list routes answer bare arrays. `/health` answers exactly `{ok, venue, indexer, db, signer, markets, rpc}` (the components `ok`, `down` or `off`, and 503 when the database or the signer is down; `rpc` is the paid fallback, `ok`, `capped` or `off`), plus `feeds` when the deployment has price feeds, and nothing about the configuration. `GET /health/bots` answers 200 while the worker's heartbeat is under a minute old, every bot is ticking and every feed is inside its age bound, and 503 with a list of problems otherwise. Every error is `{error, code}`: `bad_request` 400, `unauthorized` 401, `forbidden` 403, `not_found` 404, `conflict` 409, `rate_limited` 429, `unavailable` 503, or a more specific code such as `invalid_address`, `stale_ts`, `nonce_used`, `duplicate_thesis` or `manifest_missing`. ### The wire contract The web's types are the contract. `apps/api/src/routes/types/web.ts` copies the interfaces of `apps/web/lib/api.ts`, and `web.types.test.ts` fails when a field is added, removed or renamed on either side. The API's own models keep whole percents and `{items, nextCursor}` pages and convert on the way out (`routes/wire.ts`): percent fields become fractions, and a candle's `t` in milliseconds becomes `time` in seconds. ### How Markets rows are built `buildRadar` is a pure function. The pool set comes from `chain/poolSnapshot.ts`, which asks the Uniswap v3 factory for every listed asset against USDC and WHYPE on the four fee tiers and reads each pool's tick, liquidity and balances in Multicall3 batches. `chain/poolStats.ts` adds 24 h volume, fees, trades, age and market cap from each pool's own `Swap` logs, read incrementally into hourly buckets. The server warms the snapshot at start and every 60 s, so no request waits for it. A pool names its row through the side that is not USDC or WHYPE, joined to its Hyperliquid market through `@elyra/abi`'s token table: a crypto token to its perp, an EQX stock token to its `xyz` HIP-3 market (EQSPY to `xyz:SP500`). A symbol's best pool has the highest fee APR among pools holding at least 1 % of its pool TVL, so a dust pool cannot name the row. Elyra's own pools add one row each with `source: 'elyra'`. Carry is `basisSignal` from `@elyra/core`: pool APR plus hourly funding times 8 760, at least 8 % to watch and 20 % for strong. Pool and perp give `lp-and-short` (Hedge) when carry clears the watch bar and `neutral` otherwise; a pool alone gives `neutral` if Seasoned and `avoid` if not; a perp alone gives `long-perp`; neither gives `avoid`. ### Market data `MarketData` is one cached view of every market Elyra lists, from Hyperliquid's public info API: marks, 24 h stats, open interest and funding for the main perps and the `xyz` HIP-3 markets. A symbol Hyperliquid has no mark for still comes back, with `mark: null`. Concurrent requests for the same data share one upstream call. ### Ideas and mirroring `POST /theses` verifies an EIP-712 signature under `{ name: 'Elyra', version: '1', chainId }` over `Thesis { positionRef, side, text, ts }`. `positionRef` is `v3:`, `perp:::` or `vault:
`; `side` is `long`, `short` or `lp`; `text` is at most 500 characters; `ts` must be within 300 s of the server clock. Because `ts` is in the message, one signature makes one post: a repeat is 409 `duplicate_thesis`. The leaderboard ranks authors by realised fees plus realised PnL across their indexed positions. `POST /theses/:id/mirror` executes nothing. It returns `zapMint` calldata on `zapV3` for a v3 position (the author's pair, fee and ticks, 100 bps slippage, a 20 min deadline), `deposit(0, you)` for a vault, or, given `sizeUsd` and a live mark, a sized market order for a perp. ### Perp requests Every `/perp/*` route forwards to the configured venue. The default is `SimVenue`: an in-memory book on real marks that credits each new account 10 000 USDC, fills market orders 5 bps worse than the mark and accrues funding hourly. The live venue is an HTTP client for `services/signer` that signs every request with the shared `SIGNER_SECRET`: an HMAC over a timestamp, a one-time nonce, the path and the body, so the secret never crosses the network. The API never holds an agent wallet, and there is no withdraw route. Each write body carries `auth: { nonce, ts, signature }`, an EIP-712 signature over `PerpAction { action, account, payloadHash, nonce, ts }`, checked by `requirePerpAuth` as [Perpetuals](https://elyratrade.io/docs/perps#signed-requests) describes. A trading session adds `auth.session`, a wallet-signed `PerpSession` grant, honoured on `/perp/order` and `/perp/cancel` only. ### Limits and hardening - Every `POST`, `PUT`, `PATCH` and `DELETE` shares a budget of `RATE_LIMIT_WRITES_PER_MIN` (30) per route group and client IP. A refusal is 429 with `Retry-After`. Reads are never limited. `/contact` adds its own 5 per minute per IP. - The limiter lives in the process, so each replica grants the full budget. - `TRUST_PROXY` decides what the client IP is and is off by default; turn it on only behind a proxy that sets `X-Forwarded-For`. - `CORS_ORIGIN` is a comma-separated list of scheme-and-host origins. `*` and bare host names are refused, and with `NODE_ENV=production` the API will not start without it. - `POST /points/recompute` needs `x-admin-secret`, compared in constant time; without `ADMIN_SECRET` it answers 503. ### When the API is not there Each page hook in `apps/web/lib/data.ts` wraps its fetcher in React Query with no retry and a 15 s stale time. In a development or staging build, a failed request falls back to a fixture from `lib/fixtures/` and the page shows an "Example data" tag. A production build never shows a fixture: the page renders its empty state and a status notice. Writes need a manifest, not the API. ## The bots The bots live in `apps/api/src/bots` and run inside the API process. `startBots` returns without starting anything, and logs which variable is missing, unless `BOTS`, `BOT_PRIVATE_KEY` and `MANIFEST_PATH` are all set. `BOT_PRIVATE_KEY` signs for the vault keeper and every permissionless bot; the feed keeper signs with `FEED_KEEPER_PRIVATE_KEY` and the hedger with `HEDGER_PRIVATE_KEY`. Either falls back to `BOT_PRIVATE_KEY` when unset, which production refuses, and production also refuses one key in two roles, as the deploy does on chain. A bot is one `tick()`: it reads, decides and returns a list of actions, each a transaction hash, a venue order id or a `skipped` reason. The runner's rule is that a bot must never take the API down: every tick is wrapped and its errors logged, a tick still running when its interval comes round is skipped rather than stacked, timers never hold up a shutdown, and every bot runs once at start. The hedger ticks every `HEDGER_INTERVAL_MS` (30 s), the feed keeper every `FEED_KEEPER_INTERVAL_MS` (30 s), the pool bots every `AMM_BOT_INTERVAL_MS` (15 s), the keeper and graduator every `BOT_INTERVAL_MS` (60 s), the fee sweeper every `FEE_SWEEP_INTERVAL_MS` (10 min) and the spot fee booker every `SPOT_FEE_BOOK_INTERVAL_MS` (5 min). Diagram: One keeper tick. Three sweeps in a fixed order, then the same attempt for every candidate. A skip is a normal result: the tick reports it, the guard remembers it, and a later tick tries again with fresh data. Sweep (c) is the one deliberate send without a priced bounty and says so with bounty {kind: none}, which skips the two bounty checks. The lower half is the send path every bot shares. ### The send path Every bot write goes through `ChainClient.simulateAndSend`: 1. `simulateContract`, an `eth_call` against pending state. A revert is the usual result, not an error: the position no longer qualifies, the order is not fillable yet, the token is too young. It costs nothing, which is why the bots can run on a loop. 2. For a send paid by a bounty, `estimateContractGas` times `getGasPrice` gives its cost in HYPE, and the send is skipped when the bounty is under 3 times that (`GAS_BOUNTY_MULTIPLE`). A bounty that could not be priced skips before the estimate: a missed harvest costs the owner nothing, while sending blind would turn one market-data outage into unguarded gas for every position. 3. `writeContract`, then one confirmation. A reverted receipt counts as a failure. `ActionGuard`, keyed by action and target, mutes a target for `COOLDOWN_MS` (5 min) after a success, while the indexer catches up, and for `FAIL_BACKOFF_MS` (15 min) after a failure, so a position that always reverts costs one simulation per quarter hour. The state is in memory on purpose: a restarted bot rebuilds everything from the chain and the indexer, and the contracts' own intervals are the real guard. It also means two replicas would send twice, so run the bots on one. ### Feed keeper Elysium has no oracle network, so HYPE/USD and every stock's USD price live in Elyra's own `PushFeed`s (the manifest's `feeds`), and the feed keeper's key is the only one that may `update` them. Each tick reads every feed's latest round and `bounds()` in one multicall and the references once, then decides per feed: 1. **Target.** HYPE: Hyperliquid's HYPE oracle price. A stock during the NYSE session: its reference, the `xyz` perp's oracle price (for SPY and QQQ the mid of Hyperliquid's EQSPY and EQQQQ spot books, pushed only while Yahoo's session price agrees within 1 %). Outside the session the close stands. 2. **Sanity.** A reference older than `FEED_KEEPER_MAX_SOURCE_AGE_S` (120 s), more than `FEED_KEEPER_MAX_JUMP_BPS` (2 500) from the on-chain answer or, for SPY and QQQ, more than `FEED_KEEPER_CROSS_CHECK_BPS` (300) from Hyperliquid's EQX spot mid is refused, never pushed. With no fresh reference in the session the feed goes stale rather than an old price looking live. 3. **Due.** A move of `FEED_KEEPER_DEVIATION_BPS` (30, HYPE) or `FEED_KEEPER_STOCK_DEVIATION_BPS` (20, a stock in session), or `FEED_KEEPER_HEARTBEAT_S` (900 s, refused above 1 800) since the last push for HYPE and for a stock in session. A closed stock is never re-pushed for age. 4. **Step.** On chain one update moves a feed at most `maxDeviationBps` (10 %), at least `minInterval` (60 s) after the last, and within `maxWindowMoveBps` (15 %) of the window's anchor, the answer standing at the first update of each hour. A larger move is walked in steps just under both; past the window bound the feed is `waiting` for the next hour. A genuine gap larger than that is the owner's `setAnswer`. 5. **Gas.** No push above `FEED_KEEPER_MAX_GAS_GWEI` (5 gwei), and none once the UTC day's spend would pass `FEED_KEEPER_DAILY_GAS_HYPE` (0.15 HYPE). The contracts call HYPE/USD stale an hour after its last push, always, and a stock an hour after its last push while its session is open and four days after it while closed, so the close stands over a weekend and the feed reads stale at the open until a session price lands. `/health` adds `feeds`: each feed's answer and age read from chain, and the keeper's state for it (`ok`, `held`, `waiting`, `refused`, `no reference`, `gas` or `error`). ### Keeper One keeper tick runs three sweeps in order. 1. **Enrolled positions.** The indexer's active enrollments, then `shouldHarvest` and `shouldRebalance` for each in one Multicall3 batch, then `harvest` or `rebalance` where the contract says yes. The bounty is `bountyBps` of the position's pending fees, converted to wei at the HYPE mark. 2. **Range orders.** `fillable(orderId)` for every open order, then `fill` only where it says yes. The bounty is 1 % of the order's size (`RANGE_ORDER_BOUNTY_BPS` 100). 3. **Manifest vaults.** `LPVault.harvest()` has no "worth it" view, so the bot simulates it once per `VAULT_HARVEST_INTERVAL_MS` (6 h) per vault and sends whenever the simulation passes. The vault's own `minInterval` rejects the rest. Diagram: Hedger and graduator ticks. Neither bot earns a bounty, so each sends whenever the simulation passes. The hedger reports every 15 minutes and re-hedges sooner when the delta drifts; the graduator tracks a token the first tick it qualifies and graduates it on the first tick after three days. ### Hedger For each vault whose manifest name contains "Hedged", plus any address in `HEDGED_VAULTS`, the hedger sizes the short from the vault's LP position with `lpDelta` from `@elyra/core`, trades the difference on the funder's Hyperliquid account through the signer, and writes `reportHedge` on chain. It acts when a report is due (`HEDGE_REPORT_INTERVAL_MS`, 15 min) or when the gap between target and current short exceeds `HEDGE_DRIFT_BPS` (200) of the target, and never sooner than five minutes after the last report, which the vault refuses (`ReportTooSoon`). It always reports the truth: the vault believes a report within 15 % of its hourly anchor and three times the margin funded, walks a larger move in and holds deposits meanwhile. [Hedged vaults](https://elyratrade.io/docs/hedged-vaults#the-hedger-bot) walks through one tick. The hedger never calls `fundHedge` (that is the funder's key) or `StructuredVault.reportSleeve`. ### Graduator `LaunchPipeline` checks only age and pool depth on chain; the rest of the Seasoned screen is the indexer's flag, and this bot joins the two. For every pool the indexer marks `established` whose token (the side that is not USDC or WHYPE) has not graduated, it reads `firstSeen(token)` in one batch. Zero means `track(token)`, which starts the three-day clock. Three days or more means `graduate(token)`. Anything in between is skipped without a log line. Neither call pays a bounty. ### Pool duties and the fee path These bots need the manifest's `venue` object and share the send path above; all but the fee sweeper's `buyback()` pay their own gas with no bounty. | Bot | Acts when | Sends | Notes | | --- | --- | --- | --- | | `dlmmVaultRebalancer` | a DLMM vault's `needsRebalance()` has held for `DLMM_SUSTAIN_S` (120 s) and the vault's 5 min interval has passed | `rebalance(activeId, DLMM_ID_SLIPPAGE)`, 2 bins of slippage | only the factory's `keeper()` (or the protocol owner) may call it. The 120 s wait is the guard: holding a pushed price that long means trading against every arbitrageur | | `stockVaultRebalancer` | `rebalanceStatus()` returns ready: the session changed or the feed price drifted, the feed is fresh, the pool is near the feed price and the 5 min interval has passed | `rebalance()` | keeper only; a failed attempt is retried after `STOCK_VAULT_RETRY_S` (60 s) | | `limitOrderSettler` | `DlmmLimitOrders.readyBooks()` lists filled batches | `executeMany` for up to `LIMIT_ORDER_BATCH` (25) books | anyone may call it; a 60 s retry, because an unexecuted fill trades back if the price returns | | `buybackPoker` | `BuybackV2`'s reference price is at least 1 % from the pool price and at least 600 s old | `poke()` | anyone may call it | | `feeSweeper` | a step would move at least its configured minimum: treasury fees in the FeeRouter, a routed token, WHYPE or HYPE in the FeeCollector, or HYPE in BuybackV2 | `flush`, `convert`, the collector's unwrap and forward calls, then `buyback()` | anyone may call every step; `buyback()` pays its caller `callerRewardBps`, so it goes through the gas rule with that reward as its bounty | | `spotFeeBooker` | the FeeRouter holds more WHYPE, USDC or stock token than `accounted(token)` and a recent Universal Router transfer explains it | `take(token, amount, trader)` | see [Fees and referrals](https://elyratrade.io/docs/fees#the-uniswap-path-skim) | Note: The bots hold no special power Everything a bot sends, anyone can send: `harvest`, `rebalance`, `fill`, `track`, `graduate`, `executeMany`, `poke`, `flush`, `convert`, `buyback` and `take` are public. The exceptions are `reportHedge`, which only a vault's hedger may call, a feed's `update`, which only its keeper may call, and the DLMM and stock vault rebalances, which only their factory's keeper may call. The deploy names three different keys for the three roles. None of them can move funds out of a vault. See [Hedged vaults](https://elyratrade.io/docs/hedged-vaults) and [Security model](https://elyratrade.io/docs/security). ## Reference ### Indexer settings Parameters: apps/indexer environment - `PONDER_CHAIN_ID` (allowed: 99901 or a local id; default: 99901): A fork of Elysium keeps 99901. Production accepts 99901 only. - `PONDER_RPC_URL` (allowed: URL; default: the public Elysium RPC): Required in production. - `PONDER_RPC_MAX_RPS` (allowed: 0 or more): Request rate cap; 0 turns the throttle off for a local node. - `PONDER_MANIFEST` (allowed: path): The deployment manifest. Without it nothing is indexed; in production a path to a missing file stops the start. - `DATABASE_URL` (allowed: URL; default: empty = PGlite): Postgres; production refuses PGlite. - `PONDER_PORT / PORT` (allowed: port; default: 42074): Listen port. ### API settings Parameters: apps/api environment - `PORT` (allowed: port; default: 8796): HTTP port. - `DATABASE_URL` (allowed: URL): Unset: in-memory storage, lost on restart. - `INDEXER_URL` (allowed: URL; default: http://127.0.0.1:42074): GraphQL endpoint and the /ready probe. - `RPC_URL / CHAIN_ID` (allowed: URL / id; default: public RPC / 99901): Chain reads, the bot wallet, and the EIP-712 domain of Ideas and perp requests. - `MANIFEST_PATH` (allowed: path): Unset: vault, launch and pool routes answer empty, v3 mirroring answers 503, bots stay off. - `VENUE` (allowed: sim or the live venue; default: sim): The live venue forwards to the signer. - `SIGNER_URL / SIGNER_SECRET` (allowed: URL / string; default: http://127.0.0.1:8797): Rotate the secret on both services together. - `ADMIN_SECRET` (allowed: string): Unlocks POST /points/recompute. - `NODE_ENV` (allowed: development, test, production; default: development): production requires CORS_ORIGIN. - `RATE_LIMIT_WRITES_PER_MIN` (allowed: more than 0; default: 30): Per route group and client IP. - `TRUST_PROXY` (allowed: bool or proxy list; default: off): Only behind a proxy that sets X-Forwarded-For. - `CORS_ORIGIN` (allowed: origins): Unset: any origin is reflected, development only. ### Bot settings Parameters: apps/api environment, bots - `BOTS` (allowed: names, comma-separated; default: empty = off): feedKeeper, keeper, hedger, graduator, dlmmVaultRebalancer, buybackPoker, limitOrderSettler, stockVaultRebalancer, feeSweeper, spotFeeBooker; an unknown name stops the API at start. - `BOT_PRIVATE_KEY` (allowed: hex key): The vault keeper (KEEPER) and every permissionless bot; no bot starts without it. - `FEED_KEEPER_PRIVATE_KEY` (allowed: hex key): The feed keeper (FEED_KEEPER). Unset, BOT_PRIVATE_KEY signs, which production refuses. - `HEDGER_PRIVATE_KEY` (allowed: hex key): The hedger (HEDGER). Unset, BOT_PRIVATE_KEY signs, which production refuses. - `BOT_INTERVAL_MS` (allowed: ms; default: 60 000): Keeper and graduator. - `HEDGER_INTERVAL_MS` (allowed: ms; default: 30 000): Hedger. - `AMM_BOT_INTERVAL_MS` (allowed: ms; default: 15 000): The pool bots. - `COOLDOWN_MS / FAIL_BACKOFF_MS` (allowed: ms; default: 300 000 / 900 000): ActionGuard mutes after a success and after a failure. - `VAULT_HARVEST_INTERVAL_MS` (allowed: ms; default: 21 600 000): How often each manifest vault harvest is simulated (6 h). - `HEDGED_VAULTS / VAULT_MARKETS` (allowed: addresses / vault:MARKET; default: empty): Extra hedged vaults; market overrides such as xyz:SP500. - `HEDGE_REPORT_INTERVAL_MS` (allowed: ms; default: 900 000): Report cadence; refused above half of maxHedgeAge (1 h). The vault takes one report every 5 min at most. - `HEDGE_DRIFT_BPS` (allowed: bps; default: 200): Drift that forces a re-hedge between reports. - `HEDGE_MIN_NOTIONAL_USD` (allowed: USD; default: 50): Smallest adjustment sent. - `HEDGER_MODE` (allowed: live, report-only, off; default: live): Kill switch: report-only places no order but keeps reporting; off does nothing. - `HEDGE_MAX_ORDER_USD / HEDGE_DAILY_LOSS_USD` (allowed: USD; default: 25 000 / 2 500): Largest single hedge order (at most the signer's MAX_ORDER_NOTIONAL_USD); hedge loss per UTC day that stops orders. - `HEDGE_MAX_NOTIONAL_USD` (allowed: USD; default: off): Optional ceiling on one vault's short; off, a vault is hedged in full. - `DLMM_SUSTAIN_S / DLMM_ID_SLIPPAGE` (allowed: s / bins; default: 120 / 2): DLMM vault rebalancer. - `LIMIT_ORDER_BATCH` (allowed: books; default: 25): Limit-order books per executeMany. - `STOCK_VAULT_RETRY_S` (allowed: s; default: 60): Retry delay after a failed stock vault rebalance. - `FEED_KEEPER_INTERVAL_MS` (allowed: ms; default: 30 000): Feed keeper. - `FEED_KEEPER_DEVIATION_BPS / STOCK_DEVIATION_BPS` (allowed: bps; default: 30 / 20): Move that makes a push due: HYPE, a stock in session. - `FEED_KEEPER_HEARTBEAT_S` (allowed: s; default: 900): Push HYPE and a stock in session at least this often; refused above 1 800. - `FEED_KEEPER_MAX_SOURCE_AGE_S` (allowed: s; default: 120): Oldest reference pushed. - `FEED_KEEPER_MAX_JUMP_BPS / CROSS_CHECK_BPS` (allowed: bps; default: 2 500 / 300): A reference this far from the on-chain answer, or (SPY, QQQ) from the EQX spot mid, is refused. - `FEED_KEEPER_MAX_GAS_GWEI / DAILY_GAS_HYPE` (allowed: gwei / HYPE; default: 5 / 0.15): No push above this gas price, or past this spend in a UTC day. Where it lives: - `apps/indexer/ponder.config.ts`: sources, start blocks and the no-manifest fallback - `apps/indexer/ponder.schema.ts`: every table and column - `apps/indexer/src/logic/`: pricing, stats and the Elyra state machines - `apps/api/src/app.ts`: buildApp, the write budget and the error shape - `apps/api/src/config.ts`: every environment variable - `apps/api/src/radar.ts`: Markets rows and the Carry chip - `apps/api/src/chain/poolSnapshot.ts`: the pool set read from the chain - `apps/api/src/marketdata/hyperliquid.ts`: Hyperliquid's market data - `apps/api/src/perp/auth.ts`: requirePerpAuth and its order of checks - `apps/api/src/routes/types/web.types.test.ts`: the wire guard - `apps/api/src/bots/chain.ts`: simulateAndSend and the gas rule - `apps/api/src/bots/runner.ts`: which bots start, their keys and their intervals - `apps/api/src/bots/feedKeeper.ts`: the feed keeper's decision per feed - `apps/web/lib/data.ts`: the fixture rule and isSampleData --- # Agents and integrations Source: https://elyratrade.io/docs/agents · Reference How an AI agent or a script uses Elyra with its own wallet: the calls, the approvals, the minimums, and where the addresses and ABIs live. An agent, whether an AI agent, a bot or a script, can use every pool, vault and swap the app offers by calling Elyra's contracts on Elysium with its own wallet. Elyra never holds its key: nothing on this site can sign or send a transaction for anyone. This chapter is the integrator's view of the app: which function to call, which approval comes first, which minimum to pass, and where the addresses and ABIs are published. To set an agent up step by step, use [Connect your agent](https://elyratrade.io/agents): an instruction to paste into a chat agent, a script to start from, and a way to watch the agent's wallet. In brief: - Every Elyra contract is non-upgradeable, with no admin function over user positions. An address and its ABI never change under you. - The chain is Elysium, chain id 99901, with HYPE for gas, WHYPE as wrapped HYPE and USDC (6 decimals) as the stablecoin. - The addresses are in `/deployments/elysium.json`, the ABIs in `/abi/.json`, and an index written for agents in `/llms.txt`. `/llms-full.txt` is every chapter as plain text. - Approve the exact amount, to the contract that pulls it, and pass a minimum that is not zero wherever the call takes one. A vault deposit takes none, so check its preview just before you sign. - Simulate before you sign. Perps are not for agents through Elyra: an agent trades on Hyperliquid directly, with its own account. ## Where everything lives | Resource | Path on this site | What it holds | | --- | --- | --- | | Setup page | `/agents` | An instruction for a chat agent, a script to start from, and the agent wallet's positions | | Agent index | `/llms.txt` | What Elyra is, the rules, every contract with its ABI link, every chapter with its summary | | Full docs | `/llms-full.txt` | Every chapter of these docs as plain text, in reading order | | Deployment manifest | `/deployments/elysium.json` | Chain id, deploy block, every Elyra contract, the seed vaults by name | | Chain constants | `/deployments/elysium-external.json` | Uniswap v3 and v4, Permit2, Universal Router, WHYPE, USDC, the EQX stock tokens and Elyra's price feeds, Multicall3 | | ABIs | `/abi/index.json`, `/abi/.json` | One JSON ABI per Elyra contract, and which address uses which | All of them are generated from the same manifest and ABIs the app itself uses, at build time. The sources are verified on the [Elysium explorer](https://elysium.kinetiq.xyz/explorer). The addresses this site was built with: Core: - FeeRouter: 0xa6afd56e140cd51f631aD62D3cb79b31971F62b0 · https://elyratrade.io/abi/FeeRouter.json - ReferralRegistry: 0x982d834bBa4afc2875eC67Ed378C14E0b417105d · https://elyratrade.io/abi/ReferralRegistry.json - ElyraZapV3: 0x43e76A0874057692FD80DaD587de506F96F70e1c · https://elyratrade.io/abi/ElyraZapV3.json - ElyraZapV4: 0x3ab6f98A7C3539ECDD5ecA41e1c0AAB3fd0f15F8 · https://elyratrade.io/abi/ElyraZapV4.json - RangeOrders: 0x18661148654361D245357aC5dc598efC5047e53b · https://elyratrade.io/abi/RangeOrders.json - PositionKeeper: 0x011d0A6194534B652b8120440678cF188F20E94F · https://elyratrade.io/abi/PositionKeeper.json - VaultFactory: 0x61b855aAe7Bdec53F257FA0087E2bAf628D90911 · https://elyratrade.io/abi/VaultFactory.json - LaunchPipeline: 0x078bDD252270861da1aD54C4D3dDc6999Acc4dfA · https://elyratrade.io/abi/LaunchPipeline.json - PreMarketPerp: 0xC75AC919C8B8A14DAb7B5e0b99C2925C67e9455D · https://elyratrade.io/abi/PreMarketPerp.json Vaults: - HYPE Vault: 0x28C6C0abC1C6a1A81bd09261dC8e8d249A408569 · https://elyratrade.io/abi/LPVault.json - Income NVDA: 0xB4531F3336e0583Aa6b933c93a5D5f746Af367a7 · https://elyratrade.io/abi/StructuredVault.json - NVDA Hedged: 0x4C2093c94334A283C736b72cd97C22A1E18a2989 · https://elyratrade.io/abi/HedgedLPVault.json - Protected SPY: 0xFEDA1D261AAC50543c512C32b7684068b428C8fB · https://elyratrade.io/abi/StructuredVault.json - SPY Hedged: 0xAA04586C7a79cF5421CaFD4cb036D70B98279Db0 · https://elyratrade.io/abi/HedgedLPVault.json - USDC Vault: 0x00C14dB62a37996f927AB208C1C578416a8B7C63 · https://elyratrade.io/abi/LPVault.json Elyra pools and router: - ProtocolConfig: 0xCeF328DcEaafc0F07C198Eb6562782F9bF5A69Bc · https://elyratrade.io/abi/ProtocolConfig.json - AssetRegistry: 0x41dD7a985701746CB4918e73b031aeD2E594f4CF · https://elyratrade.io/abi/AssetRegistry.json - DammHook: 0xFA7177b795d4b60d5397664F761c1F75917768Cc · https://elyratrade.io/abi/DammHook.json - StockHook: 0xe4a414f1E91FeC01FC3bbB40d49ccBdA3bB5e8CC · https://elyratrade.io/abi/StockHook.json - DlmmFactory: 0x6f499c3Db8f02F3c8DBD5CDC732B284AcC1E68c3 · https://elyratrade.io/abi/DlmmFactory.json - DlmmPositionNFT: 0x8A063A385e2D848E2cE53B02eCe5891FB8D346E0 · https://elyratrade.io/abi/DlmmPositionNFT.json - Router: 0xDA6B9DcFb519714F62Dc945Ee4e07695003d82Df · https://elyratrade.io/abi/Router.json - FeeCollector: 0xE91c916e4b813A35b015Bcaf7B2b31b02Cb05Ca3 · https://elyratrade.io/abi/FeeCollector.json - BuybackV2: 0x6Fa7A28e49D46994D1F6f74AccD6211C2B2efDC5 · https://elyratrade.io/abi/BuybackV2.json - DlmmLimitOrders: 0x864fd8C0f504D854b9CdD8d03321E4F8462BbC31 · https://elyratrade.io/abi/DlmmLimitOrders.json - DlmmVaultFactory: 0x2a61D5A547C057BE9B5bDEE9DFbDD1A07ac9841e · https://elyratrade.io/abi/DlmmVaultFactory.json - DlmmVaultZap: 0x986ce670ba037aCA417bB8C103335f4E4Ba12298 · https://elyratrade.io/abi/DlmmVaultZap.json - LaunchPools: 0xFE9782298b321B6E9aEeE3168a04cC394724fB3B · https://elyratrade.io/abi/LaunchPools.json - LaunchVault: 0xF34676D47E21665AdD5497946A4945b050E61813 · https://elyratrade.io/abi/LaunchVault.json - StockVaultFactory: 0xaD6CBacC3D110E9B3Ae4171AcDe70d8402Ce4915 · https://elyratrade.io/abi/StockVaultFactory.json Vault implementations (every vault clone delegates to one): - HedgedLPVault implementation: 0x1AF2d539F5f4619927be4c94c954A315d5E24557 · https://elyratrade.io/abi/HedgedLPVault.json - LPVault implementation: 0xe45c42EA63f290EfbCA89B13C55Bed0D750F52d4 · https://elyratrade.io/abi/LPVault.json - StructuredVault implementation: 0xd5C93d066691FF05ed2eeC60973FAc0477f88aB1 · https://elyratrade.io/abi/StructuredVault.json Price feeds (Elyra's keeper-pushed PushFeeds, AggregatorV3 reads, 8 decimals): - AAPL/USD: 0x05FA7227A7cDf2C41813acf75c7cd644B0a868c4 · https://elyratrade.io/abi/PushFeed.json - HYPE/USD: 0xA3659C451c9E40D8869341ffd5Fe296dE24C0373 · https://elyratrade.io/abi/PushFeed.json - META/USD: 0x4C7DD932d3211D18a9A3BD8C977862ff39f88CcF · https://elyratrade.io/abi/PushFeed.json - NVDA/USD: 0x4AcA0125bb977904b5b6da6C60Be1EC1f32A2925 · https://elyratrade.io/abi/PushFeed.json - QQQ/USD: 0x745b132ac749125B18De81b5a5c041cA8F5b47D7 · https://elyratrade.io/abi/PushFeed.json - SPCX/USD: 0x98a54968367720bE4418Ef334FE54c55F065aE22 · https://elyratrade.io/abi/PushFeed.json - SPY/USD: 0x2059AB180054E0A9d4EA4865bF0e83BcFafAA173 · https://elyratrade.io/abi/PushFeed.json - TSLA/USD: 0xD9B80933C2d2A3888ec8b9c3c49BE31bE9Ee8109 · https://elyratrade.io/abi/PushFeed.json ## The loop Diagram: One transaction, signed by the agent. Everything the agent reads comes from the Elyra site or the chain; everything it sends is signed with its own key and goes through any RPC. After the receipt, the next step starts again at Build. An approval and the call after it are two turns of the loop, or one eth_simulateV1 request that checks both before the first is signed. 1. Read: Addresses from the manifest, ABIs from `/abi`, and the state you need from view calls: `previewDeposit`, `maxDeposit`, `paused`, a pool's `slot0`, `Router.quoteExactIn`. 2. Build: Encode the call: `to`, `data`, `value` and chain id 99901. Set every minimum and deadline the function takes; the next sections say which. 3. Check: The `to` must be in the manifest or the chain constants, and an approval's spender must be the contract the next call goes to. Anything else is a mistake or an attack. 4. Simulate: An `eth_call` from your own address, or one `eth_simulateV1` request for an approval and the call that follows it. A revert here costs nothing. 5. Sign and send: With the agent's own key, through any RPC. Wait for the receipt before the next step. 6. Confirm: Read the receipt's events (`Swapped`, `ZapMint`, `Deposit`) rather than trusting the simulation's numbers. ## What an agent can call | Goal | Call | Approval first | Bound you set | | --- | --- | --- | --- | | Swap | `Router.swapExactIn(hops, amountIn, minAmountOut, to, deadline)` | The exact `amountIn` of the token to the Router. HYPE goes as `msg.value` equal to `amountIn`, with no approval | `minAmountOut`, `deadline` | | Unwrap WHYPE | `WHYPE.withdraw(amount)` | None | - | | One-token liquidity, Uniswap v3 | `ElyraZapV3.zapMint(params)`, or `zapIncrease` for a position you own | The exact `amountIn` to the zap | `minLiquidity`, `maxSlippageBps` (at most 5 000), `deadline` | | One-token liquidity, Uniswap v4 and Elyra pools | `ElyraZapV4.zapMint(params)` | The exact `amountIn` to the zap, which holds its own Permit2 allowances | Same as v3 | | Remove v3 liquidity | Uniswap's `NonfungiblePositionManager.decreaseLiquidity`, then `collect` (or both in one `multicall`) | None: you own the position NFT | `amount0Min`, `amount1Min`, `deadline` | | Deposit into an LP, hedged or structured vault | `deposit(assets, receiver)` (ERC-4626) | The exact `assets` to the vault | None on chain: read `previewDeposit` and `maxDeposit` first | | Withdraw from those vaults | `redeem(shares, receiver, owner)` | None | None on chain: read `previewRedeem` and `maxRedeem` first | | DLMM vault | `DlmmVaultZap.zapIn(params)`, `zapOut(params)` | The input token to the zap; for `zapOut`, the vault shares to the zap | `minSwapOut` and `minShares`, or `minOut`; `deadline` | | Stock vault | `StockVault.deposit(amount0Max, amount1Max, minShares, to, deadline)`, `withdraw(shares, to, amount0Min, amount1Min, deadline)` | Both tokens to the vault | `minShares`, the two minimums, `deadline` | ### Routes through the Router A route is up to three swap hops, each a `Hop` of a `kind` and its ABI-encoded `data`. The Router checks that the hops chain token to token (`routeTokens`) and treats HYPE and WHYPE as the same token. | `kind` | Hop | `data` | | --- | --- | --- | | 0 | A Uniswap v4 pool, Elyra's DAMM and stock pools included | `abi.encode(PoolKey, bool zeroForOne, bytes hookData)` | | 1 | An Elyra DLMM pair | `abi.encode(address pair, bool swapForY)` | | 3 | Wrap HYPE to WHYPE or unwrap WHYPE to HYPE; does not count toward the three | empty | Quote a route with `quoteExactIn(hops, amountIn)` through `eth_call`. It is not a view function: it runs each v4 hop and reverts with the result, so it costs nothing as a call and must never be sent as a transaction. Elyra's pools are listed under [Elyra pools](https://elyratrade.io/docs/pools) and how the app picks a route under [Swaps and routing](https://elyratrade.io/docs/swaps). ## The rules 1. **Exact approvals.** Approve the amount of this one call, to the contract that pulls it, never `type(uint256).max`. When a token already has a different non-zero allowance, set it to 0 first: some tokens refuse a change from one non-zero value to another. This is what the app does (`apps/web/lib/trade/approvals.ts`). 2. **A real minimum.** The zaps' `maxSlippageBps` is measured against the pool price inside the same transaction, so a price moved before yours moves that bound with it. `minLiquidity` is the only bound fixed when you sign: derive it from `previewZap` at a price you trust, less your slippage. The same goes for `minAmountOut` from a fresh quote. See [One-token deposits](https://elyratrade.io/docs/zap). 3. **Short deadlines.** Minutes, where a function takes one. ERC-4626 `deposit` and `redeem` take none, so a signed vault transaction stays valid until it is mined: send it at once, never hold it. 4. **Vault decimals.** LP, hedged and structured vault shares carry 3 more decimals than their asset (OpenZeppelin virtual shares). Read the vault's own `decimals()`, never the asset's. USDC has 6 decimals and EQX stock tokens have 8. 5. **Vaults can say no.** Deposits and withdrawals revert while the pool's spot price is more than 3 % from its 30-minute average (`TwapGuard`). A hedged vault pauses both when its last hedge report is over an hour old or its equity jumped more than 15 %; read `paused()`. A vault with a cap reports what it still takes in `maxDeposit`. See [Vaults](https://elyratrade.io/docs/vaults) and [Hedged vaults](https://elyratrade.io/docs/hedged-vaults). 6. **Check every address.** Before signing, the `to` of the transaction and the spender of every approval must appear in `/deployments/elysium.json` or `/deployments/elysium-external.json`. Many tokens on Elysium carry stock names; only the EQX addresses in the chain constants are the ones Elyra lists. 7. **Time is a timestamp.** On Elysium, `block.number` inside a contract returns the HyperEVM block number. Every deadline Elyra takes is in unix seconds. Warning: Vault deposits take no minimum An ERC-4626 `deposit` has no minimum-shares argument. The protection is the vault's TWAP guard, which refuses a deposit while the pool price is far from its 30-minute average, and the hedged vaults' pause. Compare `previewDeposit` with what you expect just before you sign, and send straight away. ## Simulating a sequence Most actions are two transactions: an approval, then the call that uses it. A plain `eth_call` of the second fails until the first is mined. `eth_simulateV1` runs calls in order inside one simulated block, so the second sees the first. Check that the RPC you use answers it; on a local fork, anvil does. ```json { "jsonrpc": "2.0", "id": 1, "method": "eth_simulateV1", "params": [ { "blockStateCalls": [ { "calls": [ { "from": "", "to": "", "data": "" }, { "from": "", "to": "", "data": "" } ] } ], "validation": false }, "latest" ] } ``` Each call comes back with a `status`, its `returnData` and `gasUsed`. A status of `0x1` on both means the pair would succeed against the current block. Simulate again right before you send: the chain moves. ## Agent starter kit A runnable example to start from: the [agent starter kit](https://elyratrade.io/examples/agent-quickstart/README.md), plain TypeScript with viem as its only dependency, served from this site. It runs the loop above end to end. It reads `/llms.txt` and the two deployment files and stops if they disagree about an address. It quotes native HYPE for USDC with `Router.quoteExactIn`, then plans a deposit of the swap's minimum output into a USDC vault from the manifest: the swap with a minimum and a deadline, an exact approval, and the deposit. It checks every `to` against the deployment files and simulates the three calls in one `eth_simulateV1` request. It signs and sends only with `--send`, one transaction at a time, with its own key. It runs against a local fork by default. On a fork with no key set, it makes a throwaway key and funds it, so there is nothing else to set up. Set `SITE` to the address of this site first: ```bash mkdir elyra-agent-quickstart && cd elyra-agent-quickstart for f in README.md quickstart.ts elyra.ts elyra.test.ts package.json tsconfig.json; do curl -fsSO "$SITE/examples/agent-quickstart/$f" done npm install anvil --fork-url https://rpc.elysium.kinetiq.xyz --chain-id 99901 --port 8549 # Foundry, in another terminal ELYRA_SITE="$SITE" RPC_URL=http://127.0.0.1:8549 npm start # read, quote, plan and simulate ELYRA_SITE="$SITE" RPC_URL=http://127.0.0.1:8549 npm run send # and send it, on the fork ``` On Elysium itself it needs the agent wallet's own key in its environment, and `--mainnet` as well as `--send`. The [README](https://elyratrade.io/examples/agent-quickstart/README.md) lists the variables and what to change first. ## Referrals for agent builders An agent built for other people can earn from their activity without touching their funds. Register a code once with `ReferralRegistry.register(bytes8 code)`. A user who calls `bind(code)` is tied to you for life, and 20 % of every protocol fee their activity pays goes to you, through `FeeRouter`. The share comes out of the protocol fee, not out of the user's trade. A binding can never be changed, so never bind a user who has not asked for it. See [Fees and referrals](https://elyratrade.io/docs/fees). ## Reading data The chain is the source of truth, and everything an agent needs before it signs is a view call: vault previews and limits, pool prices, `Router.quoteExactIn`, `ElyraZapV3.previewZap`, token balances and allowances. Multicall3 (in the chain constants) batches them. The app's own API serves ranked markets, vault and pool lists and a portfolio by address; its routes are listed in [Indexer, API and bots](https://elyratrade.io/docs/offchain). Treat them as beta: they are unversioned and follow what the app needs. ## Rate limits - **The files on this site** (`/llms.txt`, `/llms-full.txt`, `/deployments/*.json`, `/abi/*.json` and the starter kit) are static: built once per release and cached for five minutes. Read them when the agent starts, not on every call. - **The app's API** answers reads without a limit, from caches it refreshes every 15 seconds (pools, the market list) or 30 seconds (vaults, launches), so polling faster gains nothing. Its writes are limited to 30 a minute per route group and IP address, and the contact form to 5 a minute. Past a limit it answers `429` with `{ error, code: "rate_limited" }` and a `Retry-After` header in seconds. - **The chain.** The public RPC, `https://rpc.elysium.kinetiq.xyz`, keeps full history but rate-limits parallel calls, has no WebSocket and stops `eth_getLogs` at 10,000 results. Batch view calls with Multicall3, slow down on a `429`, and give an agent that reads a lot an RPC of its own. ## Not for agents, for now - **Perps.** A Hyperliquid order through Elyra is signed by the signer's agent wallet for a person using the app. An agent opens its own Hyperliquid account and trades through Hyperliquid's API with its own key or its own agent wallet. See [Perpetuals](https://elyratrade.io/docs/perps). - **Keeper enrolment.** `PositionKeeper` needs `setApprovalForAll` on the position manager, which covers every position the wallet holds. See [Position automation](https://elyratrade.io/docs/keeper). - **Launches and range orders.** App flows with their own rules; read [Launch a token](https://elyratrade.io/docs/launch) and [Limit orders](https://elyratrade.io/docs/range-orders) before calling those contracts. ## Coming next - **An MCP server.** A hosted tool server, over MCP and plain JSON, whose read tools answer market, vault, pool and portfolio questions and whose build tools return the transactions above as unsigned, simulated plans for your agent to sign. It will keep every rule on this page, and its address will appear in `/llms.txt` when it is live. - **Perps for agents.** Until they are live, perps stay an app flow: see [Not for agents, for now](#not-for-agents-for-now). Where it lives: - `apps/web/lib/agents/llms.ts`: buildLlmsTxt and buildLlmsFullTxt: the agent index and the full text - `apps/web/lib/agents/contracts.ts`: contractTable and ABIS: every deployed contract with the ABI to call it - `contracts/src/venue/periphery/Router.sol`: swapExactIn, quoteExactIn, routeTokens and the hop kinds - `contracts/src/ElyraZapV3.sol`: zapMint, zapIncrease, previewZap and MAX_SLIPPAGE_BPS - `contracts/src/LPVault.sol`: the ERC-4626 vault, its TWAP guard and SHARE_DECIMALS_OFFSET - `contracts/src/venue/vaults/DlmmVaultZap.sol`: zapIn and zapOut with their minimums - `contracts/src/venue/stockvaults/StockVault.sol`: deposit and withdraw with their minimums - `apps/web/lib/trade/approvals.ts`: exact approvals and the reset to 0, as the app does them --- # Glossary Source: https://elyratrade.io/docs/glossary · Reference The terms these docs use, each in a sentence or two, with a link to where it is explained. The words below come up across these docs. Each entry says what the term means in Elyra, in a sentence or two, and points to the chapter that explains it properly. Numbers are the values the contracts enforce today; where a value is set at deploy time, the linked chapter names the constant. ## Chain and tokens **Elysium.** Kinetiq's chain beside Hyperliquid, an Arbitrum Orbit chain that settles to HyperEVM, chain id 99901. Every Elyra contract is deployed there. See [Introduction](https://elyratrade.io/docs/overview). **EQX stock tokens.** Tokenised stocks bridged to Elysium from HyperEVM, with 8 decimals: EQNVDA, EQTSLA, EQSPY, EQQQQ, EQAAPL, EQMETA and EQSPCX. Only the addresses in Elyra's chain config count; other tokens with stock names do not. See [Elyra pools](https://elyratrade.io/docs/pools). **HYPE and WHYPE.** HYPE is Elysium's gas token; WHYPE is its wrapped ERC-20 form, which pools and vaults hold. The Router treats the two as one asset and wraps or unwraps as a route needs. **Price feed.** Elyra's own keeper-updated price contract for a stock or for HYPE, read through the AggregatorV3 interface. Its keeper moves it at most 15 % an hour; the owner writes a larger genuine gap. Elysium has no third-party oracle network, so stock pools, stock vaults and the pre-market perp read these. See [Elyra pools](https://elyratrade.io/docs/pools). **USDC.** The dollar stablecoin on Elysium, with 6 decimals: the main quote asset of Elyra's pools, the margin of the pre-market perp, and the collateral of a Hyperliquid account. ## Trading **Agent wallet.** A trade-only key your wallet approves once for your Hyperliquid account. The signer service holds it for you; it can place and cancel orders and cannot withdraw or transfer. See [Perpetuals](https://elyratrade.io/docs/perps). **Builder fee.** Elyra's fee on Hyperliquid perps: a charge each order names, up to the maximum your wallet approved, collected by Hyperliquid with the trade. See [Perpetuals](https://elyratrade.io/docs/perps#elyra-s-builder-fee). **Carry.** What a hedged position earns per year before price moves: the pool's fee APR plus the perp funding a short receives (hourly funding × 8 760), minus any borrowing cost. Elyra flags carry of 8 % or more as worth watching and 20 % or more as strong. See [Using the app](https://elyratrade.io/docs/app-guide#markets). **Funding.** The periodic payment between longs and shorts that keeps a perp's price near its index. Positive funding means longs pay shorts. Hyperliquid settles it hourly; on the pre-market perp it settles hourly and is capped at 1 % per hour. See [Perpetuals](https://elyratrade.io/docs/perps#funding-history). **Hedge.** A liquidity position paired with a perp short sized to the position's delta, so price moves on the two legs roughly cancel and the fees remain. The Planner models it next to holding, providing liquidity and a plain perp. See [Hedged vaults](https://elyratrade.io/docs/hedged-vaults). **HIP-3 market.** A perp market deployed on Hyperliquid by a third party. Stock perps are HIP-3 markets on the `xyz` dex, named with its prefix: `xyz:NVDA`, `xyz:SP500`. See [Perpetuals](https://elyratrade.io/docs/perps#stock-perps). **Hop.** One leg of a swap route: a v4 pool, a DLMM pair, or a wrap or unwrap of HYPE. The Router accepts at most three swap hops per trade. See [Swaps and routing](https://elyratrade.io/docs/swaps). **Idea.** A position published with the argument for it and its running PnL. Mirroring an idea opens the same kind of position at your own size. See [Using the app](https://elyratrade.io/docs/app-guide). **Limit order.** On Elyra, a one-sided liquidity position placed entirely above or below the price. It converts into the other token as the price crosses it and earns swap fees while it waits. See [Limit orders](https://elyratrade.io/docs/range-orders). **Price impact.** How much worse a route's rate is than the rate for a tiny trade on the same hops. The Swap page warns above 1 %, asks you to confirm above 5 % and refuses at 15 %. See [Swaps and routing](https://elyratrade.io/docs/swaps). **Slippage.** The most the output may fall short of the quote before the transaction reverts. You set it per trade; the app turns it into a minimum amount out. ## Liquidity **Active bin.** The one bin of a DLMM pair that holds both tokens. Swaps fill there at a fixed price until it runs out, then move to the next bin. See [Elyra pools](https://elyratrade.io/docs/pools). **Anti-snipe fee.** A fee that starts high when a pool opens and falls in a straight line to the base fee over a set time, at most one hour. It makes buying the first blocks of a launch expensive. See [Launch a token](https://elyratrade.io/docs/launch). **Bin and bin step.** A DLMM pair splits its price range into discrete bins. The bin step is the price distance between neighbouring bins, in basis points: 1 to 100 bps. See [Elyra pools](https://elyratrade.io/docs/pools). **DAMM.** A Uniswap v4 pool on Elyra's `DammHook`. Its fee is a base rate plus a surcharge that rises with recent price movement, with an optional anti-snipe schedule at the start. See [Elyra pools](https://elyratrade.io/docs/pools). **DLMM.** Elyra's bin-based pair (`DlmmPair`): liquidity sits in discrete price bins and each bin trades at one exact price. See [Elyra pools](https://elyratrade.io/docs/pools). **Harvest.** Collecting a position's earned swap fees, and on a vault or an automated position, adding them back as liquidity. A harvest pays 10 % of the fees it collects to the protocol, never any principal. See [Position automation](https://elyratrade.io/docs/keeper). **Range.** The price interval a concentrated liquidity position is active in, written as two ticks. Outside it the position holds one token only and earns nothing. See [One-token deposits](https://elyratrade.io/docs/zap). **Rebalance.** Withdrawing a position that has drifted out of range and opening a new one centred on the current price, inside limits on slippage and timing. See [Position automation](https://elyratrade.io/docs/keeper). **Shape.** How a DLMM deposit is spread over its bins: evenly (Spot), concentrated near the price (Curve), or weighted towards the edges (Bid-Ask). See [Elyra pools](https://elyratrade.io/docs/pools). **Stock pool.** A v4 pool on `StockHook` for an EQX stock token. Every swap must leave the price inside a band around Elyra's feed price, and the band and fee change with the market session. See [Elyra pools](https://elyratrade.io/docs/pools). **Zap.** One transaction that takes a single token, swaps the part the range does not need, mints the position and refunds what is left. It charges 25 bps of the input. See [One-token deposits](https://elyratrade.io/docs/zap). ## Vaults and notes **Deposit cap.** The deposit limit a vault is created with. It can never be changed. The vaults Elyra deploys and the graduated vaults have none, so they take deposits of any size. See [Vaults](https://elyratrade.io/docs/vaults). **Equity jump.** On a hedged vault or an Income note, a report more than 15 % away from the hour's anchor. The report is recorded as said, but the vault believes it only up to the band's edge and walks the rest in at 15 % an hour. Deposits wait until the two figures agree; exits never wait and count the lower one. See [Hedged vaults](https://elyratrade.io/docs/hedged-vaults). **ERC-4626.** The standard interface for tokenized vaults: you deposit an asset and receive shares; your shares' value follows the vault's total assets. **Funder.** The cold key that owns a hedged vault's Hyperliquid account. It alone can take margin out of the vault, to its own address and under caps. See [Hedged vaults](https://elyratrade.io/docs/hedged-vaults). **Sleeve.** One part of a structured note's capital: the LP sleeve, and either a reported perp long (Income) or a reserve token (Protected). See [Structured notes](https://elyratrade.io/docs/structured). **Stale report.** A hedge or sleeve report older than one hour. Until a fresh one arrives, deposits wait and exits count the hedge at zero. See [Hedged vaults](https://elyratrade.io/docs/hedged-vaults). **TWAP guard.** The check every vault and the keeper run before moving value at a pool's price: the spot price must be within 3 % of its 30-minute average, and that average must cover at least 10 minutes of real history. A single manipulated block cannot mint or redeem at a false price. See [Vaults](https://elyratrade.io/docs/vaults). ## Launch **Graduation.** Turning a tracked token into a vault once it is at least three days old and its pools hold enough liquidity. Anyone can call it once the conditions are met. See [Graduation and pre-market perps](https://elyratrade.io/docs/graduation). **Launch pool.** The locked HYPE pool `LaunchPools` creates with a new token in one transaction. Its seed liquidity can never be removed; only its fees can be collected. See [Launch a token](https://elyratrade.io/docs/launch). **Pre-launch vault.** A vault that collects HYPE before a token exists and spends all of it as the new pool's first swap, so every depositor pays the same average price and nobody can trade ahead of them. See [Launch a token](https://elyratrade.io/docs/launch). **Pre-market perp.** A perp on a virtual AMM for a token no venue lists yet: USDC margin, up to 3x, hourly funding. See [Graduation and pre-market perps](https://elyratrade.io/docs/graduation). **Seasoned.** A screener label for a token whose pool is at least three days old, whose market cap is above $1 million, and which traded at least 100 times in the last 24 hours. It is set off chain, tells the graduator bot which tokens to work on, and is not a condition any contract checks. See [Graduation and pre-market perps](https://elyratrade.io/docs/graduation). ## Protocol **Bounty.** A payment to whoever calls a permissionless function, such as a harvest, a limit-order fill or a liquidation. It covers the caller's gas and is not protocol revenue. See [Fees and referrals](https://elyratrade.io/docs/fees). **Keeper.** Any account that calls Elyra's permissionless maintenance functions for the bounty. Elyra runs one as a bot; nothing stops anyone else from doing the same. See [Indexer, API and bots](https://elyratrade.io/docs/offchain). **$ELYRA.** Elyra's token. Protocol fees are converted to HYPE, which buys $ELYRA and sends it to the burn address. See [Buyback and burn](https://elyratrade.io/docs/protocol). **Protocol share.** The part of every Elyra pool's swap fee that goes to the `FeeCollector`: 20 % at deploy, and never more than 50 %. Liquidity providers keep the rest. See [Elyra pools](https://elyratrade.io/docs/pools). **Referral share.** 20 % of every protocol fee that passes through the `FeeRouter`, credited to the payer's referrer when one is registered. See [Fees and referrals](https://elyratrade.io/docs/fees). Where it lives: - `packages/core/src/basis.ts`: the carry formula and its two thresholds - `packages/core/src/established.ts`: the Seasoned label - `contracts/script/ElyraWiring.sol`: the values set at deploy time