> This is part 1 of 2 of the full documentation (pages 1–100 of 128).
> The content is paginated: fetch every part to see all of it.
> Next part: https://docs.valantis.xyz/llms-full.txt/1
> Page index: https://docs.valantis.xyz/llms.txt

# What is Valantis?

Explore Liquid Staking and Smarter Trading.

## Our Thesis

Hyperliquid is valuable real estate, staked HYPE is essential to powering its economy, and an intelligently designed Staking Protocol is well positioned to become the sink of this value.

Valantis was founded in 2023 with a single mission: build liquidity systems that exploit the superpowers of crypto composability. We began in the early years by building propAMMs on Ethereum before propAMMs had a name. We came to Hyperliquid because we understood the vision of CoreWriter.

stHYPE is the first LST on Hyperliquid and is much larger than just a liquid staking protocol. stHYPE tokenizes the utility of HYPE, which is much more unique than traditional PoS economies. stHYPE earns revenue and powers HIP-3 Exchanges, HIP-4 Exchanges, Trading Margin, Staking Discounts, Vaults, Market Makers, and much more.

## Get Started

**Hyperliquid Traders:**

* Access up to 40% Spot/Perps [Fee Discounts](/prime/discounts) Today.
* Trade on HyperCore [Prime Terminal](/prime/terminal).
* Learn how [Valantis Prime](/prime) can help you trade smarter.

**Liquidity Providers (LPs):**

* Stake with [stHYPE](/stakedhype).
* Learn about the advantages of being a [STEX LP](/amms-and-vaults/staked-amm).
* Deposit [via the Valantis App.](https://app.valantis.xyz/)
* Swap on EVM [via the Valantis App.](https://app.valantis.xyz/swap)
* Integrate Valantis DEX Liquidity [via contracts.](/amms-and-vaults/staked-amm/integration)


# stHYPE

A liquid staking network for Hyperliquid's economy.

{% hint style="info" %}
Hyperliquid and stHYPE are evolving. Features and use cases may change as the network develops.
{% endhint %}

## Liquid Staking

Liquid staking lets you earn staking rewards while keeping your capital available:

* Access HYPE before native unstaking completes when liquidity is available: through stHYPE’s no-fee instant-redemption queue or an AMM swap at the available rate and fees.
* Borrow USDC against your staked assets to free up margin while continuing to earn yield on your long-term holdings.

Deposit HYPE and receive stHYPE, a token representing your stake that you can trade or use across DeFi while the underlying HYPE supports the network.

### stHYPE is more than vanilla Liquid Staking

On most networks, staking is a way to earn yield for providing *Network Security*. On Hyperliquid, staking is a much more expansive system driving incentive alignment across its financial stack:

* Staking lowers Trading Fees through Staking Tier Discounts.
* Staking lowers Trading Latency through Foundation Peering Stake Requirements.
* Staking unlocks perps market deployments through HIP-3.
* Staking unlocks binary outcomes and scalar options deployments through HIP-4.

stHYPE makes all of this liquid:

* [Valantis Prime](/prime/discounts) enables users to borrow against stHYPE while retaining staking fee discounts.
* [Restaking](/stakedhype/restaking) turns HYPE's utility into extra yield sources for stakers by powering HIP-3 and HIP-4 deployers.

stHYPE is turning HYPE's central role on the Hyperliquid blockchain into a liquid marketplace: Holders can earn higher yield than native staking through restaking, Traders and users who want to access the utility of staked HYPE can do so with all the benefits of liquidity brought by liquid staking.

### Why stake with stHYPE

* **Productive capital:** Earn staking rewards while using stHYPE as collateral across supported DeFi markets.
* **Access to liquidity:** Exit through available liquidity without waiting for the full unstaking period, subject to liquidity and fees.
* **Extra Yield:** Connect HYPE holders with demand from traders and builders, holders earn more yield by unlocking the utility behind their HYPE.


# Understanding stHYPE

The stake accounts stHYPE uses on HyperCore, what each kind earns and gives up, and how withdrawals are served.

## Understanding stHYPE

stHYPE LST is a single unified Staking Protocol that coordinates several Stake Accounts on HyperCore.

**Fast-withdraw Stake Accounts** hold most of the protocol assets, optimized for throughput. These CoreWriter-enabled smart contracts can process up to twenty-five concurrent withdrawals, giving stHYPE higher unstaking throughput than competing LST protocols. Competing LST's five-concurrent-withdrawal limit creates delays between a user’s withdrawal request and the corresponding HyperCore unstake; stHYPE minimizes this delay to bring faster unstake times.

**Deployer Stake Accounts** are built to earn more by supporting Deployers. These Stake Accounts have slow withdrawal capacity, but help stHYPE's system earn higher than native staking yield by supporting deployers. These accounts are under stricter security over-sight (staked assets only moved under timelock); as their operations introduce Deployer Slashing Risk. All Deployer Accounts and associated risks are documented below. Deployer Account withdrawal-times are tracked in the Time-to-Cash Liquidity Waterfall.

**Valantis Prime Stake Accounts** are built to power cheaper trading. When stHYPE holders open a new Trading-Discount account; a new isolated Prime Stake Account is created by the stHYPE Protocol, and an equivalent amount of Native Stake owned by the stHYPE Protocol is moved there. This is what allows Prime to be fully self-custodial, and ensure Traders balances are never mixed or co-mingled with others.

{% hint style="info" %}
**Current status.** The USDe quote-asset module is the only active deployer stake account. The Ethena HyENA HIP-3 allocation is deprecated. The proposed HIP-4 deployer is not live.
{% endhint %}

Every account can only stake to HyperCore. None of them lend or rehypothecate.

### Accounts

* **Fast-withdrawal stake accounts (5)**
  * [Account 1](https://hyperevmscan.io/address/0x591540F231055743A37F691C3ffd50E4E53561ab)
  * [Account 2](https://hyperevmscan.io/address/0x16a4814e8eb502C56CeBD73f9c8AC7fDeE29C042)
  * [Account 3](https://hyperevmscan.io/address/0xf992Aa323eC183733213f874b6322B8bD1Aad625)
  * [Account 4](https://hyperevmscan.io/address/0x06b5659F16110319137220d1efd680053f5e72a2)
  * [Account 5](https://hyperevmscan.io/address/0xE787DD1347a29e6807d164C4Fa43105B64048556)
* **Deployer stake accounts (1)**
  * [Quote Asset Deployer Staking Module](https://hyperevmscan.io/address/0x358E783C32147B344a1168e0984D3350DE4e07cB) (USDe)
* **Prime stake accounts (>250)**

### Withdrawals

There is no fee to withdraw. In normal conditions a withdrawal targets about 7 days, and [the app](https://app.valantis.xyz/staking?tab=withdraw) shows an estimate for your amount before you confirm.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-fc943e1085ff296f837773c60514c0a1a34864f4%2Festimate_unstake_times.png?alt=media" alt="Estimated unstake times in the app for different withdrawal sizes"><figcaption><p>The estimate depends on the amount and on recent deposit flow.</p></figcaption></figure>

In normal conditions withdrawals are paid from two sources:

* **New deposits.** Every new HYPE deposit settles queued withdrawals before anything is staked, and the contracts enforce this. When deposits are flowing, withdrawals can settle faster than native unstaking.
* **The five standard accounts.** HyperCore allows one account five concurrent unstake requests and imposes a 24-hour lock after each re-delegation. Five accounts give stHYPE 25 concurrent unstakes and room to move stake between validators.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-5b354c9d23240e159c57ffe14160eb9d6e0ddc0a%2FGraphic%20B%20_%20Version%201.png?alt=media" alt="Five standard stake accounts running unstakes in parallel"><figcaption><p>Five standard accounts run unstakes in parallel, 25 at a time.</p></figcaption></figure>

### Large unwinds

* **Instant-redemption queue first.** The protocol targets approximately 10,000–50,000 HYPE in its instant-redemption queue, adjusted for market conditions. Actual available liquidity can be lower during withdrawals. [Dynamic Instant-Queue Announcement](https://x.com/stakedhype/status/2102002590586392987?s=20).
* **Fast-withdrawal accounts next.** When the Instant-redemption queue is empty, withdrawals are processed out of the fast-withdrawal accounts at unchanged capacity until those accounts are empty. Incoming deposits can settle queued withdrawals sooner, depending on deposit volume and the requests ahead in the queue.
* **Early recall from deployer accounts.** When fast-withdrawal and Valantis Prime stake accounts hold less than 10% of protocol funds, the protocol begins recalling deployer stake. Early recall prepares for liquidity pressure. Withdrawal timing still depends on available liquidity, queue demand, and each allocation’s release terms.
* **Withdrawals processed from deployer accounts.** When fast-withdrawal stake accounts are empty, remaining withdrawals may depend on stake committed to deployers. The documented recall periods range from 30 to 183 days; actual availability also depends on each allocation’s release conditions and the applicable HyperCore withdrawal process.

{% embed url="<https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-11e0c824311b84e9c5a44a3617ec838833de349b%2Fsthype-withdrawal-times-vs-tvl.mp4?alt=media>" %}

Prolonged withdrawals remain possible if requests exceed what the standard accounts and new deposits can absorb. Restakers share these delegation-related withdrawal constraints with ordinary stHYPE holders, with an additional cooldown before claiming stHYPE.

## Slashing

Slashing is defined on Hyperliquid under validator quorum: [HIP-3 and HIP-4 rules](/stakedhype/restaking/deployer-stake) [Quote-Asset rules](https://hyperliquid.gitbook.io/hyperliquid-docs/hypercore/permissionless-spot-quote-assets)

Deployer Stake accounts health is reported quarterly in [stHYPE Health Reports](/stakedhype/transparency-and-risks).

Live monitoring of Deployer Stake Accounts can be found at app.valantis.xyz/restaking

Which deployers receive stake, and how much, is decided through the Deployer Curation Process. [Restaked stHYPE](/stakedhype/restaking) is designed to be the capital that backs those commitments.


# Restaking

Restake stHYPE into one shared pool to earn committed engagement rewards alongside base staking yield, with a 14-day withdrawal cooldown.

Restaking lets stHYPE scale to power multiple high-revenue activities on Hyperliquid-- across Fee Discounts, HIP-3, and HIP-4. Restaking intends to become the largest multipurpose basket of HYPE that creates liquidity to Deployer deals, and market maker allocations. Using pooled resources, and stHYPE's liquidity design, restaking becomes the a one-of-a-kind instrument to earn extra yield on HYPE.

**Why Restaking was built**

Restaking takes a portion of stHYPE TVL out of liquid circulation: not allocated to user prime discounts, not borrowed against on lending markets, not exposed to DeFi. This increases the capacity stHYPE Protocol has to allocate to high-value use cases without risking it's DeFi integrations by protecting the liquidity of liquid stHYPE. Restakers accept a withdrawal cooldown in exchange for committed rewards. This design does not eliminate withdrawal delays or the underlying risks of stHYPE; it concentrates liquidity risk to restakers and out of DeFi.

**How to restake**

Deposit stHYPE into the shared restaking pool. Your base staking yield continues, and your active position earns its share of rewards committed to the pool. A withdrawal request starts the current 14-day cooldown. stHYPE is returned at the end of that cooldown, converting to HYPE requires an additional swap or normal unstake process. Importantly, a withdrawal from restaking continues to earn base Staking Rewards while it is in the queue, and is cancellable at any time.

Before restaking, understand stHYPE’s commitments and the circumstances that can cause [slashing](https://docs.valantis.xyz/stakedhype/transparency-and-risks#key-risk-areas) or extend withdrawal times. Review the liquidity waterfall, deployer commitments, and estimated time to cash on the [live restaking dashboardsvg](https://app.valantis.xyz/restaking). Risks and liquidity are reviewed and audited quarterly in the [stHYPE Health Reports](https://docs.valantis.xyz/stakedhype/transparency-and-risks#sthype-health-reports).

Read the audit here: [stHYPE Restaking Audit](https://github.com/ValantisLabs/audits/blob/main/stakedhypeescrow-security-review-2026-10-18.pdf).

Deployer rewards are publicly disclosed at Stake Accounts: they can be HYPE premiums, token incentives, points, or revenue share. Restaking escrow contract follows a trackable yield distribution where rewards are pre-committed for the week, so restakers can see what has been committed when deciding to restake.


# How to Restake

Deposit stHYPE, track your restaking rewards, and withdraw when you are ready.

Restake stHYPE to earn a share of the rewards committed to the restaking pool alongside your base staking yield. One deposit gives you a position in the shared pool; you do not need to select individual deployers.

The tradeoff is access to your funds: withdrawing requires a 14-day cooldown, followed by a separate claim.

## Before you start

* **Have stHYPE on HyperEVM**, plus a little HYPE for network fees. Need stHYPE? [Stake HYPE in the app](https://app.valantis.xyz/staking), or follow the [buying and staking guide](/resources/get-hype-on-hyperevm).
* **Plan for a 14-day cooldown.** It starts when you request a withdrawal, not when you deposit.
* **Know what changes.** Your validator stays the same, but restaked stHYPE does not count toward your Prime Trading discount. Yield is variable, and restaking adds liquidity risk.
* **Review contract security.** Read the [stHYPE Restaking Audit](https://github.com/ValantisLabs/audits/blob/main/stakedhypeescrow-security-review-2026-10-18.pdf).
* **Allow for wallet confirmations.** The deposit flow includes two wallet transactions. There is no deposit or withdrawal fee; network fees still apply.

{% hint style="info" %}
The screenshots are interface previews. Amounts, APYs, and dates are examples; check the terms displayed in the app before confirming.
{% endhint %}

## Restake your stHYPE

### 1. Enter your amount

Open [stHYPE Restaking](https://app.valantis.xyz/restaking), connect your wallet on HyperEVM, and select **Deposit**. Enter an amount of stHYPE, or select **Max** to use your available stHYPE balance.

**Potential Yield / Year** estimates your deposit multiplied by the current annual percentage yield (APY). It is a projection, not a promised return. Select **Review deposit** to continue.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-73261175a486651d53eb67f2563bf5494d7f526b%2F02-deposit-enter-amount.jpg?alt=media" alt="Deposit tab with the stHYPE amount field, Max option, annual yield estimate, and Review deposit button."><figcaption><p>Enter the amount you want to restake and review its estimated yield.</p></figcaption></figure>

### 2. Review and confirm

Check your amount, estimated APY, fees, and withdrawal terms. Select **Confirm deposit**, then review and confirm the transactions in your wallet.

Wait for **Deposit successful** before moving on. Your deposited stHYPE now participates in the pool’s committed rewards alongside base staking yield.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-2796204be0ff20857b8c962b94a04ba89d71868c%2F04-deposit-review.jpg?alt=media" alt="Review deposit panel showing the amount, variable APY, fee, unchanged validator, withdrawal commitment, and Confirm deposit button."><figcaption><p>Read the withdrawal and Prime Trading discount terms before confirming.</p></figcaption></figure>

### 3. Find your position

Open **Positions**, then **Active**. Look for **stHYPE Restaking** to see your position and its current APY. Select **Manage** when you want to make changes.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-09c589e98064017e47ff85e1fad8a54b90aa548e%2F06-positions-active.jpg?alt=media" alt="Positions page with Active selected and a stHYPE Restaking row showing APY, position size, and Manage."><figcaption><p>Your restaking position appears under Active.</p></figcaption></figure>

## Withdraw your stHYPE

Withdrawing has three stages: **request, wait, claim**. You receive stHYPE. It is not sent to your wallet automatically when the cooldown ends.

### 1. Request a withdrawal

On the stHYPE Restaking page, select **Withdraw**. Enter the amount you want to withdraw, then select **Review withdrawal**. You can withdraw part of your position.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-0165463b352fbcb2d34584e2fac3dcee31a9d49b%2F08-withdraw-enter-amount.jpg?alt=media" alt="Withdraw tab with an amount field, cooldown explanation, cancellation information, and Review withdrawal button."><figcaption><p>Choose how much stHYPE to withdraw.</p></figcaption></figure>

### 2. Start the 14-day cooldown

Check the amount and **Claim available** date. Select **Start 14-day cooldown** and confirm the transaction in your wallet.

Once the request is confirmed, that amount stops earning restaking rewards but keeps earning base staking yield. Any amount you leave in the active position continues earning restaking rewards.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-405ab28f5bf4a6625bd8263441f4805d02b83709%2F09-withdraw-review.jpg?alt=media" alt="Review withdrawal panel with the amount, cooldown, claim date, and button to start the cooldown."><figcaption><p>Note your claim date: you will need to return to claim.</p></figcaption></figure>

### 3. Claim after 14 days

Open **Positions**, then **Pending**. When your withdrawal shows **Ready to claim**, select **Claim** and confirm in your wallet. Wait for the confirmation that your stHYPE is back in your wallet.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-fe2103676e3d5522c4d72e83170afd8812c09bba%2F11-claim-ready.jpg?alt=media" alt="Pending tab with a stHYPE Restaking withdrawal marked Ready to claim and a Claim button."><figcaption><p>Claim returns the withdrawn stHYPE to your wallet.</p></figcaption></figure>

### Changed your mind?

Before the cooldown ends, open **Positions**, find the pending withdrawal, and select **Manage → Cancel withdrawal**. Review the cancellation and confirm in your wallet. The amount returns to your restaking position and resumes earning restaking rewards.

After the cooldown ends, claim your stHYPE and deposit it again to restake.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-a6c465d5c9cc5839a3253ebad52e4fa101bc64d0%2F13-cancel-withdrawal.jpg?alt=media" alt="Cancel withdrawal dialog showing the amount returning to the restaking position, network fee, and Cancel withdrawal button."><figcaption><p>Cancelling returns the amount to your active position.</p></figcaption></figure>

## Want HYPE back?

Once you have claimed your stHYPE, you can swap it for HYPE at the available market rate or [unstake it](/stakedhype/stake-accounts#withdrawals). Ordinary unstaking targets about seven days in normal conditions, in addition to the restaking cooldown. It can take longer when stake must be recovered from deployers.

Cooldown changes and protocol pauses can affect when withdrawals become claimable.


# Rewards

One restaking position earns a share of rewards committed to the shared pool, without selecting individual deployers or making a separate commitment to each allocation. These rewards supplement base stHYPE staking yield; current commitments are shown at [app.valantis.xyz/restaking](https://app.valantis.xyz/restaking). The underlying allocations are listed in [Stake Accounts](/stakedhype/stake-accounts).

Any extra yield not committed to the restaking pool may, at Valantis’ discretion, be distributed to all stHYPE holders through rebases to raise base yields or retained for protocol operations, growth, and revenue.

## Current Restaker Rewards

This is current committed liquidity after any fees applied, what restakers realize. These numbers can change in the future.

| Yield source                                 | Reward                       | Status            |
| -------------------------------------------- | ---------------------------- | ----------------- |
| USDe Quote Asset                             | 10 HYPE per day              | Active            |
| HIP-4 deployer (not live)                    | 40 HYPE per day              | Pending liquidity |
| Trading Fee Discount Market Maker (not live) | Estimated 20–50 HYPE per day | Coming soon       |

{% @valantis-restaking-yield/calculator-card content="revision-4" %}


# Background: Deployer Stake

Hyperliquid deployer stake requirements, release conditions, and slashing risks for HIP-3 and HIP-4.

HIP-3 supports builder-deployed perpetual markets. HIP-4 supports outcome markets with defined settlement conditions. Both require deployers to commit stake and accept responsibility for valid market operation. Stake requirements, release conditions, and slashing rules determine when an allocation can become available for withdrawals and what can threaten its value.

The following summarizes how Hyperliquid defines HIP-3 and HIP-4 mechanics, as they relate to the stHYPE Protocol and LP risk.

Any deployer markets supported by stHYPE will be listed in [Stake Accounts](/stakedhype/stake-accounts), as well as viewable live at [app.valantis.xyz/restaking](https://app.valantis.xyz/restaking).

## What can put deployer stake at risk

For **HIP-3**, validator-elected slashing addresses irregular deployer inputs that threaten valid execution, availability, or performance, including attempted exploits. Compromised keys or good intentions do not excuse their technical effects. Cross-margin markets carry additional oracle, liquidity, and manipulation requirements. Penalties can reach the entire stake, which remains slashable during the unstaking queue. Slashed HYPE is burned rather than paid to affected stHYPE holders. [HIP-3 slashing rules](https://hyperliquid.gitbook.io/hyperliquid-docs/hyperliquid-improvement-proposals-hips/hip-3-builder-deployed-perpetuals#slashing).

For **HIP-4**, market definition and resolution are central risks. Hyperliquid's published slashing framework covers poorly defined markets, settlement inconsistent with the selected template, and incorrect failure to settle for more than a week. The current API also identifies violations of template semantics as slashable. Review therefore needs to cover what the outcome means, how it is established, and who can settle it correctly and on time. [HIP-4 published framework](https://t.me/hyperliquid_announcements/575), [deployer actions](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/hip-4-deployer-actions).

These risks remain relevant to all stHYPE holders. The restaking framework changes who accepts withdrawal delays; it does not exempt the underlying stake from Hyperliquid's penalties.

## Stake Commitment period

HIP-3 and HIP-4 follow the same stake requirements and minimum commitment period, but are independent deployments that cannot reuse the same stake.

500,000 HYPE is required to deploy one DEX. A DEX can contain several markets. For HIP-3, the first three market listings do not require auction participation; additional listings use the auction process.

> `xyz`, `io`, `para`, `mkts`, `flx`, `vntl`, and `cash` are examples of deployer DEXes; `TSLA-USDC` and `US500-USDC` are examples of markets.

The 500,000 HYPE is locked by Hyperliquid L1 for 183 days after the initial DEX deployment. The stake can be released after the initial 183 days have passed and all markets are settled.

For HIP-3, the DEX-creating registration is the `perpDeploy` action with `registerAsset2` and a new DEX `schema`. For HIP-4, registration uses the `activate` variant of `activateOutcomeDeployer`. Individual HIP-4 markets are created through `outcomeDeploy`, separate from the registration action that starts the 183-day timelock.

After 183 days since deployment, the DEX can wind down and unstake its HYPE once no markets are active, with no further deployer commitment period. Unstaking then follows the normal process, including the seven-day staking-to-spot queue.

The stHYPE Protocol defines a 30-day rolling recall period on deployer accounts after the initial 183-day period. This gives deployers time to settle markets or find replacement stake without major disruption to traders on these markets.

## Relevant links

* [HyperCore staking](https://hyperliquid.gitbook.io/hyperliquid-docs/hypercore/staking)
* [HIP-3 specification](https://hyperliquid.gitbook.io/hyperliquid-docs/hyperliquid-improvement-proposals-hips/hip-3-builder-deployed-perpetuals)
* [HIP-3 deployer actions](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/hip-3-deployer-actions)
* [HIP-4 overview](https://hyperliquid.gitbook.io/hyperliquid-docs/hyperliquid-improvement-proposals-hips/hip-4-outcome-markets)
* [HIP-4 deployer actions](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/hip-4-deployer-actions)
* [HIP-4 stake requirement announcement](https://t.me/hyperliquid_announcements/575)
* [HIP-4 mainnet announcement](https://t.me/hyperliquid_announcements/585)


# Restaking Integration

SHE deposits, withdrawals, rewards, and manager permissions.

[stHYPE Restaking Audit](https://github.com/ValantisLabs/audits/blob/main/stakedhypeescrow-security-review-2026-10-18.pdf)

`StakedHypeEscrow` (SHE) holds wstHYPE in one shared pool. Active positions earn funded restaking premiums alongside ordinary stHYPE staking rewards. To exit, request a withdrawal, wait through the cooldown, then claim wstHYPE.

Restaking builds on the existing stHYPE protocol. SHE manages the restaking cooldown and rewards. Its purpose is to improve liquidity for non-restaked stHYPE in DeFi while supporting more revenue-generating stake allocations.

The existing stHYPE protocol handles stake allocation, HyperCore operations, and recalls to HyperEVM. Learn how these operations work in [Stake Accounts](/stakedhype/stake-accounts), and review their health in [Transparency and Risks](/stakedhype/transparency-and-risks).

## Your position

Restaked positions are not tokenized or transferable.

`account(owner)` returns active ownership units, raw stHYPE shares, and wstHYPE base units. Pending withdrawals are separate. To display the active stHYPE balance, pass the returned raw shares to `sharesToBalance(rawShares)` on the [stHYPE token contract](https://hyperevmscan.io/address/0xfFaa4a3D97fE9107Cef8a3F48c069F577Ff76cC1#code). Do not pass ownership units directly.

Transferring stHYPE or wstHYPE to SHE without calling `deposit` does not create a position. These transfers become donations to active balances or retained reward reserves when no user units remain. SHE's token-rescue function cannot recover these donations.

## Deposit and withdrawal functions

| Function                                                                              | What it does                                                                                                                                                                                                                                             |
| ------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `deposit(maxAmountWstHype, beneficiary, minOwnershipUnits, minAmountWstHypeAccepted)` | Accounts for accrued rewards, calculates pool ownership, and transfers only the accepted wstHYPE. Credits the beneficiary; unaccepted tokens stay with the payer. Reverts if minimums are not met or SHE is paused.                                      |
| `requestWithdrawal(ownershipUnits, minRawShares)`                                     | Removes the requested units from the owner's active position. Reserved shares stop earning restaking premiums but retain base staking yield and slashing exposure. Sets `eligibleAt = requestedAt + cooldown`. Multiple concurrent requests are allowed. |
| `cancelWithdrawal(requestId, minOwnershipUnits)`                                      | The owner can cancel a pending request before or after maturity. Shares return to the active pool at its current price. The request is marked cancelled; a later exit requires a new request and cooldown. Missed premiums are not restored.             |
| `executeWithdrawal(requestId, minWstHypeAmount)`                                      | Anyone can execute a matured, pending request. The full wstHYPE payout goes to the stored owner; the caller cannot redirect it. This permits third-party claim services.                                                                                 |

Claiming returns **wstHYPE**, also reflected in the owner's stHYPE balance, **not native HYPE or WHYPE**. Restaking withdrawals do not enter Overseer's redemption queue. Converting to HYPE requires a separate swap or [unstaking operation](/stakedhype/stake-accounts#withdrawals).

The cooldown starts at request time, not deposit time. A matured request still requires a claim transaction.

Execution requires SHE to be unpaused, token transfers to succeed, sufficient share backing, and the caller's minimum to be met. Failed execution leaves the request retryable. Payout rounds down to whole wstHYPE base units; residual raw shares remain in the pool or reward reserve.

## Rewards

`fundRewards(minNewRawShares)` is payable and restricted to `REWARD_DISTRIBUTOR_ROLE`. It sends new native HYPE through `Overseer.mint`, measures received shares, and streams them with retained reserves over the configured duration.

A running stream cannot be cancelled, replaced, or topped up through SHE's reward functions. Its funded shares follow a fixed release schedule. The configured stream duration is **23 hours**; starting the next stream requires a new funding transaction.

Premiums compound into active positions; there is no separate claim function.

`checkpointRewards()` is permissionless after the first deposit. It records elapsed emissions and donations. `rewardState()` reports the schedule and reserves.

Ordinary rebases change the value of underlying shares; premium streams increase the active pool's shares. Neither guarantees a fixed HYPE return.

## Manager roles and limits

[SHE deployed contract](https://hyperevmscan.io/address/0x0447d0339c82a8EFe01994b7D1981bf5c517da0e#code)

Parameters checked on **18 October 2026**: **14-day cooldown**, **23-hour reward streams**. Read `configuration()` for current settings.

| Authority                 | Holder                                                                                                                                                                                                                      | Permissions                                                                                                                                                    |
| ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `MANAGER_ROLE`            | Keeper [0x4eb038eB501045DAa520B972Fcad48C429531E10](https://hyperevmscan.io/address/0x4eb038eB501045DAa520B972Fcad48C429531E10)                                                                                             | `setPaused(bool)` and `rescueTokens(token, recipient, amount)`. Recovery is limited to unrelated ERC-20 tokens; native HYPE, stHYPE, and wstHYPE are excluded. |
| `REWARD_DISTRIBUTOR_ROLE` | Same keeper                                                                                                                                                                                                                 | `fundRewards(minNewRawShares)`.                                                                                                                                |
| `DEFAULT_ADMIN_ROLE`      | [Protocol multisig](/stakedhype/transparency-and-risks/roles-and-controls-registry#admin-setup), [0x97dEe0eA4Ca10560f260A0f6f45bdC128A1D51f9](https://hyperevmscan.io/address/0x97dEe0eA4Ca10560f260A0f6f45bdC128A1D51f9)   | Grant/revoke operational roles; manager permissions; `setCooldown` (1 second–180 days); `setRewardDuration` (1 second–7 days).                                 |
| ProxyAdmin owner          | [Protocol timelock](/stakedhype/transparency-and-risks/upgrade-and-risk-governance#current-state), [0xc5DEd4F7F53919c714059a17d31371aE847E23D2](https://hyperevmscan.io/address/0xc5DEd4F7F53919c714059a17d31371aE847E23D2) | Upgrade SHE, with a 48-hour minimum delay. The protocol multisig holds proposer, canceller, and executor roles.                                                |

The linked multisig registry documents its signers, threshold, and control history.

`setPaused` blocks deposits, requests, cancellations, and execution together. Existing clocks keep advancing. There is no automatic expiry or maximum pause duration. Reward funding, checkpointing, and administrative setters remain available during a pause.

Pausing is intended for security incidents, not routine withdrawal management.

Duration changes affect future requests or streams; existing requests keep their claim date. SHE's two-day default-admin transfer delay does not delay these setters or operational-role changes.

## Quotes and indexing

SHE uses the wstHYPE interface. Read about the [relationship between stHYPE and wstHYPE](/stakedhype/integrate/wsthype) before integrating.

Approve the escrow proxy to spend wstHYPE. Pass that proxy to each [StakedHypeEscrowLens](https://hyperevmscan.io/address/0x649440C43540242E947CB8aBF88eCC7f01472407#code) helper:

* `previewDeposit`: units issued, accepted wstHYPE, and unspent amount.
* `previewRequestWithdrawal`: raw shares reserved for selected units.
* `previewCancelWithdrawal`: units returned at the current pool price.
* `previewExecution`: status/clock/pause eligibility and wstHYPE payout.

Quotes are snapshots, not execution guarantees. Track request IDs from `WithdrawalRequested` events and read their status with `getWithdrawalRequest`.


# Restaking: risks and FAQ

What restaking adds to holding stHYPE, where the extra yield comes from, how the rate changes as the pool grows, and how long it takes to get HYPE back.

Restaking puts stHYPE into one shared pool. The pool's stake is used by curated partners who need staked HYPE on Hyperliquid, and they pay restakers in HYPE for it. Your stHYPE keeps earning base staking yield the whole time. In exchange, withdrawals take a 14-day cooldown.

This page answers the questions we hear most before people deposit. For step-by-step instructions, see [How to Restake](/stakedhype/restaking/how-to-restake). \
\
Ready to start? [Restake in the Valantis app](https://app.valantis.xyz/restaking).

## At a glance

| Topic                 | Details                                                                                                                                 |
| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| **What you earn**     | Base staking yield, plus a share of the HYPE partners pay the pool each day                                                             |
| **Who pays today**    | Ethena, 10 HYPE per day, for stake that keeps USDe live as a quote asset on HyperCore                                                   |
| **Withdrawals**       | 14-day cooldown, earning base staking yield throughout. Cancellable at any time                                                         |
| **Getting HYPE back** | About 17 days in total typically, about 21 days at most in normal conditions                                                            |
| **Fees**              | No deposit or withdrawal fee. Network fees apply                                                                                        |
| **Minimum deposit**   | None                                                                                                                                    |
| **Audit**             | [stHYPE Restaking Audit, Oct 18 2026](https://github.com/ValantisLabs/audits/blob/main/stakedhypeescrow-security-review-2026-10-18.pdf) |

## Key risks

* **Slashing.** Restaking does not add new slashing risk to your stake. Hyperliquid's penalties apply to all stHYPE, restaked or not. The live allocation backs the USDe quote asset and follows Hyperliquid's [quote-asset slashing rules](https://hyperliquid.gitbook.io/hyperliquid-docs/hypercore/permissionless-spot-quote-assets). Slashed HYPE is burned. If a slashing happens, all stHYPE holders share the loss equally.
* **Liquidity.** You accept a 14-day cooldown before you get your stHYPE back. Large, protocol-wide withdrawals can take longer. See [Understanding stHYPE](/stakedhype/stake-accounts#large-unwinds).
* **Yield dilution.** Partners pay a fixed amount of HYPE per day, shared by everyone restaking. The more stHYPE in the pool, the lower each depositor's rate. See [How the rate changes as the pool grows](#how-the-rate-changes-as-the-pool-grows).
* **Smart contracts.** The restaking contract is audited, but no audit removes smart-contract risk.
* **No backstop.** There is currently no insurance or insolvency backstop for losses. See [Transparency and Risks](/stakedhype/transparency-and-risks).

## Current Restaker Rewards

This is current committed liquidity after any fees applied, what restakers realize. These numbers can change in the future.

<table><thead><tr><th>Yield source</th><th>Reward</th><th width="207">Status</th><th>Term</th></tr></thead><tbody><tr><td>USDe Quote Asset</td><td>10 HYPE per day</td><td>Active</td><td>Active until Dec 2028</td></tr><tr><td>HIP-4 deployer (not live)</td><td>Estimated 40 HYPE per day</td><td>Not live yet. Soon.</td><td>TBD</td></tr><tr><td>Trading Fee Discount Market Maker (not live)</td><td>Estimated 20–100 HYPE per day, depending on volume and HYPE price</td><td>Not live yet. Soon.</td><td>TBD</td></tr></tbody></table>

### stHYPE Restaking Yield Calculator

Partners pay a fixed amount of HYPE per day, split across everyone restaking. The more stHYPE in the pool, the smaller each share, so APY goes down as deposits grow.

{% @valantis-restaking-yield/calculator-card content="revision-4" %}

## FAQ

### Yield

<details>

<summary>Where does the extra yield come from?</summary>

Ethena pays restakers 10 HYPE per day to keep USDe live as a quote asset on HyperCore. Hyperliquid requires staked HYPE to back a quote asset, and restaked stHYPE provides that stake.

The 10 HYPE is shared by everyone restaking, on top of the base staking yield every stHYPE already earns. Your HYPE is never lent out, borrowed, or traded. It stays staked on HyperCore in stHYPE protocol accounts.

</details>

<details>

<summary>Is the 10 HYPE per day guaranteed?</summary>

The USDe agreement runs from Dec 1 2025 to Dec 1 2028. Rewards are committed to the pool one week at a time, so you can always see what the pool is earning before you deposit.

The 10 HYPE per day is committed by the USDe quote asset and is expected to continue through December 2028. If USDe delists as a quote asset or changes staking provider, restakers get 90 days' notice before the extra yield stops.

</details>

<details>

<summary>Why is USDe still live if Ethena shut down its HIP-3 exchange?</summary>

Ethena closed its HIP-3 perps exchange, but USDe remains a live quote asset on HyperCore. Hyperliquid requires a quote asset's stake to stay in place for its full term, so the agreement and its payments continue through Dec 2028.

</details>

<details>

<summary>Do stHYPE holders who don't restake get the USDe yield?</summary>

Before restaking launched, Ethena's USDe payments were shared across all stHYPE holders. Restaking now directs them to restakers, which slightly lowers base stHYPE yield in exchange for a larger boost for restakers. The goal is to grow the pie: restaking makes entirely new yield deals possible, which raise earnings for the whole system.

</details>

<details>

<summary>What happens to my rate as more people deposit?</summary>

Your share of the daily HYPE gets smaller as the pool grows, because the same amount is split across more stHYPE. New partners add to the daily amount when they go live. See [How the rate changes as the pool grows](#how-the-rate-changes-as-the-pool-grows).

</details>

<details>

<summary>Are there fees?</summary>

There is no deposit or withdrawal fee; network fees apply. stHYPE's standard 10% protocol fee is already accounted for in the APY shown in the app.

</details>

### Risk

<details>

<summary>Does restaking add slashing risk?</summary>

No new slashing risk is added to your stake. Hyperliquid's penalties apply to the protocol's stake whether stHYPE is restaked or not. What restaking changes is who accepts withdrawal delays: restakers take the 14-day cooldown so that liquid stHYPE stays liquid.

The live allocation backs the USDe quote asset. That stake can be slashed if the USDe markets break Hyperliquid's [quote-asset rules](https://hyperliquid.gitbook.io/hyperliquid-docs/hypercore/permissionless-spot-quote-assets).

In plain terms: the USDe stake can be slashed if the USDe/USDC and USDe/HYPE order books become illiquid and USDe is considered to have lost its $1 peg for more than 3 days.

HIP-3 and HIP-4 rules are covered in [Background: Deployer Stake](/stakedhype/restaking/deployer-stake). Neither is live today.

</details>

<details>

<summary>If a slashing happens, who takes the loss?</summary>

Slashed HYPE is burned. It is not paid to anyone, and there is currently no insurance or insolvency backstop.

All stHYPE holders share the loss equally. Restakers don't take on extra slashing risk; they only accept the longer withdrawal conditions.

</details>

<details>

<summary>Can I choose which strategies my stHYPE supports?</summary>

No. One deposit gives you a share of the whole pool. Rewards and risks are shared across all restakers; you don't opt into individual partners.

</details>

<details>

<summary>Has the restaking contract been audited?</summary>

Yes. Read the [stHYPE Restaking Audit](https://github.com/ValantisLabs/audits/blob/main/stakedhypeescrow-security-review-2026-10-18.pdf). Protocol-wide risks and liquidity are reviewed quarterly in the [stHYPE Health Reports](/stakedhype/transparency-and-risks#sthype-health-reports).

</details>

<details>

<summary>What protects restakers if a HIP-4 deployer goes live?</summary>

The proposed HIP-4 terms include $1,000,000 of slashing protection and a stake committed by the deployer alongside restakers. These terms are not final until the deployer goes live.

</details>

### Withdrawals

<details>

<summary>How long does it take to get HYPE back?</summary>

1. **Request a withdrawal.** A 14-day cooldown starts. That amount keeps earning base staking yield, and you can cancel at any time.
2. **Claim.** After 14 days, claim your stHYPE from Positions. It is not sent automatically.
3. **Convert to HYPE.** Swap stHYPE at the market rate for the fastest exit, or unstake with no fee. Unstaking takes up to about 7 days, about 3 on average.

Typical total: about 17 days. In normal conditions, at most about 21 days with no fees, 14 of them still earning. Very large, protocol-wide withdrawals can take longer.

</details>

<details>

<summary>Do I keep earning during the cooldown?</summary>

Yes, base staking yield. The amount you withdraw stops earning restaking rewards when the cooldown starts. Anything left in your position keeps earning both.

</details>

<details>

<summary>Can I cancel a withdrawal?</summary>

Yes, any time before the cooldown ends. The amount returns to your restaked position and restaking rewards resume. After the cooldown, claim your stHYPE and deposit it again if you change your mind.

</details>

<details>

<summary>Is there a faster exit for large holders?</summary>

No. All restakers exit after the same 14-day cooldown, whatever the size of their position.

</details>

<details>

<summary>Can the 14-day cooldown change?</summary>

It may be raised in the future, but only with at least 30 days' notice, so you have time to withdraw under the current terms. Requests already in progress keep their original claim date, even if the cooldown changes afterward. Protocol pauses can also affect when withdrawals become claimable.

</details>

### Using restaked stHYPE

<details>

<summary>Do I get a receipt token? Can I borrow against it?</summary>

Not yet. Restaked stHYPE is not tokenized, so it can't be used on lending markets or elsewhere in DeFi.

</details>

<details>

<summary>Does restaking change my validator or my Prime trading discount?</summary>

Your validator stays the same. Restaked stHYPE does not count toward your Prime trading discount.

</details>

<details>

<summary>Is there a minimum deposit?</summary>

No.

</details>


# For Validators

A mechanism for independent frontends, users, and protocols building with stHYPE to direct stake to partnered validators, and/or receive extra staking revenue.

Community Codes have been live since the inception of stHYPE at the launch of HyperEVM. The program has since been expanded following the takeover of sthype by Valantis in September 2025.

### Validators

* Mint stHYPE with their community code to send stake directly to their validator; receiving a higher share of stake than possible with native staking through the community codes boost.
* Utilize looping to leverage even more stake into their validator than possible with native staking.

### Protocols

* Have their vault tokens whitelisted for Community Codes eligibility to enable Validators & Users to direct stake to certain validators through their vault.
* Receive a higher share of fees by delegating to a validator offering a rebate on commission.

### User

* Deeper liquidity and utility from a strengethened integration layer of Sthype.
* Ability to directly support validators while still utilizing DeFi.

## Integrate

When an address mints stHYPE with a Validator Community Code, the ERC20 balances of the minting address is continuously tracked and assigned to that validator. These ERC20 tokens currently include:

* sthype, wsthype
* wsthype lending market deposits - HypurrFi, HyperLend, Felix Morpho

If you would like more ERC20 balances or DeFi deposits with Sthype underlying tracked, please email <hello@valantis.xyz>

Minting stHYPE with a new validator, will automatically re assign the accounts entire balance to this new validator; overriding any previous delegations. Each address is only able to stake to one validator at a time, using their entire sthype balance and wsthype balance in DeFi.

## Delegating with Community Codes

Any address that holds sthype, or wsthype in DeFi, can assign their entire balance to a particular validator.

The frontend supports validator selection during the minting process.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-d11c7f9f22aa164f7cb761a498af2103c8447cef%2Fval-mint.png?alt=media" alt=""><figcaption></figcaption></figure>

minting any amount with a community code selected will automatically track the entire balance of the account and assign it to the most recent validator selected.

* stHYPE that was previously minted without a validator selected will automatically be tracked and assign to the most recent validator selected. No need to withdrawal.
  * For example, a mint of 0.001 stHYPE with community code Validator X will enable tracking for the user's entire stHYPE balance to Validator X, not just the 0.001 stHYPE recently minted.
* minting with a new validator selected, will override any previous selections.

[documentation](/stakedhype/integrate) covers the smart contract integration with community codes minting. Validators are enouraged to host thier own minting frontend.

Examples of tracking:

* If a user holds `1000` stHYPE & mints `0.01` stHYPE with `Validator X`;
  * `1000.01` HYPE x Boost will be sent to `Validator X`
* If the same user mints another `0.01` stHYPE to Validator Y
  * `1000.01` HYPE x Boost will be removed from Validtor X and `1000.02` HYPE x Boost will be delegated to `Validator Y`
* If the same user sells 500 stHYPE on a DEX
  * `500` HYPE x Boost will be undelegated from `Validator Y`
* If the same user deposits `500` stHYPE into felix, borrows `250` HYPE, and mints `250` more stHYPE
  * an additional `250` HYPE x Boost will be delegated to `Validator Y`

## Community Codes Boosts

User's that mint with a validator selected, dictate the delegation of the entire protocol (with security constraints).

For example, at the time of writing:

25% of all stHYPE has a validator selected.

This means that 1 stHYPE minted with community codes dictates 4 HYPE delegated in the protocol (4x boost)

Constraints:

* no validator is able to exceed 50% of stHYPE's total delegation
* Validators outside the active set can accumulate Community Codes allocations. Stake can be delegated once their allocation is sufficient to enter the active set and they have considerable uptime and operating history. stHYPE has helped several validators enter the active set since the launch of HyperEVM.
* All active-set validators with considerable uptime and operating history are eligible for Community Codes delegation and must follow auditable security practices.

## Incentive Alignment

Community Codes is a mature economic mechanism to align incentives between Hyperliquid's DeFi Layer and Validator Layer, using the stHYPE LST as the interface.

Community Codes allows stHYPE holders and protocols to direct the stake of the stHYPE protocol; and still utlize thier holdings across HyperEVM DeFi.

The result is more value flow to the end user, and higher utility for sthype.

Protocols include:

* **DEXes** with stHYPE liquidity.
* **Lending Markets** holding stHYPE collateral.
* **Yield Vaults** utilizing strategies with stHYPE.
* **Builder Code Terminals / Wallets** that allow users to mint stHYPE.
* **Large Holders** with stHYPE in their wallet, etc.

These entities can choose to direct their share of HYPE stake to any validator under the stHYPE protocol; doing so often results in some incentive provided by validators.

Validators are encouraged to partner with DeFi Vaults to receive their stake. Validators creating relationships with DeFi Protocols can come in the form of:

* Direct rebates on validator commissions, meaning DeFi protocols using stHYPE can receive higher staking yield, i.e., zero validator commission.
* Marketing and distribution support, as many validators are also active community members.
* Validators directly acting as liquidity providers to partnered DeFi protocols, as many validators are also large holders of HYPE and LPs across the ecosystem.
* Validators can offer services/create partnerships based on their other lines of business, such as market-making support, custodian support, etc.

If you are a validator looking for more stake, reach out to be partnered with DeFi protocols / whales holding significant stHYPE. If you are a stHYPE holder or Yield Vault holding stHYPE, reach out to be partnered with a validator. <hello@valantis.xyz>

## Eligibility

#### Eligibility - Operators

All operators can have their own Community Code. All active-set validators with considerable uptime and operating history are eligible for delegation from stHYPE. Operators outside the active set can accumulate Community Codes allocations before receiving stake. Stake will be delegated once:

1. The operator has considerable uptime and operating history.
2. The operator is in the active set, or will enter the active set following the delegation by stHYPE. This allows established operators to use Community Codes to enter the active set.

Operators can include stHYPE staking in their interfaces. Community codes are codes included in user stake transactions (see technical details [here](/stakedhype/integrate)). All tracking and delegation occurs onchain from smart contracts, meaning permissionless integration.

Users can also directly mint to a validator using the staking UI on app.valantis.xyz/staking.

All operators are held to an extremely high performance standard, as decided by onchain metrics. In the event that an operator falters, Valantis and other operators will attempt to provide advice to remedy performance. If performance does not improve, they will be removed from the set.

Please reach out if you are interested in operating a Community Code. To integrate community codes into your frontend, see our [Integrate stHYPE](/stakedhype/integrate) page.

***

### Guardrails & Discretion

All listed mechanisms of this program are entirely subject to the safe operation and low concentration risk of the stHYPE protocol.

* **Concentration limits** prevent excessive stake from flowing to a single validator.
* **Diversity floors** ensure that a healthy number of validators remain active.
* **Performance standards** apply equally to all validators, with removal for persistent underperformance.
* **Validator commissions** must remain competitive among all validators receiving delegation to avoid diluting the yield of stHYPE.
* **Lazy rebalancing** reduces churn by only redelegating when allocation changes exceed a threshold, this avoids stake being locked due to constant redelegation.

***


# Transparency and Risks

## stHYPE Health Reports

stHYPE Health Reports are internal documents published roughly once a quarter. They snapshot key operations of stHYPE relevant to its risk analysis. Risks and liquidity are also reviewed and audited quarterly.

* [stHYPE Health Report March 1 2026](https://github.com/ValantisLabs/audits/blob/main/stHYPE%20Health%20Report%20-%20March%201%202026.pdf)
* [stHYPE Health Report April 1 2026](https://github.com/ValantisLabs/audits/blob/main/stHYPE%20Health%20Report%20-%20April%201%202026.pdf)
* [stHYPE External Health Report Audit Q2 2026](https://github.com/ValantisLabs/audits/blob/main/Risk%20Report%20stHYPE-%20Valantis%20Hosted.pdf)

## System Overview

stHYPE accepts HYPE deposits and issues stHYPE, with backing managed through HyperCore staking modules.\
At a high level, rewards and base unbonding constraints are determined by Hyperliquid network mechanics.

stHYPE operates with:

* standard HyperCore staking modules, and
* one active non-standard external-management stake account: the USDe quote-asset module, which has its own withdrawal and slashing characteristics.

The Ethena HyENA HIP-3 allocation is deprecated. The proposed HIP-4 deployer is not live.

Historical market references:

* As of **2026-02-23**, the USDe quote-asset stake account had two spot markets deployed which can be monitored for slashing risk: [USDe/USDC](https://app.hyperliquid.xyz/trade/USDE/USDC) and [HYPE/USDe](https://app.hyperliquid.xyz/trade/HYPE/USDE). Slashing requirements for these markets are outlined in [Permissionless Spot Quote Asset Slashing Docs](https://hyperliquid.gitbook.io/hyperliquid-docs/hypercore/permissionless-spot-quote-assets). Liquidity depth and historical compliance of these markets can be publicly verified onchain.
* The deprecated HyENA HIP-3 allocation used the DEX identifier `hyna`. Historical risk references: [HyENA docs](https://docs.hyena.trade), [HIP-3 Slashing Docs](https://hyperliquid.gitbook.io/hyperliquid-docs/hyperliquid-improvement-proposals-hips/hip-3-builder-deployed-perpetuals#slashing).

See [Understanding stHYPE](/stakedhype/stake-accounts) for current inventory and withdrawal profiles.

## Core Constraints

### Base staking behavior

stHYPE rewards primarily track staking-related yield from HyperCore staking activity.\
All stHYPE-managed assets are intended for staking operations, not lending or discretionary trading strategies by the stHYPE contracts.

### Withdrawal behavior

Users can exit through:

* direct protocol burn/redeem paths, and/or
* secondary market liquidity where available.

Withdrawal timelines can vary depending on queue state and module mix.\
See [Integrate stHYPE](/stakedhype/integrate) and [Understanding stHYPE](/stakedhype/stake-accounts).

## Key Risk Areas

### Smart contract risk

Smart contracts can still contain vulnerabilities despite audits and testing.\
No documentation should be interpreted as eliminating smart-contract risk.

### Validator slashing risk

Hyperliquid validators can be slashed for protocol-defined failures.\
This is a core Proof-of-Stake network risk.

### Non-standard module slashing/operational risk

Non-standard stake accounts introduce additional trust and slashing surfaces beyond standard validator slashing:

* [HIP-3 slashing rules](https://hyperliquid.gitbook.io/hyperliquid-docs/hyperliquid-improvement-proposals-hips/hip-3-builder-deployed-perpetuals#slashing)
* [Permissionless quote-asset slashing rules](https://hyperliquid.gitbook.io/hyperliquid-docs/hypercore/permissionless-spot-quote-assets)

## Governance and Control Transparency

* Current execution controls are role-gated and multisig-administered.
* No active on-chain veto mechanism currently enforces upgrades.
* stHYPE proxy upgrades are subject to a 48-hour on-chain timelock.

Detailed control mapping:

* [Roles Registry](/stakedhype/transparency-and-risks/roles-and-controls-registry)
* [Governance Risk](/stakedhype/transparency-and-risks/upgrade-and-risk-governance)

## Monitoring and Incident Operations

Monitoring and incident-disclosure commitments are documented in:

* [Monitoring](/stakedhype/transparency-and-risks/monitoring-and-incident-response)

## Financial Resilience and Loss Position

* There is currently **no guaranteed insolvency backstop** for user losses.
* Any future discretionary resilience framework would be published as a separate policy with explicit scope and limits.

## Security Program Status

* stHYPE currently does **not** run an active public bug bounty program.
* Security updates and operational controls should be interpreted together with:
  * [Contract Addresses](/stakedhype/integrate/contract-addresses)
  * [Roles Registry](/stakedhype/transparency-and-risks/roles-and-controls-registry)


# Roles Registry

Last updated: 2026-10-16

This page is the canonical registry for stHYPE roles, privileged controls, and currently documented delay/timelock behavior.

## Current Control Map

| Contract             | Role / Control                | Effective Scope                                                             | Address                                      |
| -------------------- | ----------------------------- | --------------------------------------------------------------------------- | -------------------------------------------- |
| `stHYPE`             | `DEFAULT_ADMIN_ROLE`          | Role administration                                                         | `0x97dEe0eA4Ca10560f260A0f6f45bdC128A1D51f9` |
| `stHYPE`             | `PAUSER_ROLE`                 | `pauseTransfer`, `pauseMint`, `pauseBurn`, `pauseRebase`                    |                                              |
| `stHYPE`             | `MINTER_ROLE`                 | `mint`                                                                      |                                              |
| `stHYPE`             | `BURNER_ROLE`                 | `burn`                                                                      |                                              |
| `stHYPE`             | `REBASER_ROLE`                | `syncSupply`                                                                |                                              |
| `stHYPE`             | `WRAPPER_ROLE`                | `transferShares` wrapper interactions                                       |                                              |
| `Overseer`           | `DEFAULT_ADMIN_ROLE`          | Role administration, staking-module/parameter controls, pause controls      | `0x97dEe0eA4Ca10560f260A0f6f45bdC128A1D51f9` |
| `Overseer`           | `MANAGER_ROLE`                | Module operations (`deposit`, withdrawal flow coordination, delegation ops) | `0x53D6c6594d14f9bBDFC572f048312728F7B2418e` |
| `Overseer`           | `REBASER_ROLE`                | `rebase`                                                                    | `0x4eb038eb501045daa520b972fcad48c429531e10` |
| `Overseer`           | `FEE_RECIPIENT_ROLE`          | `claimFee`                                                                  | `0xa2666b4dd1242def4c3cf5731a85aa8457fe01c1` |
| `wstHYPE`            | `DEFAULT_ADMIN_ROLE`          | Role administration                                                         | `0x97dEe0eA4Ca10560f260A0f6f45bdC128A1D51f9` |
| ProxyAdmin contracts | Owner (multisig-administered) | Proxy implementation upgrades, subject to a 48-hour on-chain timelock       | `0x97dEe0eA4Ca10560f260A0f6f45bdC128A1D51f9` |

## Explicit Delay/Bounds Currently in Contracts

* stHYPE proxy upgrades are subject to a 48-hour on-chain timelock.
* `AccessControlDefaultAdminRules` is initialized with a default-admin transfer delay of `0` in current deployments. This is separate from the 48-hour proxy-upgrade timelock.
* `Overseer.setPauseDuration` must be `>0` and `<=14 days`.
* `Overseer` V3 initialization sets pause duration to `7 days`.

## Clarifications

* The 48-hour proxy-upgrade timelock, the default-admin transfer delay, and pause durations are separate controls.
* Address-level transfer disable controls affect transfer behavior and are separate from burn/redeem queue accounting. There are no protocol or admin level restrictions on burn/claim transactions.
* No active on-chain veto mechanism currently enforces upgrades.

## Admin Setup

Updated 2026-04-07

`DEFAULT_ADMIN_ROLE`: [0x97dEe0eA4Ca10560f260A0f6f45bdC128A1D51f9](https://hyperevmscan.io/address/0x97dEe0eA4Ca10560f260A0f6f45bdC128A1D51f9)

`Threshold`: 4/6

<table><thead><tr><th width="249">#</th><th>Address</th><th>Explorer</th></tr></thead><tbody><tr><td>1</td><td>0x4F1Badad95B7A5901b6927d6C4A6761b3e8A00b4</td><td><a href="https://hyperevmscan.io/tx/0xc48ec349bf2f342440399cc90a4e56766c32ce570f21f9ae80013e05cc36379c">hyperevmscan</a></td></tr><tr><td>2</td><td>0xD78a2374d5459ed44087fcfe5A40105B03CD9D71</td><td><a href="https://hyperevmscan.io/address/0xD78a2374d5459ed44087fcfe5A40105B03CD9D71">hyperevmscan</a></td></tr><tr><td>3</td><td>0x5cd0448cC4AAE28e46BabdB285B9E3B601872378</td><td><a href="https://hyperevmscan.io/address/0x5cd0448cC4AAE28e46BabdB285B9E3B601872378">hyperevmscan</a></td></tr><tr><td>4</td><td>0x10f6160f0033700CB55C478826068DAD4d210465</td><td><a href="https://hyperevmscan.io/address/0x10f6160f0033700CB55C478826068DAD4d210465">hyperevmscan</a></td></tr><tr><td>5</td><td>0x785c7DF2717c119929BC5a3d6c52638D2918aC2C</td><td><a href="https://hyperevmscan.io/address/0x785c7DF2717c119929BC5a3d6c52638D2918aC2C">hyperevmscan</a></td></tr><tr><td>6</td><td>0x4993522ee8091cc7A452Af7a98D5ef4a269f6FC5</td><td><a href="https://hyperevmscan.io/address/0x4993522ee8091cc7A452Af7a98D5ef4a269f6FC5">hyperevmscan</a></td></tr></tbody></table>

## Changelog Policy

This registry will track dated changes to:

* role assignments and scope,
* signer/threshold changes for controlling multisigs,
* upgrade events and implementation changes.

***

### 2026-04-10 Upgrade all Proxy Contracts with 48 hour Timelock

| #    | Action                        | Tx                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| ---- | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1    | Overseer ProxyAdmin           | [hyperevmscan](https://hyperevmscan.io/tx/0x11482a6a4d24946fb79d3c631310633e700b38cb4bef56a357d301339e7a6bbe)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| 2    | stHYPE ProxyAdmin             | [hyperevmscan](https://hyperevmscan.io/tx/0xc77ea2006f15b84698c6de202495a7f376a42623ea9a753ca2ceb3d9b1f8621c)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| 3    | wstHYPE ProxyAdmin            | [hyperevmscan](https://hyperevmscan.io/tx/0x73a1ab4ecd780c0f2e937852f53fd14b205883073829f8d2e391930116ce9e36)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| 4-10 | Staking Module 1-7 proxyAdmin | <p><a href="https://hyperevmscan.io/tx/0x47d4138b027ec8ffe1b8d240b1234c9e370bf977d3ad56ac84533c7606787b81">1) hyperevmscan</a><br><a href="https://hyperevmscan.io/tx/0x7ccb9872353b20b59fccf993244946fc951d15fb8fe6a88fcf50700444a94ab1">2) hyperevmscan</a><br><a href="https://hyperevmscan.io/tx/0xa8e69d9807bc260dd6402b12ce319f00c6d5cf62510b91008bbae67f61599d4d">3) hyperevmscan</a><br><a href="https://hyperevmscan.io/tx/0xcbbc1b06d51525e7c8b28df3116457a99cb1b939733245a45062949755993f3e">4) hyperevmscan</a><br><a href="https://hyperevmscan.io/tx/0xb967c3d41418b536ed7eb19788b8a19e65c5319ce356ca879d3963cc779f5ca3">5) hyperevmscan</a><br><a href="https://hyperevmscan.io/tx/0x0078ccb736515d4a377a9c64c728c07bf0f6c17381bb96e0fe3f0d68df51e669">6) hyperevmscan</a><br><a href="https://hyperevmscan.io/tx/0x0b35ac9aa34424feb258e20f9d485c7644e70dec277d3c55b0b532be32b5572c">7) hyperevmscan</a></p> |

### 2026-04-10 Remove Admin Address Level Transfer Restrictions

Deprecate the ability of DEFAULT\_ADMIN\_ROLE to restrict addresses from transferring sthype and wsthype to remove trust in protocol admin.

Remove the function `setSelfDisableTransfer(address who, bool status) onlyRole(DEFAULT_ADMIN_ROLE)`.

| # | Action                                        | Tx                                                                                                            |
| - | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| 1 | Remove admin transfer restrictions on stHYPE  | [hyperevmscan](https://hyperevmscan.io/tx/0x11482a6a4d24946fb79d3c631310633e700b38cb4bef56a357d301339e7a6bbe) |
| 2 | Remove admin transfer restrictions on wsthype | [hyperevmscan](https://hyperevmscan.io/tx/0x7f080983d15eef9ea5ee7de63641c61cca152191bcb4c2f794179102da377d05) |

### 2026-04-07 — stHYPE MultiSig Signer Rotation

Move signing infrastructure to a more secure setup, routine wallet rotation, and increase in threshold.

Change Threshold from `3/5` to `4/6`

| # | Action                                                        | Tx                                                                                                            |
| - | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| 1 | Deprecate Signer `0x47Cb7961D4a9218433023e9D0f3b2E3630A3e10e` | [hyperevmscan](https://hyperevmscan.io/tx/0xc48ec349bf2f342440399cc90a4e56766c32ce570f21f9ae80013e05cc36379c) |
| 2 | Add signer `0x785c7DF2717c119929BC5a3d6c52638D2918aC2C`       | [hyperevmscan](https://hyperevmscan.io/tx/0xc48ec349bf2f342440399cc90a4e56766c32ce570f21f9ae80013e05cc36379c) |
| 3 | Deprecate Signer `0x7fa8B1D57d31286377c7103255967da7F682861D` | [hyperevmscan](https://hyperevmscan.io/tx/0x0f226741b99d71c5a777fab7fb1a37ea05a1c093401cff3a5cc0fd134184da2b) |
| 4 | Add Signer `0xD78a2374d5459ed44087fcfe5A40105B03CD9D71`       | [hyperevmscan](https://hyperevmscan.io/tx/0x0f226741b99d71c5a777fab7fb1a37ea05a1c093401cff3a5cc0fd134184da2b) |
| 5 | Add Signer `0x4F1Badad95B7A5901b6927d6C4A6761b3e8A00b4`       | [hyperevmscan](https://hyperevmscan.io/tx/0x12a49b22e611383ce57f9dfd71ddde3abaf4f61e36b374c90a85fe5f46c97e09) |
| 6 | Increase threshold to `4/6`                                   | [hyperevmscan](https://hyperevmscan.io/tx/0x05727d92885e39fc92ef39ccab421e065c2eb199965854f4eca0dfc7272d2f08) |

### 2026-02-19 — stHYPE Slashing Upgrade

Overseer upgrade to support protocol slashing handling.

| # | Action                          | Tx                                                                                                            |
| - | ------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| 1 | Upgrade Overseer implementation | [hyperevmscan](https://hyperevmscan.io/tx/0x1e6ea6c80e27dc5d805e380b285024948e25c7fdb10cfa814715e4bb8f19ad09) |

***

### 2025-12-08 — stHYPE HIP-3 Upgrade

`setAprThreshold(uint256)` > `500 bps` to account for increased yield and prevent rebase reverts.

| # | Action                       | Tx                                                                                                            |
| - | ---------------------------- | ------------------------------------------------------------------------------------------------------------- |
| 1 | Set APR threshold to 500 bps | [hyperevmscan](https://hyperevmscan.io/tx/0xef8d393d61cec8d85b97c37e8466934d8a78c3c0f6ed3a1f78778728a744ee4a) |

***

### 2025-11-30 — stHYPE HIP-3 Upgrade

Add staking modules for HyENA delegations.

| # | Action                                                                                                | Tx                                                                                                            |
| - | ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| 1 | Add Staking Module `0xa5101b03675294c87ab7381b41d4225eb8709128` for HyENA USDe Quote Asset Delegation | [hyperevmscan](https://hyperevmscan.io/tx/0xc0de76000afa5c4f9aaff83019a7cab55555251ec5aeff65654f90727e936796) |
| 2 | Add Staking Module `0x358e783c32147b344a1168e0984d3350de4e07cb` for HyENA HIP-3 Delegation            | [hyperevmscan](https://hyperevmscan.io/tx/0xf5ca20013d70385d27ac15622335bec3d01a0c83442a36e556c1ce99de1c5449) |

***

### 2025-11-21 — stHYPE Protocol Maintenance CoreWriter V1.5

Upgrade Overseer implementation.

| # | Action                                                                          | Tx                                                                                                            |
| - | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| 1 | Upgrade Overseer to implementation `0xc9dcf086ee9f063bcd4c7d2ec4b82085142a8cee` | [hyperevmscan](https://hyperevmscan.io/tx/0xa8602e162c8aa29791a1fbe7515d7325c8d0d88f2362e73b6f66045b760657a9) |

***

### 2025-10-23 — stHYPE CoreWriter V1 Role Upgrades

Grant operational roles on Overseer (`0xb96f07367e69e86d6e9c3f29215885104813eeae`).

| # | Action                                                                     | Function                      | Tx                                                                                                            |
| - | -------------------------------------------------------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------- |
| 1 | Grant `MANAGER_ROLE` to `0x53D6c6594d14f9bBDFC572f048312728F7B2418e`       | `grantRole(bytes32, address)` | [hyperevmscan](https://hyperevmscan.io/tx/0x3a4ee651ec75fb419d62ba2c7caa4e69bdd10b47c4b255ff978c13a0ba05387c) |
| 2 | Grant `REBASER_ROLE` to `0x4eb038eb501045daa520b972fcad48c429531e10`       | `grantRole(bytes32, address)` | [hyperevmscan](https://hyperevmscan.io/tx/0x82b428a01f7ca382c30be91f31d90c3516ed8432a66aa4e677fe90227ce708be) |
| 3 | Grant `FEE_RECIPIENT_ROLE` to `0xa2666b4dd1242def4c3cf5731a85aa8457fe01c1` | `grantRole(bytes32, address)` | [hyperevmscan](https://hyperevmscan.io/tx/0xefd5546f67c0fe889d021d9aebc3bc53889a2f5d28c89b9a7fa89db282e7f3ff) |

***

### 2025-10-23 — stHYPE CoreWriter V1 Staking Module Upgrade

Add 5 HyperCore Staking Modules.

| # | Module Address                               | Tx                                                                                                            |
| - | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| 1 | `0x591540F231055743A37F691C3ffd50E4E53561ab` | [hyperevmscan](https://hyperevmscan.io/tx/0x566da985fe1c00af7c1b2326904eac26e533f2aab98b08abefbc7da450212e1f) |
| 2 | `0x16a4814e8eB502C56CeBd73F9c8aC7FDee29c042` | [hyperevmscan](https://hyperevmscan.io/tx/0x02b8e72a433534b6d38227814a1b2466fd0f7a0b6b8ab8838281b9b28f9b38cb) |
| 3 | `0xf992aa323ec183733213f874b6322b8bd1aAD625` | [hyperevmscan](https://hyperevmscan.io/tx/0x696cfe6759927897cc25fee2bfc6381b5163bfccbc5878f74cd089a9c2e3421a) |
| 4 | `0x06b5659f16110319137220D1EFd680053F5e72a2` | [hyperevmscan](https://hyperevmscan.io/tx/0x3eb82d0524cc9b82a16ee2a2cae790138a1a6bcf6b1628cd5d91638c2c91cdd5) |
| 5 | `0xe787dD1347A29e6807D164C4FA43105b64048556` | [hyperevmscan](https://hyperevmscan.io/tx/0x0025875b6ff4d06de2827151cdeb12e60abc848d2c4d62f57fda330024e80bd5) |

***

### 2025-10-23 — stHYPE CoreWriter V1 Overseer Upgrade

Upgrade stHYPE to CoreWriter V1 Overseer.

| # | Action                                                                                | Tx                                                                                                            |
| - | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| 1 | Upgrade Overseer to proxy implementation `0xbe3a24a161e7704f01f4a6c73137451fcce8f85f` | [hyperevmscan](https://hyperevmscan.io/tx/0x79dd7a6f44ce04f504f50b943089d404ce9732ec9bd424ad73be832a963c4ac7) |

***

### 2025-08-22 — Ownership Change

Transfer `DEFAULT_ADMIN_ROLE` to `0x97dEe0eA4Ca10560f260A0f6f45bdC128A1D51f9` across all core contracts.

| # | Contract | Target                                       | Function                       | Tx                                                                                                            |
| - | -------- | -------------------------------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------- |
| 1 | Overseer | `0xb96f07367e69e86d6e9c3f29215885104813eeae` | `acceptDefaultAdminTransfer()` | [hyperevmscan](https://hyperevmscan.io/tx/0xe818b51ff820933afff7638aaa0c79cba5743ec92d71f8154d3104112a851da1) |
| 2 | stHYPE   | `0xffaa4a3d97fe9107cef8a3f48c069f577ff76cc1` | `acceptDefaultAdminTransfer()` | [hyperevmscan](https://hyperevmscan.io/tx/0x7ad4d8ecbf55cd0fbf6995af9364ef2a0543fde06425a6425234c9d805182fac) |
| 3 | wstHYPE  | `0x94e8396e0869c9f2200760af0621afd240e1cf38` | `acceptDefaultAdminTransfer()` | [hyperevmscan](https://hyperevmscan.io/tx/0x70964d0d12b3184377bfb29e310386c4399a6af974b078bf429da21a152d84e5) |

See also:

* [Contract Addresses](/stakedhype/integrate/contract-addresses)
* [Governance Risk](/stakedhype/transparency-and-risks/upgrade-and-risk-governance)
* [Transparency and Risks](/stakedhype/transparency-and-risks)


# Monitoring

Last updated: 2026-02-24

This page explains how stHYPE monitoring works in plain terms, what happens during incidents, and how safety controls are used.

## At a Glance

* stHYPE does not rely only on off-chain bots for core safety.
* Critical checks are enforced on-chain and can block unsafe actions automatically.
* Off-chain monitoring is used for detection, escalation, and incident coordination.
* Off-chain alerts do **not** auto-submit pause transactions.
* Pause actions are operator-confirmed, role-gated, and time-bounded on-chain.

## How stHYPE Monitoring Works

stHYPE uses two control layers:

1. **Automatic on-chain safety checks**

* Critical conditions are checked directly in contract execution.
* Unsafe state transitions are reverted without waiting for off-chain responders.

2. **Off-chain monitoring and response**

* Monitoring detects market, operational, and control-plane risk signals.
* On-call responders triage, escalate, and execute role-gated actions when needed.

## Key On-Chain Safety Guarantees

Without operator intervention or off-chain monitoring services:

* Pending-slash checks can block unsafe mint/redeem behavior.
* Rebase safety bounds can revert unsafe supply changes (`AprTooHigh`, `SupplyDecreaseTooHigh`).
* Queue/liability checks prevent unsafe redemption progression.

In the event of operator initiated pausing:

* Pause duration is bounded on-chain (`> 0` and `<= 14 days`).

## What We Monitor

Public monitoring coverage includes:

* role changes, pause/unpause operations, and upgrades,
* mint/burn/redeem queue health and solvency posture,
* rebase and slashing-accounting signals,
* staking-module allocation and withdrawal-status signals,
* critical address and control-plane activity,
* secondary market stress (for example depeg and liquidation pressure).

All data publicly accessible. Operators use internal services and alert systems. In the future, bi-weekly reports will be published and posted in documentation on size of queue health, mean/median time to withdraw, secondary market peg health, and other key metrics.

## Incident Severity and Escalation

We classify incidents into:

* `SEV-1`: critical user-impacting safety incident.
* `SEV-2`: major degradation or elevated risk requiring active intervention.
* `SEV-3`: non-critical degradation requiring planned remediation.

Operations coverage is timezone-distributed with designated primary/backup ownership and escalation paths.

Public response commitments are severity-based and qualitative:

* `SEV-1`: immediate triage and active incident coordination.
* `SEV-2`: rapid triage and active remediation.
* `SEV-3`: planned remediation with tracking.

## Incident Playbooks

Our incident runbooks are organized around the main risk classes:

* pending-slash or slashing-accounting incidents,
* queue/liquidity stress incidents,
* privileged-key/control-plane incidents,
* infrastructure dependency disruptions.

## Safety Control Matrix

| Trigger                                   | Detection Path                                 | Automatic Contract Behavior                                              | Operator-Confirmed Action                                         | Authority + Bounds                                                            |
| ----------------------------------------- | ---------------------------------------------- | ------------------------------------------------------------------------ | ----------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| Pending slash state                       | `pendingSlashExists` / `_pendingSlashExists()` | `mint` blocked; `redeem` non-redeemable; `maxRedeemable` can drop to `0` | Assess slash state and execute bounded pause if needed            | `DEFAULT_ADMIN_ROLE` + `REBASER_ROLE`; pause duration bounded by `<= 14 days` |
| Slash exceeds configured cap              | `_accountForSlashing()` during `rebase()`      | `rebase` reverts with `SupplyDecreaseTooHigh`                            | Keep burns/redemptions paused if needed; run incident process     | `DEFAULT_ADMIN_ROLE`; bounded pause controls                                  |
| Excessive positive APR/supply change      | `rebase()` APR check                           | `rebase` reverts with `AprTooHigh`                                       | Investigate state/config and run safe rebase workflow             | `REBASER_ROLE` (+ admin for config updates)                                   |
| Queue or solvency stress                  | Queue and liability checks                     | Unsafe redemptions remain blocked by on-chain checks                     | Execute queue/liquidity operations and incident communications    | Operations + role-gated module workflows                                      |
| Predicted slash not yet readable on-chain | Off-chain monitoring + governance intel        | No automatic off-chain pause execution                                   | Operator-confirmed `pauseRedemption`, `pauseBurns`, or both       | `DEFAULT_ADMIN_ROLE`; bounded by configured pause duration                    |
| Suspicious privileged-key activity        | Control-plane monitoring                       | No automatic off-chain pause by bot                                      | Immediate containment, rotation flow, and incident communications | Multisig-governed admin controls                                              |

## What Users and Integrators Should Expect

* Withdrawals are user-triggered on-chain (`burn`, `burnAndRedeemIfPossible`, `redeem`).
* During slash risk or incident conditions, burns/redemptions can be temporarily constrained by safety logic or bounded pause controls.
* Burn/redemption pauses are protocol-wide and time-bounded.
* Address-level transfer-disable toggles are transfer-path controls and are separate from withdrawal-queue accounting.

See [Integrate stHYPE](/stakedhype/integrate) and [Roles Registry](/stakedhype/transparency-and-risks/roles-and-controls-registry) for implementation details.

## Disclosure Boundaries

For security reasons, this page does not publish:

* full provider/vendor topology,
* exact alert-channel internals,
* sensitive responder identity details.

Public dinsclosure is intentionally scoped to moitoring domains, severity process, control behavior, and authority boundaries.


# Governance Risk

Last updated: 2026-10-16

This page defines the current governance execution model and the roadmap direction for upgrade controls.

## Current State

* Protocol execution is managed by smart contracts, without centralized custody
* Constrained operations such as staking, unstaking, and rebasing are handled by permissioned keeper functions. Keeper functions are unable to act outside of the smart contract boundaries, and never custody funds.
* Currently, protocol security upgrades are managed by multisig/role-admins
* `DEFAULT_ADMIN_ROLE` and proxy-admin ownership paths control privileged operations.
* There is currently no active on-chain veto mechanism enforcing upgrades.
* stHYPE proxy upgrades are subject to a 48-hour on-chain timelock.

For technical role scope, see [Roles Registry](/stakedhype/transparency-and-risks/roles-and-controls-registry).

## Roadmap Direction (Public Scope)

* A 48-hour on-chain timelock is already in place for proxy upgrades.
* stHYPE holder veto design direction follows a dual-governance style model, pioneered by Lido's Dual-Governance Framework
* Timelines for Dual-Governance Framework with follow the adoption of Valantis Governance in 2026.

## Governance Transparency Commitments

When governance execution is activated, public disclosures will include:

* activation status and scope,
* execution safeguards (for example quorum/threshold/timelock parameters),
* concentration-risk disclosures and change-log records.

## Current Risk Interpretation

Any voting-power concentration analysis should be interpreted as a forward-looking governance risk until token voting is actually wired to execution pathways.

Existing Multisig actions are well documented in [Registry](/stakedhype/transparency-and-risks/roles-and-controls-registry).

See also:

* [Transparency and Risks](/stakedhype/transparency-and-risks)
* [For Validators](/stakedhype/community-codes)


# Integrate stHYPE

How to integrate staking and unstaking stHYPE on your frontend or from smart contracts.

## Integrate

{% hint style="danger" %}
If you are a DeFi protocol interacting with StakedHYPE contracts, PLEASE familiarize yourself with the [relationship](/stakedhype/integrate/wsthype) between stHYPE/wstHYPE.
{% endhint %}

### Operational Safety Notes for Integrators

Before integrating, account for protocol safety controls and queue behavior:

1. `burnAndRedeemIfPossible` can redeem instantly only up to currently available liquidity (`maxRedeemable()`); remainder enters queue and must be claimed later via `redeem(burnId)`.
2. Redemptions and burns can be paused by role-gated controls in `Overseer`.
3. `pauseDuration` is configurable, must be `>0` and `<=14 days`, and is initialized to `7 days` in current V3 initialization.
4. Mint/redeem paths include slashing-aware checks (`pendingSlashExists`) that can temporarily block actions until accounting catches up.
5. Address-level transfer-disable toggles exist in `stHYPE`/`wstHYPE` (`setSelfDisableTransfer`) and affect transfer behavior, not queue accounting.

Recommended integration behavior:

* Always handle reverts and retryable states around burns/redemptions.
* Surface queued-withdrawal state clearly in UI.
* Treat pause/slashing windows as expected safety behavior, not exceptional protocol failure.

#### Minting (Staking)

1. Send a transaction to the overseer with the function signature `mint(address to, uint256 communityCode)(uint256)` , which returns the amount of StakedHYPE (as of right now this will always be the same amount as minted). There is also another function signature `mint(address to)` that is callable if you do not have a community code to stake to. The `to` address is the address the stHYPE tokens will be minted to and the `communityCode` is the code representing the validator you want those tokens to be designated too. **The amount minted will be the amount of HYPE included in the value of the transaction**. There is no onchain Community Code validation - please ensure you are using the right one.
2. This will mint stHYPE to the user.

```solidity
function Example_Mint() public {
    address user = address(0x1234);
    vm.deal(user, 10 ether);

    vm.startPrank(user); // using the private key of the user
    uint256 mintedShares = overseer.mint{value: 10 ether}(user, "<validator code>"); // mint 10 stHYPE
    
    overseer.mint{value: 10 ether}(user); // mint another 10 stHYPE to user
}
```

#### Community Codes

These will be whitelisted in a public, transparent offchain indexer for governance approved validators. This index was originally onchain prior to the Hyperliquid gas/s updates.

These are passed as a param to the staking and unstaking functions in order to track HYPE flow and rewards throughout the ecosystem.

#### Burning (Unstaking)

Burning is has the *potential* to be a multistep process depending on the amount of free (unstaked) tokens available in the protocol. There will typically always be a small float of the total supply unstaked in order to instantly fulfill burns, but if it is the burn of a large amount of tokens or there is high outflow volume steps become a two-step process. You can access the amount of free tokens (if a burn has less than this amount it will be processed atomically) by calling `maxRedeemable()`

1. Approve the overseer with the amount of stHYPE tokens that you want to unstake.
2. Call `burnAndRedeemIfPossible(address to, uint256 amount, string communityCode)` to burn `amount` of tokens from `communityCode` the redeemed HYPE will go to the `to` address. Note: if you do not want to burn from a community code leave the field a blank string (""). `maxRedeemable()` of these tokens will be burned instantly and sent to the `to` address, and the rest will be processed in a burn request. This function returns the `burnID` which will be used to redeem the burn once it has been finished.
3. If this was a large burn or there was not enough tokens, wait some time until `redeemable(uint256 burnID` is `true`
4. Call `redeem(uint256 burnID)` which will send the pending HYPE to the `to` address specified in the previous transaction

```solidity
function Example_Burn() public {
    uint256 decimals = 10 ** 18;

    address user = address(0x1234); // set up with a balance of 10 stHYPE
    vm.startPrank(user);
    
    // 1. approve 10 stHYPE (18 decimals)
    sthype.approve(overseer, 10 * decimals); 

    // 2. redeem the max amount of tokens instantly available
    uint256 maxRedeemable = overseer.maxRedeemable(); // 5 HYPE
    uint256 burnID = overseer.burnAndRedeemIfPossible(address(user), 10 ether, "<validator code>");
    require(address(user).balance == 5 ether, "user should have 5 HYPE now");
    
    // 3. wait some time
    
    // ...
    
    // 4. redeem the burn for the rest of the tokens
    overseer.redeem(burnID);
    require(address(user).balance == 10 ether, "user should have all of their HYPE now");
}
```

## stHYPE on HyperCore

{% hint style="info" %}
stHYPE on HyperCore is currently not tradable on any order book since the deprication of [USDH](https://usdh.com). stHYPE can be freely bridged between HyperEVM and HyperCore, and can be trasferred between active HyperCore addresses for zero fee.
{% endhint %}

{% hint style="danger" %}
stHYPE on HyperCore follows the wstHYPE interface. 1 stHYPE on Core = 1 wstHYPE. Yield accrues to stHYPE on Core in the same way as wstHYPE on HyperEVM.

1 wstHYPE > 1 HYPE which will explain the lower balance shown when briding between HyperCore and HyperEVM. There are no fees or reduction of underlying balance when bridging between HyperCore and HyperEVM.
{% endhint %}

stHYPE on HyperCore accrues yield at the same rate as wstHYPE/stHYPE on HyperEVM.

1 stHYPE on HyperCore = 1 wstHYPE on HyperEVM at all times. User's never need to worry about claiming yield on HyperEVM or HyperCore.

stHYPE not currently listed on the HyperCore Order Book as a tradeable market since USDH shutdown.


# wstHYPE <> stHYPE

Pioneering a new, more efficient token model.

## Summary

stHYPE is the rebasing interface for staked HYPE

* 1 stHYPE = 1 HYPE wstHYPE is the yield-bearing interface for staked HYPE
* 1 wstHYPE > 1 HYPE

on HyperEVM, user's hold both tokens (no wrapping required) and can chose to interact with either interface. This is a novel token mechanism and should be reviewed carefully.

stHYPE on HyperCore is a yield-bearing interface, like wsthype. There is no rebasing on HyperCore.

* 1 stHYPE on HyperCore = 1 wstHYPE

## Summary

Liquid staking tokens are typically faced with a dilemma: whether or not they should pick rebasing or yield-bearing LST.

#### Rebasing

* [Amazing](https://t.me/chainflip_io_chat/121821) and easy to understand user experience
* Require wrapping into a separate token for DeFi compatibility
* Deemed a "Mind Virus" by Sam Kazemian due to painful DeFi interactions

#### Yield-Bearing

* Painful for users to understand: "Why am I immediately losing money!?!"
* Very easy to integrate into DeFi

What if we could get the best of both worlds? With stHYPE you can!

## wstHYPE Contract Address

<https://hyperevmscan.io/token/0x94e8396e0869c9f2200760af0621afd240e1cf38>

### Implementation on HyperEVM

For stakedhype, we have stHYPE and wstHYPE simultaneously! The Overseer mints/burns from the stHYPE token contract. wstHYPE reads the share balances from the stHYPE contract and has admin transfer rights to manipulate the balances.

Ultimately, rebasing and yield-bearing are just different representations of the same thing. Yield-bearing tokens display a share value which represent a portion of total supply. Rebasing tokens perform the multiplication to show you how much your shares are worth.

wstHYPE and stHYPE are just different interfaces to interact with the same data. This means that when you transfer/mint/burn stHYPE, it will perform the same action for wstHYPE. Users and DeFi protocols can interact with both interfaces seamlessly without wrapping, allowing users and DeFi protocols alike to have an easy UX!

### Caveats <a href="#caveats" id="caveats"></a>

{% hint style="danger" %}
This dual-token model introduces a significant vulnerability for certain DeFi integrations. It is very simple to mitigate! Be Wary!
{% endhint %}

These types of multi-entrypoint tokens have caused issues in the past. Please read this vulnerabilty [report](https://medium.com/chainsecurity/trueusd-compound-vulnerability-bc5b696d29e2) of another protocol for more information.

Contracts and EOAs can self disable their transfer functionality by calling `setSelfDisableTransfer(bool status)`on either stHYPE or wstHYPE.


# Contract Addresses

## Addresses

#### Testnet

<table><thead><tr><th width="209">Contract</th><th width="252">Proxy</th></tr></thead><tbody><tr><td>stHYPE</td><td>0xe2FbC9cB335A65201FcDE55323aE0F4E8A96A616</td></tr><tr><td>OverseerV1</td><td>0x371de8EBDA2ebB627a4f6d92bD6d01eC385A309b</td></tr><tr><td>wstHYPE</td><td>0x13d76D68170bD5e75eaa18eb074a2f0562f3e6ca</td></tr></tbody></table>

#### Mainnet

<table><thead><tr><th width="211">Contract</th><th width="245">Proxy</th></tr></thead><tbody><tr><td>stHYPE</td><td>0xfFaa4a3D97fE9107Cef8a3F48c069F577Ff76cC1</td></tr><tr><td>OverseerV1</td><td>0xB96f07367e69e86d6e9C3F29215885104813eeAE</td></tr><tr><td>wstHYPE proxy</td><td>0x94e8396e0869c9F2200760aF0621aFd240E1CF38</td></tr></tbody></table>


# Valantis Prime Trading

Valantis Prime unlocks new experiences on HyperCore securely through CoreWriter.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2F1lQ7z7cQwkzIu5Xb782P%2Fbreathing-orb-hq.gif?alt=media&amp;token=48db74fc-10cf-4730-a204-eb85b0680327" alt=""><figcaption></figcaption></figure>

Prime is a system for programming HyperCore without needing to outsource security to EVM DeFi, pooling funds, or giving up sovereignty over trading balances. Balances and security live on HyperCore by default - and gain opt-in functionality boosts from EVM programmability.

Its core use cases today are:

* Liquid Staking HyperCore Trading Discounts
* Cross EVM x HyperCore DCA

## Documentation Structure

For Traders:

1. [Prime Staking Discounts](/prime/discounts): Compare the benefits, choose a strategy, and set up a Prime Account.
2. [Using the Terminal](/prime/terminal): Exporting API Wallets, Managing Account, Trading, etc.
3. [Fees for Staking Discounts Traders](/prime/fees): Valantis Fee Structure.

For Developers:

1. [**Valantis Prime EVM Extensions**](/prime/thesis)**:** Connecting HyperCore with EVM Applications.
2. [**Prime Architecture**](/prime/developers/architecture)**:** Core system model and security boundaries.
3. [**Account Features**](/prime/developers/account)**:** Agents, Connectors, Allowances, Sessions, and Guardians.
4. [**HyperCore Connector**](/prime/developers/hypercore-connector)**:** HyperCore-specific programmable controls.

[**Prime DCA**](/prime/dca)**:** First production Prime Connector cross HyperEVM x HyperCore order type.

## License

BUSL-1.1


# Prime Staking Discounts

prime.valantis.xyz

Lower your Hyperliquid trading fees & access specialized strategies.

Discover what Valantis Prime Liquid Staking Discounts unlocks:

* **Borrow:** Prime Traders can access an extra 59% in USDC margin against their staked HYPE while keeping their Staking Discount.
* **Upgrade:** Prime Traders can upgrade their staking tiers for 2x less capital by using the stHYPE Looping Vault.
* **Hedge:** Prime Traders can access HYPE Staking Tier Discounts while effeciently hedging HYPE exposure more effeciently than Native Staking.
* **Earn:** Prime Traders get access to stHYPE's higher than native staking yield which can be used in basis trades, looping strategies, covered call strategies, and vault strategies while maintaining Trading Fee Discounts.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-562d6ae8769f6167165e08c9fa31125d0df78e5d%2F00_Valantis%20Prime%20Staking%20Dscounts%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

## Start with the profile that sounds like you

| You are                                                         | Start here                                                                               | What it unlocks                                                                                                           |
| --------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| Hold HYPE and borrow trading capital                            | [Unlock USDC Margin](/prime/discounts/strategies/usdc-margin)                            | Borrow USDC against wstHYPE without dropping the fee tier.                                                                |
| Within 2x of the next staking tier                              | [Upgrade Tiers with the 2x Vault](/prime/discounts/strategies/2x-vault)                  | Target the next tier with roughly half the HYPE deposit in our Premier managed looping strategy vault targeting 4–6% APY. |
| Staking & using Portfolio Margin                                | [Use Portfolio Margin](/prime/discounts/strategies/portfolio-margin)                     | Keep the tier & turn staked HYPE into PM collateral.                                                                      |
| Sensitive to HYPE price/ running a hedge but want Fee Discounts | [Stay Delta-Neutral](/prime/discounts/strategies/delta-neutral)                          | Run a more flexible hedge with stHYPE and short HYPE perps against it.                                                    |
| Warehousing HYPE as a market maker or prop desk                 | [Put Market-Maker Inventory to Work](/prime/discounts/strategies/market-maker-inventory) | Add yield, a fee tier, and a standby USDC line to existing inventory.                                                     |
| long term spot HYPE maximizing yield                            | [Stack Yield with Covered Calls](/prime/discounts/strategies/covered-calls)              | Add option premium while Rysk-held wstHYPE continues to count.                                                            |
| Running spot/perp basis and funding trades                      | [Run the Looped Basis Trade](/prime/discounts/strategies/looped-basis)                   | A unique basis trade unlocked from staking spread, perp funding, and cheaper rebalances.                                  |

## What you get

| Benefit                          | What it means for you                                                                                                                                                                                                                                                                                                    |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Lower trading fees               | Your stHYPE balance qualifies a Prime trading account for Hyperliquid's staking tiers. The staking discount applies after your volume tier.                                                                                                                                                                              |
| Higher-than-native staking yield | stHYPE normally earns about **2.4%**, with periods as high as **3%**, including a share of trading volume generated through Valantis Prime.                                                                                                                                                                              |
| Working collateral               | Borrow up to **59% LTV in USDC on HyperLend** while supported wstHYPE positions in HyperLend, Felix, and Rysk continue to count toward your Prime holding requirement.                                                                                                                                                   |
| Practical liquidity              | <p>Deep DEX liquidity and the stHYPE redemption buffer usually provide an instant exit. Users typically paid <strong>1 bps</strong> - <strong>3 bps</strong> to exit over the trailing 90 days; trailing 60 days gave an average of 1.3 day 0 fee withdrawal timelines due to stHYPE Buffer.<br>(Snapshot July 2026)</p> |

## Tier requirements

The professionally managed HyperLend e-mode strategy vault (stHYPE Vault) targets 4–6% APY and can target each Prime-supported tier. Borrow rates can make carry negative and cause the manager to unwind, but the discount does not drop merely because the leveraged portion unwinds.

| Prime tier | Standard HYPE requirement | Approx. 2x Vault deposit | Hyperliquid staking discount |
| ---------- | ------------------------: | -----------------------: | ---------------------------: |
| Wood       |                  10+ HYPE |                  5+ HYPE |                           5% |
| Bronze     |                 100+ HYPE |                 50+ HYPE |                          10% |
| Silver     |               1,000+ HYPE |                500+ HYPE |                          15% |
| Gold       |              10,000+ HYPE |              5,000+ HYPE |                          20% |
| Platinum   |             100,000+ HYPE |             50,000+ HYPE |                          30% |

These percentages reduce the applicable Hyperliquid volume-tier fee; they are not basis points.

Trades through the Prime UI incur a Valantis fee equal to 30% of the staking savings. Valantis collects no trading-volume fees on API or external-terminal trades. Third-party builder-code fees may differ.

See [Fees](/prime/fees) for Hyperliquid maker and taker rates with staking and the separate interface-fee policy.

The Diamond tier requires 500,000 HYPE, provides a 40% Hyperliquid staking discount, and is currently available only by special request.

## What can change your discount

Your qualifying balance can sit in supported DeFi integrations, but it must remain above the selected tier requirement. If it falls below the requirement, a 5-day notice period begins. Refill the balance during that period and the notice resets.

Each strategy adds its own risks—borrow rates, slashing, options assignment, funding, margin, or smart contracts. The strategy pages explain those tradeoffs before showing setup steps.

## Next

1. Read [How Prime Discounts Work](/prime/discounts/how-it-works) for account ownership and security boundaries.
2. Use [Choose Your Strategy](/prime/discounts/strategies) to compare the paths in one table.
3. [Set up a Prime Account](/prime/discounts/setup) and begin trading.


# How Prime Discounts Work

This page covers the Valantis Prime technical architecture for how Traders access Staking Discounts.

## What is a Valantis Prime Account?

A Valantis Prime Account is a CoreWriter smart contract owned by the trader’s EOA. In a staking-discount account, the trader and stHYPE protocol control different actions, as shown below. The trader retains live trading permissions during normal operation and the shutdown notice period; HyperCore access is restricted during shutdown.

The purpose of this architecture is to safely separate Trading Balances (Trader) from Staking Balances (stHYPE Protocol)

* The Trader never gives up custody of their trading assets.
* The Staker never exposes their HYPE to the Trader.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-f775e6431cf4ca8498f4506da74054b196d7cbcb%2Ftradingf_01_Valantis%20Prime%20Staking%20Dscounts_V2.png?alt=media" alt=""><figcaption></figcaption></figure>

The Staking Discount is applied to the Valantis Prime Account, not the Trader's EOA directly.

The Trader's EOA interacts with the Valantis Prime Account through CoreWriter and API Wallets. Using API wallets - the Trader can trade directly on HyperCore with no latency difference.

While using [prime.valantis.xyz](https://prime.valantis.xyz) this experience is abstracted from you.

## Is this Stake Linking?

No. This solution is unique from [Stake Linking](https://hyperliquid.gitbook.io/hyperliquid-docs/trading/fees?q=Stak#staking-linking).

Stake Linking would give permanent control of your trading address to the stHYPE protocol. With Valantis Prime, the trader retains account ownership. During normal operation, stHYPE cannot transfer or withdraw the trader’s spot or perp balances. During shutdown, HyperCore access is restricted and cleanup may close positions, as described in the [Staking Discounts Risk Matrix](/prime/developers/staking-discounts-risk-matrix).

## Is this Self Custodial?

Yes. Claiming the account makes the trader its owner, and ending the staking-discount relationship does not change that ownership.

During shutdown, access to HyperCore functions is temporarily restricted while the managed staking balance is recovered. EVM balances remain accessible through the parent Prime Account. HyperCore access returns after the managed exit is completed.

Any future rewards distributed to the Prime address for HyperCore or HyperEVM activity belong to the trader. Access to assets on HyperCore remains subject to the shutdown restrictions described above.

The Valantis Prime Account is immutable. Its action permissions and the staking-discount lifecycle determine which functions the registered owner can access at each stage.

## Where can I use a Valantis Prime Account?

API wallets are used to trade with your Valantis Prime Account.

Prime accounts can trade through:

* [prime.valantis.xyz](https://prime.valantis.xyz).
* The Hyperliquid API and SDKs.
* Third-party interfaces that support API-wallet imports.

At the time of writing, [app.hyperliquid.xyz](https://app.hyperliquid.xyz) does not support API wallet imports.

At the time of writing, Valantis has not released support for third party Builder Code approvals.

For the best experience, use [prime.valantis.xyz](https://prime.valantis.xyz) or official Hyperliquid API.

## Controls during normal operation

| Trader controls                                                                                        |
| ------------------------------------------------------------------------------------------------------ |
| Spot and perp balances.                                                                                |
| API wallet listing delisting.                                                                          |
| Deposits and withdrawals.                                                                              |
| The owner EOA and Prime smart account.                                                                 |
| Full control of their stHYPE Balance held in owner EOA wallet.                                         |
| All CoreWriter action IDs except staking, unstaking, validator delegation, and builder code approvals. |

| stHYPE Protocol controls                                           |
| ------------------------------------------------------------------ |
| Owns Native Staking Balance used for your Prime Discount.          |
| Validator selection and delegation.                                |
| Builder Code approvals.                                            |
| Starting the timelocked shutdown path if requirements are not met. |

stHYPE cannot transfer or withdraw the trader's spot or perp balances during normal operation. The detailed action matrix is available in the [Staking Discounts Risk Matrix](/prime/developers/staking-discounts-risk-matrix).

## Safety model

Audits are listed in [Resources](/resources/audits#valantis-prime).

Valantis Prime never pools or mixes funds.

Next: [choose a strategy](/prime/discounts/strategies) or [set up your Prime account](/prime/discounts/setup).


# How Traders Are Using Liquid Staking Discounts

Liquid Staking Discounts are a powerful technology that (for the first time) combines properties of Liquid Staking & Native Staking Trading Fee Discounts.

Here is how we have seen Traders use this new technology to unlock new strategies.

Select your profile, and learn how the product can benefit you.

<table><thead><tr><th width="186.00390625">Goal</th><th width="146.7578125">Strategy</th><th width="207.01171875">Main benefit</th><th width="199.1875">Main tradeoff</th></tr></thead><tbody><tr><td>Reach the next tier with less HYPE</td><td><a href="/prime/discounts/strategies/2x-vault">2x Vault</a></td><td><p>Half the HYPE required per tier.</p><p>Privileged looping vault targeting 4–6% target APY.</p></td><td>Fluctuating borrow rates can cause decreased returns.<br><br>E-mode looping vault has increased exposure to stHYPE slashing risk.<br><br></td></tr><tr><td>Access USDC Trading Margin against your staked HYPE.</td><td><a href="/prime/discounts/strategies/usdc-margin">USDC Margin</a></td><td>Up to 59% LTV on HyperLend while the collateral earns yield &#x26; discount.</td><td>Variable USDC borrow rate and lending liquidation risk</td></tr><tr><td>Keep staking benefits while using PM</td><td><a href="/prime/discounts/strategies/portfolio-margin">Portfolio Margin</a></td><td>HyperCore's native PM experience with 39% LTV, one-click coin-margin against staked HYPE.<br><br>PM with Staking Yield &#x26; Trading Fee Discount.</td><td>Less PM capacity than raw spot HYPE plus two borrow-rate layers (exposed to Hyperlend e-mode HYPE borrow rates)</td></tr><tr><td>Remove most HYPE direction</td><td><a href="/prime/discounts/strategies/delta-neutral">Delta-Neutral Tier</a></td><td>Keep the tier and yield while shorting HYPE perps</td><td>Funding can flip.<br>Exposure to HyperEVM USDC borrow rates if running short with coin-margin.<br>the short needs margin and rebalancing</td></tr><tr><td>Maximize basis carry</td><td><a href="/prime/discounts/strategies/looped-basis">Looped Basis Trade</a></td><td>Staking spread + funding + cheaper rebalances</td><td>Borrow-rate, funding, perp-margin, slashing, and contract risk</td></tr><tr><td>Improve existing HYPE inventory</td><td><a href="/prime/discounts/strategies/market-maker-inventory">Market-Maker Inventory</a></td><td>Higher-than-native yield, lower fees, and collateral utility</td><td>stHYPE and integration smart-contract risk</td></tr><tr><td>Add option premium</td><td><a href="/prime/discounts/strategies/covered-calls">Covered Calls</a></td><td>Staking yield + call premium + fee tier</td><td>Capped upside; assignment can put the tier at risk</td></tr></tbody></table>

If you already hold or natively stake HYPE, the simplest starting point is often to convert only the amount needed for your current tier. Add leverage, borrowing, options, or hedging only when the extra benefit matches a job your portfolio already needs.


# Upgrade Tiers with half the HYPE required

Target the next staking tier with roughly half the HYPE deposit.

The 2x Vault is a professionally managed HyperLend e-mode leverage strategy. It borrows HYPE against wstHYPE, restakes the borrowed HYPE, and targets roughly 2x qualifying exposure with a **4–6% target APY**.

## Tier requirements

| Prime tier | Standard requirement | Approx. 2x Vault deposit | Gross fee discount |
| ---------- | -------------------: | -----------------------: | -----------------: |
| Wood       |             10+ HYPE |                  5+ HYPE |                 5% |
| Bronze     |            100+ HYPE |                 50+ HYPE |                10% |
| Silver     |          1,000+ HYPE |                500+ HYPE |                15% |
| Gold       |         10,000+ HYPE |              5,000+ HYPE |                20% |
| Platinum   |        100,000+ HYPE |             50,000+ HYPE |                30% |

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-1e54d7a82c6891b5313be8706a1a7a5b5e0ad7e0%2Flooping%20vault.png?alt=media" alt=""><figcaption></figcaption></figure>

## When it fits

* Your current HYPE balance is within 50% of the next tier requirement.
* Your trading volume makes the next tier valuable.
* Boosted APY for increased DeFi Lending exposure is appropriate.

## Risks

* **Target APY is not guaranteed.** Borrow costs can exceed staking income.
* **No market-depeg liquidation path.** HyperLend e-mode uses the wstHYPE/HYPE exchange rate, so a market depeg does not reduce the health factor.
* **Unwind costs.** In borrow rate spikes, strategiests may need to unwind positions using DEX liquidity. In a July 2026 snapshot - this carries a 1-3bps loss per loop; although unstake queue shows average unwinds in 1-3 days which makes DEX swapping an option of last resort. This is managed entirely by the strategist and abstracted from users.
* **Slashing risk remains.** Validator slashing can reduce the exchange rate and, at sufficient severity, impair the loop.
* **Smart-contract risk remains.** The strategy depends on stHYPE, HyperLend, wrappers, and vault management.

The trader's discount does **not** drop merely because the manager unwinds the leveraged portion. This separates the fee-tier benefit from the vault's short-term carry decision.

See [Fees](/prime/fees) to value the tier at your volume.


# Unlock USDC Margin

Use wstHYPE as a standby USDC line without giving up staking yield or your Prime tier.

There are two models for accessing USDC margin against your stHYPE

* EVM Lending Protocols
* HyperCore [Portfolio Margin stHYPE Strategy](/prime/discounts/strategies/portfolio-margin)

This section covers EVM Lending Protocols. Both EVM and Portfolio Margin allow accessing more margin against your stHYPE.

* Portfolio Margin is better for active Traders. Less margin, but easier to manage borrowing risk. Borrowing happens on HyperCore.
* HyperEVM Borrowing is better for active stablecoin borrows and active risk management. More margin, but liquidation risk is managed between both HyperEVM and HyperCore.

## HyperEVM USDC Margin

On HyperLend, wstHYPE supports a **59% maximum LTV**, **74% liquidation threshold**, and **15% liquidation penalty** for USDC borrowing.

Illustrative values use HYPE at **$67.78 on July 15, 2026**. Rates and prices change.

Parameters: [HyperLend markets API](https://api.hyperlend.finance/data/markets?chain=hyperEvm), accessed July 15, 2026.

| Tier-sized wstHYPE position | Approx. collateral value | USDC at 40% LTV | USDC at 59% max LTV |
| --------------------------- | -----------------------: | --------------: | ------------------: |
| Wood — 10 HYPE              |                     $678 |            $271 |                $400 |
| Bronze — 100 HYPE           |                    $6.8k |           $2.7k |               $4.0k |
| Silver — 1,000 HYPE         |                   $67.8k |          $27.1k |              $40.0k |
| Gold — 10,000 HYPE          |                  $677.8k |         $271.1k |             $399.9k |
| Platinum — 100,000 HYPE     |                   $6.78M |          $2.71M |              $4.00M |

A lower operating LTV leaves more room for slashing, oracle movement, interest accrual, and parameter changes.

Felix also has Morpho-based markets for borrowing USDC against wstHYPE and for looping, but available liquidity is smaller. HyperLend is the primary venue for the capacity analysis above. Felix CDP feUSD is also a method for accessing stablecoin liquidity against wsthype and maintaining discount.

## How To Unlock USDC via Hyperlend

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-d2c2cc00095fc2446710f6109018503b3a1c9471%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>

NOTE: This strategy requires that you disable E-mode on Hyperlend.

## What to do with your extra USDC

Works for both EVM borrowing and Portfolio Margin

* Working USDC margin for active trading. Keep holding spot HYPE, but unlock extra USDC for active trading.
* You want to increase HYPE exposure. Long HYPE using stHYPE as collateral.
* Hedge HYPE price. You need tactical liquidity for a hedge, drawdown, or short-lived trading opportunity.

## Cost and risk

* **Borrow rate:** USDC rates are utilization-driven and can change sharply. Treat this as a line you draw when needed, not automatically as permanent leverage. It requires active switching and movement of funds between HyperEVM and HyperCore to manage risk.
* **Liquidation:** the position can be liquidated below health factor 1. HyperLend's wstHYPE oracle follows redemption value rather than DEX prices, so a sthype market depeg alone does not trigger liquidation; validator, HIP-3 slashing, or stHYPE smart contract risk can reduce collateral value and cause liquidation.
* **Penalty:** liquidation carries the configured 15% penalty.
* **Protocol risk:** the position depends on stHYPE and HyperLend contracts.

Your wstHYPE remains tier-eligible while supplied to supported HyperLend markets.


# Use Portfolio Margin

Note: Enable Account Portfolio Margin will be made available in a future upgrade. Valantis Prime does not support Portfolio Margin as of July 15 2026.

Keep the staking tier and stHYPE yield while routing part of the position back into Hyperliquid Portfolio Margin.

Hyperliquid Portfolio Margin gives spot HYPE a **0.5 LTV** and lets spot HYPE offset HYPE perp exposure. Natively staked HYPE is outside the PM collateral balance. For a Prime account with PM enabled, the current route is:

1. Supply wstHYPE to HyperLend e-mode.
2. Borrow HYPE against it.
3. Move the borrowed HYPE to HyperCore spot.
4. Use that spot HYPE as PM collateral

## Capacity, cost, and what you give up

At HyperLend's 77.77% maximum e-mode LTV:

```
PM capacity per $1 of wstHYPE
= 77.77% routed as HYPE × 50% PM LTV
= 38.885%
```

Raw spot HYPE has 50% PM capacity. The Prime route therefore gives up about **$0.111 of capacity per collateral dollar**, or **22.2% relative to raw spot HYPE**, at the maximum e-mode setting. In exchange, the underlying wstHYPE keeps its yield and Prime tier.

| Structure                           | Fee tier                               | Staking yield                              | PM capacity per $1 of HYPE value | Main cost                                    |
| ----------------------------------- | -------------------------------------- | ------------------------------------------ | -------------------------------: | -------------------------------------------- |
| Native staking                      | Yes                                    | Native staking yield                       |                            $0.00 | No PM utility while staked                   |
| Raw spot HYPE in PM                 | No staking tier from that spot balance | None                                       |                            $0.50 | PM stablecoin borrow rate                    |
| Prime wstHYPE → HyperLend HYPE → PM | Yes                                    | About 2.4% normally, with periods up to 3% |                     Up to $0.389 | HyperLend HYPE borrow + PM stablecoin borrow |

HyperLend WHYPE borrow was about 1% at the July 15, 2026 snapshot. Hyperliquid PM stablecoin borrowing has a separate **5% base APY** and follows:

```
PM stablecoin borrow APY
= 5% + 475% × max(0, utilization − 80%)
```

The PM rate therefore rises sharply above 80% utilization. Both borrow rates are variable and apply to different legs of the route.

## When it fits

* You are already staking for a fee tier and already use Portfolio Margin.
* The tier value plus stHYPE yield is worth more than the extra borrow cost and the reduction from $0.50 to about $0.389 of maximum PM capacity per collateral dollar.
* You use spot HYPE to offset a HYPE perp hedge and want the qualifying stake to stay productive.

## How to use stHYPE Portfolio Margin

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-47aa120e7bbfe03437a777899af603a7c3d2c1a6%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>

## Risks and limits

* Confirm that Portfolio Margin is enabled for the Prime account before relying on this route.
  * NOTE: Requires account upgrade for legacy users.
* The route adds stHYPE, HyperLend E-mode, & PM margin risk.
* A DEX market depeg does not create HyperLend liquidation because the e-mode oracle uses the wstHYPE/HYPE exchange rate. Validator slashing, HIP-3 slashing can.

See the [official Portfolio Margin documentation](https://hyperliquid.gitbook.io/hyperliquid-docs/trading/portfolio-margin) for eligibility, caps, and current rates.


# Put Market-Maker Inventory to Work

Convert strategic or idle HYPE inventory into stHYPE so the same balance earns yield, qualifies the desk for lower fees, and remains available as collateral.

stHYPE normally earns about **2.4%**, with periods as high as **3%**. It can earn more than native staking because holders also receive a share of trading volume generated through Valantis Prime.

## What changes

| Before                            | With Prime stHYPE                                                             |
| --------------------------------- | ----------------------------------------------------------------------------- |
| HYPE inventory or native stake    | Higher-than-native stHYPE yield                                               |
| Native staking tier only          | Prime tier while the balance remains usable in supported DeFi                 |
| No USDC line against native stake | Up to 59% LTV on HyperLend                                                    |
| Native unstaking before reuse     | Instant exit usually available through DEX liquidity or the redemption buffer |

For illustration, a Platinum-sized 100,000-HYPE position at $67.78 and $500M of monthly taker flow through the Prime UI produces approximately:

* **$31.5k per month** of fee savings after the Prime UI fee, assuming a 3.0 bps base volume-tier rate and a 30% staking discount.
* **$13.6k per month** at a 2.4% stHYPE yield.
* Roughly **$540k per year** combined before borrow costs, hedging costs, slippage, or taxes.

Valantis collects no trading-volume fees on API or external-terminal trades; third-party builder-code fees may differ.

## When it fits

* The desk already warehouses HYPE and does not need the entire balance as intraday spot inventory.
* Taker flow is large enough for Gold or Platinum savings to matter.
* The desk wants a standby USDC line or a delta-neutral hedge without giving up the tier.

## Operating guidance

* Keep operational inventory separate from the strategic balance allocated to stHYPE.
* Maintain a buffer above the tier threshold if the position will move through lending or options venues.
* Use the [delta-neutral strategy](/prime/discounts/strategies/delta-neutral) if the desk does not want HYPE direction.
* Use the [USDC margin strategy](/prime/discounts/strategies/usdc-margin) for tactical liquidity instead of selling.

DEX liquidity and the redemption buffer usually provide an instant exit; users typically paid 1 bp and less than 3 bps over the trailing 90 days. The fallback unstaking path completes in under 7 days.


# Stay Delta-Neutral

Hold the stHYPE required for your tier and short HYPE perps against it.

This is designed for traders who value the fee discount but do not want a long HYPE position, or who already hedge a native staking position and want a more flexible spot leg.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-f774121e990a8a7a38b8f743105db4f9770e02d7%2Fimage%20(9).png?alt=media" alt=""><figcaption></figcaption></figure>

Any hedging instruments are welcome. wstHYPE gives more margin and options is crafting hedging strategies while keeping your staking discount.

## Mechanics

1. Hold tier-qualifying stHYPE or wstHYPE.
2. Short approximately 1 HYPE perp for each HYPE of net spot exposure.
3. Rebalance the short as staking yield, deposits, withdrawals, or strategy allocations change the exposure.
4. Keep sufficient USDC margin on the perp side.

The position keeps the Prime tier and stHYPE yield. The short receives funding when HYPE funding is positive and pays funding when it is negative.

At the July 15, 2026 snapshot, HYPE funding averaged **11.2% annualized over 30 days** and was positive during **91.6% of hours** in the trailing year. Those figures are historical, not a forecast.

## Why stHYPE helps

* You can run your hedge with margin borrowed against the staked inventory that gives your discount. Using [HyperEVM Margin](/prime/discounts/strategies/usdc-margin) or [stHYPE Portfolio Margin](/prime/discounts/strategies/portfolio-margin).
* The spot leg earns higher-than-native staking yield.
* The qualifying balance can remain in supported lending or options integrations.
* The Prime discount lowers the trading cost of hedge adjustments.
* DEX liquidity and the redemption buffer usually let you reduce the spot leg without waiting for native unstaking.

## When it fits

* You already hedge a staked HYPE position.
* Your HYPE sensitivity changes over time and you want to adjust the spot leg without a native unstaking queue.
* Your fee savings are large enough to justify perp margin and rebalancing.

## Risks

* Funding can compress or turn negative.
* A fast HYPE rally can pressure the short's USDC margin even while the spot leg gains.
* The hedge is approximate and must account for wstHYPE exchange-rate growth and any borrowed HYPE.
* Contract, exchange, and operational risks remain.

For a levered version that adds the staking spread, see the [Looped Basis Trade](/prime/discounts/strategies/looped-basis).


# Stack Yield with Covered Calls

Deposit wstHYPE into a supported Rysk covered-call market to combine:

* stHYPE staking yield.
* Option premium.
* The Prime staking tier on trading elsewhere.

wstHYPE held in Rysk counts toward Prime eligibility.

## What you are selling

A covered call pays premium in exchange for agreeing to sell the wstHYPE at the selected strike if the option expires in the money. The strategy earns more income when implied volatility and option premium are high, but it caps upside above the strike.

## The five-day tier risk

If a call finishes in the money, the wstHYPE can be sold at the strike. If that sale takes your eligible balance below the Prime tier requirement, the 5-day notice period begins.

Refill the holding requirement within those five days and the notice resets. If you do not refill it, you risk losing the discount and entering the Prime unstaking lifecycle.

## Safer sizing

* Write calls only on wstHYPE held above the tier threshold.
* Keep a tier buffer large enough for likely assignments, withdrawals, and balance changes.
* Treat the premium as compensation for capped upside, not as guaranteed APY.
* Choose strikes based on the price at which you are genuinely willing to sell.

## When it fits

* You are structurally long HYPE and willing to sell at a higher strike.
* You want additional income without giving up the tier before assignment.
* You can refill the requirement within five days if assignment reduces the eligible balance.

## Risks

* Upside is capped above the strike.
* Option premium varies by strike and expiry.
* Assignment can create a taxable sale and a Prime tier shortfall.
* Rysk, stHYPE, settlement, and smart-contract risks remain.

See [Rysk documentation](https://docs.rysk.finance/getting-started/protocol-and-product/how-to-use-rysk) for current market mechanics.


# Run the Looped Basis Trade

Combine a looped wstHYPE spot leg with a 1x HYPE perp short.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-13189dd435ab4481c942961b3b54fa403be16719%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>

The trade earns:

1. Levered stHYPE staking spread.
2. Funding paid to the HYPE perp short when funding is positive.
3. Lower rebalance fees from the Prime staking tier.

## Mechanics

1. Supply wstHYPE to HyperLend e-mode.
2. Borrow HYPE against it.
3. Restake the borrowed HYPE and repeat to the chosen loop multiple.
4. Short HYPE perps equal to the strategy's **net equity**, not gross loop exposure.

Borrowed HYPE offsets the added spot HYPE, so the loop's net HYPE delta stays approximately 1x equity regardless of the loop multiple.

## Illustrative carry

Inputs as of July 15, 2026: 2.4% normal stHYPE yield, 0.97% WHYPE borrow rate, and 11.23% trailing-30-day HYPE funding.

| Structure | Staking spread on loop equity | Funding on 1x hedge | Carry on loop equity | Approx. carry on total capital with 3x perp margin |
| --------- | ----------------------------: | ------------------: | -------------------: | -------------------------------------------------: |
| No loop   |                          2.4% |               11.2% |                13.6% |                                              10.2% |
| 2x loop   |                          3.8% |               11.2% |                15.1% |                                              11.3% |
| 4.5x loop |                          7.4% |               11.2% |                18.6% |                                              14.0% |

Historical funding and current borrow rates are not forecasts. HyperLend's one-click HyperLoop also charges a one-time 0.04% flashloan fee on the looped amount.

## When it fits

* You already run spot/perp basis and actively rebalance it.
* You want a yielding spot leg instead of idle spot HYPE.
* You can monitor HyperLend utilization, funding, and perp margin continuously.

## Risks

* **Borrow rates:** WHYPE rates rise sharply above the utilization kink and can erase the loop spread.
* **Funding:** the short pays funding when rates turn negative.
* **Perp margin:** a HYPE rally can pressure USDC margin even while the spot leg gains.
* **Slashing:** HyperLend's exchange-rate oracle prevents DEX market-depeg liquidations, but validator slashing can reduce wstHYPE collateral value. At maximum e-mode leverage, the slashing buffer is materially smaller.
* **Contract stack:** the strategy depends on stHYPE, HyperLend, WHYPE, HyperCore transfers, and Hyperliquid perps.

DEX liquidity and the stHYPE redemption buffer usually provide an instant exit; users typically paid 1 bp and less than 3 bps over the trailing 90 days. If the buffer is unavailable, fallback unstaking completes in under 7 days.


# Setting up a Prime Account

## Setting up a Prime Smart Account

During onboarding, claiming a Prime Account means signing an intent to receive ownership of the smart account to your EOA.

This account has already had stake supplied to it for the staking tier you have selected, and is ready to be traded with.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Ft3CeZmborw7YIJQihKdx%2F02_Settin%20Up%20A%20Prime%20Account_V2.png?alt=media&amp;token=199eb30a-88be-4147-8f96-38c2d6959dcf" alt=""><figcaption></figcaption></figure>

This does not submit a transaction on HyperEVM. It is signed data used by the setup contract to transfer ownership to your EOA.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2FlkyowBr0PojKJJxmKi0r%2F03_Settin%20Up%20A%20Prime%20Account%20_V1.png?alt=media&amp;token=3cba1fd1-b8ae-41f9-9753-d1e23c73918e" alt=""><figcaption></figcaption></figure>

stHYPE deploys and configures accounts in advance, then transfers ownership to users during onboarding.

* No waiting for Staking Discounts to activate
* No waiting for contract deployments to finalize

The setup contract ensures that staking-discount accounts open with secure default settings:

* Only CoreWriter calls enabled (No Prime Extensions)
* No approvals or interface to any EVM applications
* No API wallets listed
* No Session Keys listed

Only the owner EOA can sign any actions for the account, and the account can only interact with its HyperCore address.

The discount is active immediately after the account is claimed. ![](https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2FKrcuvzeVftrOSpwvz14n%2Fimage.png?alt=media\&token=34a4fbfb-a6ba-462e-bc87-c146de084541)

\*Discount may not be active immediately upon claiming if Pre-Staking occurred after 00:00 UTC from the current day. In this case, Staking Discount will become active after 00:00 UTC the following day. This is determined by the Hyperliquid Blockchain. Official information about Staking Discounts activation can be found in [Hyperliquid Fee Docs](https://hyperliquid.gitbook.io/hyperliquid-docs/trading/fees).


# Trading with a Prime Account

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2FdWFh3vTXbw4oIva5g2Vo%2F02_Fund%20Your%20Account.png?alt=media&amp;token=d8e1f5e0-f8de-4fce-848b-ba846715dc86" alt=""><figcaption></figcaption></figure>

The recommended funding path is to transfer HyperCore tokens directly from an external wallet to your Prime HyperCore address.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2FWwdjE2yJV3uVPkSK3XU8%2FTRANSFER_ON_HYPERCORE.png?alt=media&amp;token=ecdc2ce3-8d4b-4eaf-a2a0-d835c149a250" alt=""><figcaption></figcaption></figure>

Alternatively, assets on HyperEVM can be deposited to the Prime Account via CoreWriter transactions.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2FPRdnPWWhmRVlYlJlzsyC%2FDEPOSIT_FROM_EVM.png?alt=media&amp;token=c35db03a-ae21-4fe1-b4ff-af29856a5263" alt=""><figcaption></figcaption></figure>

## Trading With Prime Account

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2FFjOu9bGiaYdeZkf5nM6O%2F01_Enable%20Trading.png?alt=media&amp;token=01a5b1cf-19ce-4357-8cab-e42bf943c257" alt=""><figcaption></figcaption></figure>

List an API Wallet to begin trading directly on HyperCore

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2F6viTen0IfA2gKub5QxoJ%2F02_ADD_API_WALLET.png?alt=media&amp;token=80d1373e-2d19-4244-99b6-cc668f9c12d1" alt=""><figcaption></figcaption></figure>

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2FKHCsHgoOk4zk0TObjwDJ%2F03_Trading%20with%20Valantis%20Prime.png?alt=media&amp;token=77bc1562-ade9-4617-9256-a1d92858798e" alt=""><figcaption></figcaption></figure>

API wallets can sign orders for your Prime Account, allowing transactions to be submitted directly to HyperCore with no added latency.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2F6pvVWdJ2NhS6xP1qxRNk%2F04_Withdrawal.png?alt=media&amp;token=e23415f9-b878-4632-8988-61214cc95c45" alt=""><figcaption></figcaption></figure>

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2FLkecCht52zmaKXqOtYhI%2FWITHDRAW_VIA_COREWRITER.png?alt=media&amp;token=24149ec0-42bb-481b-a533-f8123c1bab9c" alt=""><figcaption></figcaption></figure>

Withdrawals from spot and perp balances can be initiated only by the trader EOA and can be received only by the trader EOA. For tighter security, withdrawals return to HyperEVM through the CoreWriter route:

* No external address is able to receive funds out of the Valantis Prime Account other than the Trader Wallet EOA.
* Only the trader EOA can trigger a withdrawal through the owner-level `ExecuteOwner()` action, which is distinct from the usual `execute()`.
* stHYPE cannot withdraw or transfer the trader's spot or perp balances.


# Ending Prime Discounts / Unstaking

## Unstaking

If the trader ends the Prime discount relationship, stHYPE follows a defined and delayed shutdown path to recover only the managed staking balance from the account.

Shutdown cannot occur without onchain warnings and timelocks - enforced by Smart Contracts.

During normal operation, stHYPE cannot transfer or withdraw the trader’s spot or perp balances. It retains the managed staking, builder-fee approval, and shutdown-notice controls listed in the [Staking Discounts Risk Matrix](/prime/developers/staking-discounts-risk-matrix).

When shutdown begins, the trader’s access to HyperCore functions is restricted while the managed staking balance is recovered. The notice period and guard delay precede this restriction. stHYPE’s recall is limited to the managed HYPE staking balance measured at the start of unwind; cleanup may close positions that put that balance at risk.

## LifeCycle at a Glance

During `ACTIVE`, the trader can use the trading, transfer, and withdrawal actions listed in the control matrix. stHYPE can manage stake delegation, approve builder-fee settings, and start a shutdown notice. Starting a notice does not immediately remove the trader’s live trading permissions.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2FaqJLwC5P2e7eRt0vYeKD%2Factive_01.png?alt=media&amp;token=69c42f72-8174-4b7c-9334-8ddc374b67d7" alt=""><figcaption></figcaption></figure>

If the trader falls below the required stHYPE holding, a five-day notice period begins. During `SHUTDOWN_NOTICE`, the trader keeps the same live trading permissions as in `ACTIVE`. Restoring the required holdings resets the notice period. Shutdown can begin once the notice maturity and guard delay are satisfied.

Users should close positions and cancel open orders during the notice period if they plan to enter unstaking. Those positions will not be accessible and may be liquidated or closed during the unstaking period. Withdraw trader-owned funds before unstaking begins to avoid temporary inaccessibility.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2FQVUDNT9ySTU5IyYhlx0y%2Fnotice_02.png?alt=media&amp;token=6e47be74-1922-4c79-b25e-f52acbf3e99d" alt=""><figcaption></figcaption></figure>

If the holding requirement remains unmet after the notice period and guard delay, stHYPE can begin shutdown. The trader then loses access to all HyperCore functions, while retaining access to EVM balances through the parent Prime Account. Shutdown takes at least seven days; seven to eight days is expected, but there is no guaranteed maximum duration.

stHYPE’s recall is limited to the managed HYPE staking balance measured at the start of shutdown. Remaining trader balances become accessible after shutdown completes. Open positions may be closed during cleanup if they put the recalled HYPE at risk, so traders should close positions, cancel orders, and withdraw trading balances during the notice period.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2FH8Ma4MCu7HBwtEK4OUp0%2Fshutdown_03.png?alt=media&amp;token=23ce9020-bdec-44ee-aef8-bea215f36205" alt=""><figcaption></figcaption></figure>

After the managed exit completes and `finalizeDetach` is called, the same HyperCore account returns to the trader’s control with the staking discount removed. The stHYPE management relationship ends, and its shutdown restrictions are removed.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2FofndURvC3WO55IqeU6Sn%2Freturn_04.png?alt=media&amp;token=15c6f5f1-d7b1-452a-8747-ca4af60162ec" alt=""><figcaption></figcaption></figure>

After final detachment, stHYPE no longer administers the account through the staking-discount relationship. The account’s admin functions return to the trader’s EOA, and the account contracts remain non-upgradable.


# Fees

## Calculation assumptions

The USDC margin illustrations assume a HYPE price of **$80** and a borrowing LTV of **59%**.

Your rolling 14-day weighted volume determines your starting Hyperliquid maker and taker rates. Your staking tier then reduces those rates.

The fee tables below show Hyperliquid rates with staking. Interface fees are disclosed separately.

<table><thead><tr><th width="112.80859375">Prime tier</th><th width="172.25390625" align="right">stHYPE requirement</th><th width="170.57421875" align="right">Hyperliquid staking discount</th><th align="right">Illustrative USDC margin</th></tr></thead><tbody><tr><td>Wood</td><td align="right">>10 stHYPE</td><td align="right">5%</td><td align="right">~$472</td></tr><tr><td>Bronze</td><td align="right">>100 stHYPE</td><td align="right">10%</td><td align="right">~$4,720</td></tr><tr><td>Silver</td><td align="right">>1,000 stHYPE</td><td align="right">15%</td><td align="right">~$47,200</td></tr><tr><td>Gold</td><td align="right">>10,000 stHYPE</td><td align="right">20%</td><td align="right">~$472,000</td></tr><tr><td>Platinum</td><td align="right">>100,000 stHYPE</td><td align="right">30%</td><td align="right">~$4,720,000</td></tr><tr><td>Diamond</td><td align="right">>500,000 stHYPE</td><td align="right">40%</td><td align="right">~$23,600,000</td></tr></tbody></table>

## Fees by trading interface

Trades through [prime.valantis.xyz](https://prime.valantis.xyz) incur a Valantis fee equal to **30% of the Hyperliquid trading-fee savings from staking**.

Valantis collects no trading-volume fees on trades placed through the API or external terminals. Third-party terminals may apply their own builder-code fees. Hyperliquid trading fees apply in all cases.

## Fee Tables

These tables calculate Hyperliquid trading fees from its published base volume-tier schedule and staking discounts, expressed in basis points (bps). Prime provides the same Hyperliquid fee rates as native HYPE staking at the corresponding volume and staking tiers.

Values retain three decimal places in bps, so they may show more precision than Hyperliquid’s rounded percentage tables. One basis point is 0.01%.

**Base** is the Hyperliquid fee before a staking discount. **With staking** is the fee after that discount.

The tables exclude Prime UI fees, third-party builder-code fees, and the other fee adjustments described below.

Hyperliquid uses one volume tier across perps and spot. Spot volume counts twice toward the rolling 14-day weighted volume, and the tier is assessed daily at 00:00 UTC.

| Volume tier | Rolling 14-day weighted volume |
| ----------: | -----------------------------: |
|           0 |                            $0+ |
|           1 |                           >$5M |
|           2 |                          >$25M |
|           3 |                         >$100M |
|           4 |                         >$500M |
|           5 |                           >$2B |
|           6 |                           >$7B |

## Wood — 10 stHYPE

Prime benefits:

* Access with only 5 HYPE deposited in the 2x Vault ($400 less capital for the Wood tier)
* Borrow up to $472 USDC

### Wood Perps Fees

| Volume tier | Base taker (bps) | Taker with staking (bps) | Base maker (bps) | Maker with staking (bps) |
| ----------: | ---------------: | -----------------------: | ---------------: | -----------------------: |
|           0 |            4.500 |                    4.275 |            1.500 |                    1.425 |
|           1 |            4.000 |                    3.800 |            1.200 |                    1.140 |
|           2 |            3.500 |                    3.325 |            0.800 |                    0.760 |
|           3 |            3.000 |                    2.850 |            0.400 |                    0.380 |
|           4 |            2.800 |                    2.660 |            0.000 |                    0.000 |
|           5 |            2.600 |                    2.470 |            0.000 |                    0.000 |
|           6 |            2.400 |                    2.280 |            0.000 |                    0.000 |

### Wood Spot Fees

| Volume tier | Base taker (bps) | Taker with staking (bps) | Base maker (bps) | Maker with staking (bps) |
| ----------: | ---------------: | -----------------------: | ---------------: | -----------------------: |
|           0 |            7.000 |                    6.650 |            4.000 |                    3.800 |
|           1 |            6.000 |                    5.700 |            3.000 |                    2.850 |
|           2 |            5.000 |                    4.750 |            2.000 |                    1.900 |
|           3 |            4.000 |                    3.800 |            1.000 |                    0.950 |
|           4 |            3.500 |                    3.325 |            0.000 |                    0.000 |
|           5 |            3.000 |                    2.850 |            0.000 |                    0.000 |
|           6 |            2.500 |                    2.375 |            0.000 |                    0.000 |

## Bronze — 100 stHYPE

Prime benefits:

* Access with only 50 HYPE deposited in the 2x Vault ($4,000 less capital for the Bronze tier)
* Borrow up to $4,720 USDC

### Bronze Perps Fees

| Volume tier | Base taker (bps) | Taker with staking (bps) | Base maker (bps) | Maker with staking (bps) |
| ----------: | ---------------: | -----------------------: | ---------------: | -----------------------: |
|           0 |            4.500 |                    4.050 |            1.500 |                    1.350 |
|           1 |            4.000 |                    3.600 |            1.200 |                    1.080 |
|           2 |            3.500 |                    3.150 |            0.800 |                    0.720 |
|           3 |            3.000 |                    2.700 |            0.400 |                    0.360 |
|           4 |            2.800 |                    2.520 |            0.000 |                    0.000 |
|           5 |            2.600 |                    2.340 |            0.000 |                    0.000 |
|           6 |            2.400 |                    2.160 |            0.000 |                    0.000 |

### Bronze Spot Fees

| Volume tier | Base taker (bps) | Taker with staking (bps) | Base maker (bps) | Maker with staking (bps) |
| ----------: | ---------------: | -----------------------: | ---------------: | -----------------------: |
|           0 |            7.000 |                    6.300 |            4.000 |                    3.600 |
|           1 |            6.000 |                    5.400 |            3.000 |                    2.700 |
|           2 |            5.000 |                    4.500 |            2.000 |                    1.800 |
|           3 |            4.000 |                    3.600 |            1.000 |                    0.900 |
|           4 |            3.500 |                    3.150 |            0.000 |                    0.000 |
|           5 |            3.000 |                    2.700 |            0.000 |                    0.000 |
|           6 |            2.500 |                    2.250 |            0.000 |                    0.000 |

## Silver — 1,000 stHYPE

Prime benefits:

* Access with only 500 HYPE deposited in the 2x Vault ($40,000 less capital for the Silver tier)
* Borrow up to $47,200 USDC

### Silver Perps Fees

| Volume tier | Base taker (bps) | Taker with staking (bps) | Base maker (bps) | Maker with staking (bps) |
| ----------: | ---------------: | -----------------------: | ---------------: | -----------------------: |
|           0 |            4.500 |                    3.825 |            1.500 |                    1.275 |
|           1 |            4.000 |                    3.400 |            1.200 |                    1.020 |
|           2 |            3.500 |                    2.975 |            0.800 |                    0.680 |
|           3 |            3.000 |                    2.550 |            0.400 |                    0.340 |
|           4 |            2.800 |                    2.380 |            0.000 |                    0.000 |
|           5 |            2.600 |                    2.210 |            0.000 |                    0.000 |
|           6 |            2.400 |                    2.040 |            0.000 |                    0.000 |

### Silver Spot Fees

| Volume tier | Base taker (bps) | Taker with staking (bps) | Base maker (bps) | Maker with staking (bps) |
| ----------: | ---------------: | -----------------------: | ---------------: | -----------------------: |
|           0 |            7.000 |                    5.950 |            4.000 |                    3.400 |
|           1 |            6.000 |                    5.100 |            3.000 |                    2.550 |
|           2 |            5.000 |                    4.250 |            2.000 |                    1.700 |
|           3 |            4.000 |                    3.400 |            1.000 |                    0.850 |
|           4 |            3.500 |                    2.975 |            0.000 |                    0.000 |
|           5 |            3.000 |                    2.550 |            0.000 |                    0.000 |
|           6 |            2.500 |                    2.125 |            0.000 |                    0.000 |

## Gold — 10,000 stHYPE

Prime benefits:

* Access with only 5,000 HYPE deposited in the 2x Vault ($400,000 less capital for the Gold tier)
* Borrow up to $472,000 USDC

### Gold Perps Fees

| Volume tier | Base taker (bps) | Taker with staking (bps) | Base maker (bps) | Maker with staking (bps) |
| ----------: | ---------------: | -----------------------: | ---------------: | -----------------------: |
|           0 |            4.500 |                    3.600 |            1.500 |                    1.200 |
|           1 |            4.000 |                    3.200 |            1.200 |                    0.960 |
|           2 |            3.500 |                    2.800 |            0.800 |                    0.640 |
|           3 |            3.000 |                    2.400 |            0.400 |                    0.320 |
|           4 |            2.800 |                    2.240 |            0.000 |                    0.000 |
|           5 |            2.600 |                    2.080 |            0.000 |                    0.000 |
|           6 |            2.400 |                    1.920 |            0.000 |                    0.000 |

### Gold Spot Fees

| Volume tier | Base taker (bps) | Taker with staking (bps) | Base maker (bps) | Maker with staking (bps) |
| ----------: | ---------------: | -----------------------: | ---------------: | -----------------------: |
|           0 |            7.000 |                    5.600 |            4.000 |                    3.200 |
|           1 |            6.000 |                    4.800 |            3.000 |                    2.400 |
|           2 |            5.000 |                    4.000 |            2.000 |                    1.600 |
|           3 |            4.000 |                    3.200 |            1.000 |                    0.800 |
|           4 |            3.500 |                    2.800 |            0.000 |                    0.000 |
|           5 |            3.000 |                    2.400 |            0.000 |                    0.000 |
|           6 |            2.500 |                    2.000 |            0.000 |                    0.000 |

## Platinum — 100,000 stHYPE

Prime benefits:

* Access with only 50,000 HYPE deposited in the 2x Vault ($4,000,000 less capital for the Platinum tier)
* Borrow up to $4,720,000 USDC

### Platinum Perps Fees

| Volume tier | Base taker (bps) | Taker with staking (bps) | Base maker (bps) | Maker with staking (bps) |
| ----------: | ---------------: | -----------------------: | ---------------: | -----------------------: |
|           0 |            4.500 |                    3.150 |            1.500 |                    1.050 |
|           1 |            4.000 |                    2.800 |            1.200 |                    0.840 |
|           2 |            3.500 |                    2.450 |            0.800 |                    0.560 |
|           3 |            3.000 |                    2.100 |            0.400 |                    0.280 |
|           4 |            2.800 |                    1.960 |            0.000 |                    0.000 |
|           5 |            2.600 |                    1.820 |            0.000 |                    0.000 |
|           6 |            2.400 |                    1.680 |            0.000 |                    0.000 |

### Platinum Spot Fees

| Volume tier | Base taker (bps) | Taker with staking (bps) | Base maker (bps) | Maker with staking (bps) |
| ----------: | ---------------: | -----------------------: | ---------------: | -----------------------: |
|           0 |            7.000 |                    4.900 |            4.000 |                    2.800 |
|           1 |            6.000 |                    4.200 |            3.000 |                    2.100 |
|           2 |            5.000 |                    3.500 |            2.000 |                    1.400 |
|           3 |            4.000 |                    2.800 |            1.000 |                    0.700 |
|           4 |            3.500 |                    2.450 |            0.000 |                    0.000 |
|           5 |            3.000 |                    2.100 |            0.000 |                    0.000 |
|           6 |            2.500 |                    1.750 |            0.000 |                    0.000 |

## Diamond — 500,000 stHYPE

Prime benefits:

* Access with only 250,000 HYPE deposited in the 2x Vault ($20,000,000 less capital for the Diamond tier)
* Borrow up to $23,600,000 USDC

### Diamond Perps Fees

| Volume tier | Base taker (bps) | Taker with staking (bps) | Base maker (bps) | Maker with staking (bps) |
| ----------: | ---------------: | -----------------------: | ---------------: | -----------------------: |
|           0 |            4.500 |                    2.700 |            1.500 |                    0.900 |
|           1 |            4.000 |                    2.400 |            1.200 |                    0.720 |
|           2 |            3.500 |                    2.100 |            0.800 |                    0.480 |
|           3 |            3.000 |                    1.800 |            0.400 |                    0.240 |
|           4 |            2.800 |                    1.680 |            0.000 |                    0.000 |
|           5 |            2.600 |                    1.560 |            0.000 |                    0.000 |
|           6 |            2.400 |                    1.440 |            0.000 |                    0.000 |

### Diamond Spot Fees

| Volume tier | Base taker (bps) | Taker with staking (bps) | Base maker (bps) | Maker with staking (bps) |
| ----------: | ---------------: | -----------------------: | ---------------: | -----------------------: |
|           0 |            7.000 |                    4.200 |            4.000 |                    2.400 |
|           1 |            6.000 |                    3.600 |            3.000 |                    1.800 |
|           2 |            5.000 |                    3.000 |            2.000 |                    1.200 |
|           3 |            4.000 |                    2.400 |            1.000 |                    0.600 |
|           4 |            3.500 |                    2.100 |            0.000 |                    0.000 |
|           5 |            3.000 |                    1.800 |            0.000 |                    0.000 |
|           6 |            2.500 |                    1.500 |            0.000 |                    0.000 |

## Other fee adjustments

The tables cover Hyperliquid's standard perps and spot schedules. HIP-3 growth mode, deployer fees, aligned quote assets, stable-pair reductions, referral discounts, and other order-specific adjustments can change the execution rate. See Hyperliquid's [fee documentation](https://hyperliquid.gitbook.io/hyperliquid-docs/trading/fees) for protocol details.


# Prime Terminal

To be written


# Prime Extensions (EVM x Core)

> Valantis Prime's extension to EVM DeFi experiences are optional add-ons. Prime Accounts are deny-by-default. Staking Discounts default settings only use EVM for direct interactions with CoreWriter functions.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2FEiatQ9xXZ4EsPuqCJyfC%2FScreenshot%202026-05-19%20at%2011.59.41%E2%80%AFAM.png?alt=media&amp;token=371a6beb-2292-446b-bcdf-f4dd15868d33" alt=""><figcaption></figcaption></figure>

Valantis Prime Extensions is an account system designed to make HyperEVM and HyperCore operate like one product.

## The Problem

Hyperliquid has two powerful environments:

* **HyperCore** for exchange-native execution.
* **HyperEVM** for programmable DeFi.

They are connected through precompiles/CoreWriter, but the bridge between them is constrained and non-atomic. In practice, this creates three problems:

1. **UX is fragmented**: users repeatedly sign, bridge, and rebalance between environments.
2. **HyperCore is Static**: HyperCore is not extensible on its own. Complex strategies and new order types can't be programmed on a per-user level.
3. **Permissions are broken**: Offering services to users on HyperCore requires custody or high levels of trust. HyperCore's account structure is not prepared for the world of Agent-run DeFi Automations.

## The Thesis

The user account is the only durable control surface shared across HyperCore and HyperEVM. Creating programmable experiences on HyperCore requires programmability at the account layer, and HyperEVM is the programmable layer.

For Hyperliquid to feel unified, automation must be embedded in the account itself.

Valantis Prime is that account layer: it lets users authorize specific automated behavior across both environments while preserving explicit ownership and bounded risk. It creates the basis for Agent-enabled automations across Hyperliquid's full stack.

## What This Unlocks

* **Yield-bearing order flow**: DCA/TWAP/limit orders can keep idle capital productive on HyperEVM and move to HyperCore when execution conditions are met.
* **Risk-managed automation**: agents can execute useful operations without inheriting full account authority.
* **custom HyperCore account policies**: Per-action thresholds for HyperCore Multisigs, API-wallets with whitelisted transfer capabilities.

## Why a New Account Standard

Valantis Prime is not based on existing smart account architectures like SAFE. It operates first as the connective tissue enabling constrained agent automations on Hyperliquid; and seconds as an arbitrary DeFi smart account. SAFE and other tooling can be plugged in to Valantis Prime using connectors, recovering familiar experiences.

Valantis Prime works by whitelisting actions into the wallet, reducing the attack surface significantly compared to traditional wallets. This works well because HyperCore has a constrained set of actions (all of which are supported via [HyperCore Connector](/prime/developers/hypercore-connector)). Overtime, critical HyperEVM integrations will continue to be added, currently [Prime DCA](/prime/dca) support HyperEVM Lending and STEX. This deny-by-default, Hyperliquid-first architecture allows us to recover Agent automations in a safe way on Hyperliquid.

Valantis Prime is distinct from HyperCore strategies accessed through pooled DeFi. As opposed to depositing into a strategy being run by external smart contracts, Valantis Prime user's enable agents to run customizable strategies directly from their account.

Next: read [Prime Architecture](/prime/developers/architecture) for role boundaries, permission flow, and trust assumptions.


# Trading with Valantis Prime

Import methods for trading with Valantis Prime accounts, critical for using stHYPE Staking-Tier Discounts with popular trading terminals

For Builder Code apps that support the [Valantis Prime Integration Spec](/prime/integration)

LST-enabled Discounted HyperCore Accounts can trade on these Trading Terminals. More coming soon.

## Insilico

Method: API Private Key Import

{% embed url="<https://insilicoterminal.com/#/trade>" %}

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2FilFyRX3ukSaORZgMMUWP%2FInsilico.png?alt=media&amp;token=5465c174-d0d7-4861-af49-b1071fdc0c39" alt=""><figcaption></figcaption></figure>

## BasedApp

Method: Mobile QR Code Scan

<https://based.one>

#### Mobile

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2FibMP4rQOEarAczj4Xd87%2FBasedApp.png?alt=media&amp;token=aa07166b-5aa7-41a6-87d2-e7777331568e" alt=""><figcaption></figcaption></figure>

## Dreamcash

Method: Mobile QR Code Scan

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2FlURsMCMVCYCqTN2NSO0t%2FDreamcash.png?alt=media&amp;token=1584ee4e-0884-4af2-a715-771fa0c25e2f" alt=""><figcaption></figcaption></figure>

## Dexari

Method: Mobile QR Code Scan

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2FChW0RNlea0t6QYDhSYfN%2FDEXARI-PRIME.png?alt=media&amp;token=2e977acb-2ea0-4a4d-8cab-85f14587fec9" alt=""><figcaption></figcaption></figure>


# Valantis Prime Developers


# Prime Architecture

Valantis Prime follows an *Owner -> Account -> Connector (protocol) -> Action (function) -> Agent/SessionKey/Guardian (access)* chain of command.

* The owner controls the Account, subject to Staking Discounts lifecycle restrictions if Prime Staking is enabled.
* The Account CONTROLS external access to funds by agents and integrated protocols.
* Connectors define WHAT external Actions can be done.
* Agents, Guardians, and Session Keys control HOW those Actions are executed.

### Architecture

```
                         ┌─────────┐
                         │  Owner  │
                         │  (You)  │
                         └────┬────┘
                              │
                    ┌─────────▼─────────┐
                    │      Account      │
                    │                   │
                    │  Agents, Sessions │
                    │  Allowances, etc. │
                    └──────────┬────────┘
                               │
         ┌─────────────────────┼─────────────────────┐
         ▼                     ▼                     ▼
   ┌───────────┐         ┌───────────┐         ┌───────────┐
   │ HyperCore │         │  Lending  │         │  Future   │
   │ Connector │         │ Connector │         │ Protocols │
   └───────────┘         └───────────┘         └───────────┘
```

This page is the technical model for Valantis Prime component boundaries, execution flow, and trust assumptions.

For product rationale and positioning, start with [Valantis Prime Thesis](/prime/thesis).

## Owner

You are the owner of your Account. As owner, you have:

* Control over Account features, subject to delegated action permissions
* Ability to add/remove agents and connectors (external access)
* Control over all allowances and guardians (restrictions)
* Power to start/end sessions (listed signing keys)
* Authority to withdraw accessible Account balances; integrated protocol balances may be subject to withdrawal or lifecycle restrictions
* Account recovery setup

## Account

Your Account lets you configure:

* **Who** can execute actions (Agents)
* **What** protocols they can use (Connectors)
* **How much** they can spend (Allowances)
* **What rules** they must follow (Guardians)
* **How long** access lasts (Sessions)

Delegating a HyperCore action-admin role limits the owner’s control over that action. The owner cannot forcibly reclaim that role; see [Admin Role Transfers](/prime/developers/hypercore-connector#admin-role-transfers-protocol-integrated-hypercore-accounts). Prime staking-discount accounts also restrict the trader’s HyperCore access during shutdown, while EVM balances in the parent Account remain accessible. See the [Staking Discounts Risk Matrix](/prime/developers/staking-discounts-risk-matrix).

## Key Features

#### **Protocol Integrations** (Connectors)

Valantis Prime does not support arbitrary transactions natively, every Protocol/Action is integrated into the system carefully through Connectors.

A Connector defines what actions can be called, and who can call them.

* Implements custom business logic for a specific protocol
* Restricts external calls to pre-approved contracts
* Has its own access control and action types

**Available Connectors:**

* **HyperCore** - Bridge, trade, stake, transfer, vault operations, BLP deposits, API-wallet management, and builder-fee operations on HyperCore precompiles. (All HyperCore precompiles on Mainnet as of March 2026).
* **STEX Lending** - Deposit/withdraw from STEX Multi Market Lending Optimizer integrated with AAVE and Morpho contracts (Felix, Hyperlend, HypurrFi, etc.).

Each action in a Connector has defined permission controls:

* What agents and session keys can call it
* What restrictions those external callers have (Guardians)
* Who can edit the permissions for an action (Admin/Owner)

Connectors add an additional layer of protection through allowances. Since protocols are integrated directly into a user's account, allowances enforce that added connectors have limit access to funds.

```
HyperCore Connector: 1,000 USDC allowance
STEX Lending: 500 HYPE allowance
```

Even if an agent or protocol is compromised, losses are limited to the allowance you've set.

#### **Agents**

Connectors define the actions, Agents automate them. Valantis Prime architecture is made to allow in-account Agent Automations without giving full control to external services.

For example:

* Allow a trading bot to place orders on HyperCore, but not withdraw funds
* Allow a liquidation protection bot to add collateral, but not borrow or withdraw

Each agent operates within strict boundaries you define, enforced by smart contract invariants.

Agent can be further restricted by **Guardians**. Introducing a programmable safety-net on giving agents access to in-account automations. Guardians are smart contract callbacks that revert Agent actions under certain conditions.

Each Connector can have one Guardian that implements:

* `beforeExecute()` - Validates conditions before action
* `afterExecute()` - Validates state after action

**Example Use Cases:**

1. **Price Limits**

   ```
   Guardian checks: Trade price must be within 2% of oracle
   If agent tries to trade at bad price → Guardian reverts
   ```
2. **Health Factor Protection**

   ```
   Guardian checks: Health factor must stay above 1.4
   If action would drop health factor → Guardian reverts
   ```
3. **Position Size Limits**

   ```
   Guardian checks: Total position size < $10,000
   If action exceeds limit → Guardian reverts
   ```

**Agents** have whitelisted actions, but **Guardians** apply criteria/restrictions to how/when Agents can call those actions. They are pre/post state checks that can limit an Agent's freedom over your funds.

#### **Session Keys and Signing**

Every non-critical action allows an owner to register a Session Key with a custom expiry. Session keys are whitelisted across the entire account + connectors, but each action can define how long that session key is valid for (can be set to 0 for no-session key allowed actions).

This enables HyperCore actions that typically require a user signature to use session keys, overcoming the pre-defined nature of API wallets.

This enables fine-tuned control of critical and non-critical operations across the account and it's integrations.

For example, in yield-bearing DCA:

* HyperEVM Lending + HyperCore whitelisting/allowances are set via owner signature
* Order creation is done via a medium-expiry session key
* Order cancellation is done via a long-expiry session key

This enables smoother interactions without constant wallet pop-ups, and fine-tuned control by the owner to define their security comfort across all of Hyperliquid. Session keys can be revoked at any time by the owner.

#### **Account Recovery**

Valantis Prime allows the owner to set up state-of-the-art account recovery services natively in the account.

Protect against lost private keys:

* Pre-approve recovery wallet addresses
* Set a recovery manager (trusted party or service)
* If you lose access, recovery can transfer ownership after a time delay
* You maintain control and can cancel at any time

### Security Model

Valantis Prime account security is based on:

1. **Trusted Integrations** - Only call pre-approved external contracts and functions can be called
2. **Integration Allowances** - Token transfers to Integrated Protocols (Connectors) cannot exceed allowances.
3. **Session Time Limits** - Session keys expire (max 60 days) and can be revoked by owner at any time.
4. **Recovery Delays** - Ownership changes require multi-day time locks
5. **Guardian Validation** - Optional pre/post execution checks on agent actions

#### What You Need to Trust

* **Connector code** - Each Connector's logic (you should verify it's immutable and secure)
* **Agents you authorize** - They operate within allowances but are trusted to act correctly
* **Guardians you add** - They can block actions by agents, so must be correct implementations
* **Recovery manager** - Can initiate recovery (but only to wallets you pre-approved)

### Next Steps

* [Account Features](/prime/developers/account) - Learn about agents, sessions, allowances, and guardians
* [HyperCore Connector](/prime/developers/hypercore-connector) - HyperCore-specific features


# Prime Account Features

The Account.sol contract is the central hub of Valantis Prime. It manages permissions, allowances, and coordinates all interactions with Connectors.

This page reviews the use, set up, and configuration of Valantis Account contract in the Valantis Prime Account Architecture.

### Agents & Connector Relationship

Agents are addresses you authorize to execute actions on Connectors. They're perfect for:

* Trading bots
* Automated strategies
* Liquidation protection services
* Yield optimizers

**Key Features:** Up to 20 agents per Account. By default, each agent can call `Account.execute()` for any **whitelisted** Connector. But, Connectors can place action-level restrictions:

For example:

* HyperCore blocks agents & session keys by default: using `authorizedSender`, session-signature requirement, and action-specific session expiry.
* STEX Lending Connector allows all agents and session keys to interact by default.

It is up to connectors to implement agent-by-agent rules, if they are necessary.

**Example Use Case (HyperCore):**

1. Add your bot as an agent.
2. Whitelist your HyperCore Connector and set a 1,000 USDC allowance.
3. Configure HyperCore action-level controls so only that bot is `authorizedSender` for the action types you want it to run. (i.e. longing HYPE <5x under $25)
4. Bot actions are still bounded by allowance and Guardian checks (if configured). (bot cannot access >$1000, bot cannot open HYPE trades >5x, bot cannot buy HYPE above $25; all enforced by smart contracts)

**Important Guardians Note:** *HyperCore API wallet activity is outside Guardian enforcement*

There are two common set-ups for Agent-automated HyperCore Trading:

1. Avoid API wallets for critical strategies and enforce rules through Guardian-gated HyperCore actions on EVM. If plausible and protections are required, use CoreWriter precompiles + Guardian restrictions to place low-frequency, but controlled trades. Guardians only can revert actions that originate on EVM.
2. Use API wallets for low-latency execution, but guard the bridge flow so only bounded capital is moved from EVM to HyperCore under predefined conditions (for example, yield-bearing DCA controls HyperCore max balance and time-based bridging restrictions). This avoids exposing too much risk to an unconstrained HyperCore API Wallet, but still gives high-frequency execution abilities to an agent.

### Common Operations

#### Adding an Agent

To restrict what an agent can call, combine:

1. Connector whitelist scope (only add needed Connectors),
2. HyperCore action-level `authorizedSender` configuration, and
3. Tight per-token allowances (optionally with Guardians).

**Direct Call (from your wallet):**

```solidity
account.addAgent(agentAddress);
```

**Via Signature (meta-transaction):**

```solidity
// Off-chain: Sign typed data
signature = signTypedData(AddAgent{
    agent: agentAddress,
    authorizedSender: relayerAddress,
    maxFee: 0.01 ether,
    feeToken: USDC,
    nonce: currentNonce,
    deadline: timestamp
});

// On-chain: Relayer submits
account.addAgent(agentAddress, signature, ...);
```

#### Setting Up a Connector

```solidity
// 1. Whitelist the Connector
account.addConnector(hyperCoreConnectorAddress);

// 2. Set token allowances
account.setAllowance(
    hyperCoreConnectorAddress,
    USDCAddress,
    1000 * 1e6  // 1,000 USDC
);

// 3. (Optional) Add Guardian
account.setGuardian(
    hyperCoreConnectorAddress,
    guardianAddress
);

// 4. Now agents can execute actions
account.execute(
    hyperCoreConnectorAddress,
    actionData
);
```

#### Starting a Session

```solidity
// Start session with temporary key
account.startSession(sessionKeyAddress);

// Session key can now sign for:
// - sendFromOwner()
// - setAllowance()

// Later: End the session
account.endSession();
```

#### Sending Tokens

**Send tokens from Account to your wallet:**

```solidity
account.sendToOwner(tokenAddress, amount);
```

**Pull tokens from your wallet into Account:**

```solidity
// Requires either:
// 1. Pre-approved token allowance on token contract, OR
// 2. ERC-2612 permit signature

account.sendFromOwner(tokenAddress, amount, permitData);
```

### Function Reference

#### Agent Management

| Function               | Who Can Call       | Description                |
| ---------------------- | ------------------ | -------------------------- |
| `addAgent(address)`    | Owner / Authorized | Add new agent (max 20)     |
| `removeAgent(address)` | Owner / Authorized | Remove existing agent      |
| `getAgents()`          | Anyone             | View all registered agents |

#### Connector Management

| Function                   | Who Can Call       | Description                                          |
| -------------------------- | ------------------ | ---------------------------------------------------- |
| `addConnector(address)`    | Owner / Authorized | Whitelist Connector (must be linked to this Account) |
| `removeConnector(address)` | Owner / Authorized | Unregister Connector                                 |
| `getConnectors()`          | Anyone             | View all registered Connectors                       |

#### Session Management

| Function                   | Who Can Call       | Description                                                    |
| -------------------------- | ------------------ | -------------------------------------------------------------- |
| `startSession(address)`    | Owner / Authorized | Set session signer (max 60 days)                               |
| `endSession()`             | Owner / Authorized | Terminate active session                                       |
| `invalidateSessionNonce()` | Owner only         | Increment sessionNonce to revoke pre-signed session signatures |

#### Allowance Management

| Function                                 | Who Can Call       | Signature Type | Description                               |
| ---------------------------------------- | ------------------ | -------------- | ----------------------------------------- |
| `setAllowance(connector, token, amount)` | Owner / Authorized | Session        | Set allowance for registered Connector    |
| `revokeAllowance(connector, token)`      | Owner / Authorized | Owner          | Clear allowance (works for any Connector) |

#### Guardian Management

| Function                           | Who Can Call       | Description                                       |
| ---------------------------------- | ------------------ | ------------------------------------------------- |
| `setGuardian(connector, guardian)` | Owner / Authorized | Set Guardian for Connector (address(0) to remove) |

#### Token Operations

| Function                                   | Who Can Call       | Signature Type | Description                                              |
| ------------------------------------------ | ------------------ | -------------- | -------------------------------------------------------- |
| `sendToOwner(token, amount)`               | Owner / Authorized | Owner          | Transfer tokens to owner wallet                          |
| `sendFromOwner(token, amount, permitData)` | Owner / Authorized | Session        | Pull tokens from owner wallet (requires approval/permit) |

#### Execution

| Function                        | Who Can Call   | Description                                                 |
| ------------------------------- | -------------- | ----------------------------------------------------------- |
| `execute(connector, data)`      | Owner / Agents | Call Connector's execute function                           |
| `executeOwner(connector, data)` | Owner only     | Call Connector with owner flag (bypasses some restrictions) |

### State Variables

| Variable          | Type    | Description                                                |
| ----------------- | ------- | ---------------------------------------------------------- |
| `owner`           | address | Current owner of the Account                               |
| `pendingOwner`    | address | Pending owner (2-step transfer)                            |
| `sessionAccount`  | address | Current session signer (address(0) if none)                |
| `sessionStartAt`  | uint256 | Timestamp when session started                             |
| `sessionEpochId`  | uint256 | Increments on startSession (prevents cross-session replay) |
| `nonce`           | uint256 | Nonce for owner-signed operations                          |
| `sessionNonce`    | uint256 | Nonce for session-signed operations                        |
| `recoveryManager` | address | Address authorized to initiate recovery                    |

### Constants

| Constant               | Value   | Description                         |
| ---------------------- | ------- | ----------------------------------- |
| `MAX_SESSION_DURATION` | 60 days | Maximum session validity period     |
| `MAX_AGENTS`           | 20      | Maximum number of concurrent agents |

### Events

All Account operations emit events for off-chain tracking:

| Event                                                            | Emitted When               |
| ---------------------------------------------------------------- | -------------------------- |
| `AgentAdded(address agent)`                                      | Agent is added             |
| `AgentRemoved(address agent)`                                    | Agent is removed           |
| `ConnectorAdded(address connector)`                              | Connector is whitelisted   |
| `ConnectorRemoved(address connector)`                            | Connector is unregistered  |
| `SessionStarted(address sessionAccount, uint256 timestamp)`      | Session is started         |
| `SessionEnded(address sessionAccount, uint256 timestamp)`        | Session is ended           |
| `GuardianSet(address connector, address guardian)`               | Guardian is set or updated |
| `AllowanceSet(address connector, address token, uint256 amount)` | Allowance is set           |
| `SentToOwner(address token, uint256 amount)`                     | Tokens sent to owner       |
| `SentFromOwner(address token, uint256 amount)`                   | Tokens pulled from owner   |
| `SessionNonceIncremented(uint256 newSessionNonce)`               | Session nonce invalidated  |

### Security Considerations

#### Trust Assumptions

When using Account, you are trusting:

1. **Connectors you whitelist** - They control which external contracts are called
2. **Agents you authorize** - They can execute actions within allowances
3. **Guardians you set** - They can block actions, so must be correct
4. **Session keys** - They can adjust allowances for registered Connectors

#### Best Practices

1. **Start with small allowances** - Test agents with limited funds first
2. **Use Guardians for automated actions** - Add extra safety checks
3. **Monitor events** - Watch for unexpected operations
4. **Set up recovery** - Protect against lost keys
5. **Review Connector code** - Verify it's immutable and secure before whitelisting (official Connectors here are deployed as immutable contracts, not proxies)
6. **Limit session duration** - Use shorter sessions when possible
7. **Keep agent count low** - Easier to audit and manage

### Common Patterns

#### Setup Pattern for New Protocol

```
1. Deploy or get Connector address
2. Link Connector to your Account (setAccount)
3. Add Connector to whitelist
4. Set token allowances
5. (Optional) Configure Guardian
6. (Optional) Add agents for specific actions
7. Execute actions via Account.execute()
```

#### Temporary Agent Access

```
1. Add agent
2. Set allowance
3. Agent performs task
4. Remove agent
5. Optionally reduce allowance
```

#### Session-Based UX Flow

```
1. User starts session with temporary key
2. Dapp can now call setAllowance without wallet pop-ups
3. Agent executes actions via Connector
4. User ends session when done
```

### Next Steps

* [HyperCore Connector](/prime/developers/hypercore-connector) - HyperCore-specific features


# HyperCore Connector

## Overview

The HyperCore Connector is Valantis Prime's programmable access layer for HyperCore.

All CoreWriter operations are defined as Valantis Prime Connector Actions (15 total), allowing custom controls and automations to be defined.

In practice, what new controls are created for HyperCore Accounts through Valantis Prime:

* who can execute each HyperCore Action, with what parameters, and under what conditions.
* Session key logic for all HyperCore actions: what actions can session keys be used for, how long are keys valid.

## Why This Exists

HyperCore native permissions are powerful but coarse. This Connector adds account-level policy controls around those capabilities.

| Current HyperCore Permissions | Limitations                                                                           |
| ----------------------------- | ------------------------------------------------------------------------------------- |
| **Standard Account**          | Single Signer with access to all actions                                              |
| **API Wallet**                | Can trade but cannot transfer, bridge, or stake. No restrictions on trading activity. |
| **Stake Linking**             | Staking account has full control over owner account                                   |
| **Multisigs**                 | All signers have equal access to all actions                                          |

Valantis Prime creates a baseline for safer automation design: action-level access, optional owner consent, and explicit recovery paths.

## What Becomes Possible

* Transfer-enabled trading agents (without granting full staking/control rights)
* Action-specific multisig and governance delegation
* Yield routing across HyperEVM and HyperCore
* Spot/perps/staking segmentation by agent
* Guarded automation (price checks, size limits, health constraints)
* BLP supply/withdraw automation with separate permissions from trading/staking

## Architecture

```
┌───────────────────────────────────────────────────────────────┐
│                    HyperCore Connector                        │
│                                                               │
│  Per-Action Configuration:                                    │
│  ├─ Admin (who can change action permissions)                 │
│  ├─ Authorized Sender (who can execute the action)            │
│  ├─ Skip Session Signature (are session keys allowed yes/no)  │
│  └─ Session Expiry Duration                                   │
│                                                               │
│  Execution Paths:                                             │
│  ├─ Via Agent → Guardian + Allowance restrictions             │
│  ├─ Via Owner → Owner bypass restrictions                     │
└──────────────┬──────────────────────────────┬─────────────────┘
               │                              │
               ▼                              ▼
       ┌────────────────┐              ┌────────────────┐
       │  CoreWriter    │              │  CoreWriter    │
       │  Action #1     │   ........   │  Action #16    │
       └────────────────┘              └────────────────┘
               │                              │
               ▼                              ▼
       ┌────────────────┐              ┌────────────────┐
       │   HyperCore    │              │   HyperCore    │
       │  L1 Action #1  │              │ L1 Action # 16 │
       └────────────────┘              └────────────────┘
```

## Permission Decision Path

```
HyperCore Connector Action
     │
     ▼
Is the Signer an Agent?
          │
          ├─ Yes -> Verify Restrictions ────────────────────────────────────────┐  
          └─ No  -> continue                              (agent path)          │
               (higher trust in caller/admin setup)                             │
               │                                                                │
               ▼                                                                │
Is caller authorized for this Action type?                                      │
     │                                                                          │
     ├─ No  -> revert                                                           │
     └─ Yes                                                                     │
          │                                                                     │
          ▼                                                                     │
Are session keys allowed to sign this action?                                   │
          │                                                                     │
          ├─ Yes -> verify EIP-712 signature, nonce, expiry ───────────────┐    │
          └─ No  -> continue                          (session path)       │    │
               (higher trust in caller)                                    │    │
                    └────────────────────────────────────────────────┐     │    │
                                        (owner path)                 ▼     ▼    ▼           
          
                                                             Execute CoreWriter Action
                                                                           │
                                                                           ▼
                                                       HyperCore Account Execution (1 per block guard)
```

## Permission Model

### Per-Action Controls

Every HyperCore action (15 total) has independent configuration:

| Control                    | Description                                                  | Default                                                 |
| -------------------------- | ------------------------------------------------------------ | ------------------------------------------------------- |
| **Admin**                  | Who can configure this action type                           | `address(0)` (owner via executeOwner)                   |
| **Authorized Sender**      | Who can execute this action type                             | `address(0)` (any agent whitelisted in Account & Owner) |
| **Skip Session Signature** | Whether agents can act on their own, or need owner signature | `false` (signature required)                            |
| **Session Expiry**         | How long session signatures last                             | 1 hour (or custom)                                      |
| Guardian                   | What conditions can this action be called under              | none                                                    |

### Admin Role Transfers (Protocol-integrated HyperCore Accounts)

Admin Delegation is a rare case when the Owner is willing to outsource configuration ownership of certain Actions to external smart contracts. Admin rights are delegated per-Action, so it does not mean account ownership transfer.

This enables protocols to interact/trust user's HyperCore account directly by restraining certain CoreWriter calls from the owner. This creates a new class of usecases on HyperCore

Admin ownership transfers is intended for Protocol-Level integrations into HyperCore Accounts

* It is a neccessity to unlock LST-enabled Staking Discounts.
* It paves the way for DAO governed HyperCore Accounts.

Solo user's should typically not use Admin Transfer functions. The owner cannot forcibly reclaim admin control once it is tranferred, only the new admin can self-revoke. This is intentionally a semi-permanent action. In most cases, these contracts should implement an permissionless recovery process for action-admin-privileges by the owner.

## Available Actions

The contract supports all 15 CoreWriter Actions in `HyperCoreConnector.sol`.

High-value execution rules:

* All CoreWriter-backed actions are subject to the one-action-per-block guard in `_beforeCoreWriter()`.
* `SEND_TO_ACCOUNT` is a local escape-hatch transfer to parent `Account` (not a CoreWriter call).

| ExecuteActionType                 | CoreWriter / HyperCore Path                          | Primary Use                                    | Key Fields                                                             | High-Value Constraints                                                                         |
| --------------------------------- | ---------------------------------------------------- | ---------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| `ADD_API_WALLET`                  | `addApiWallet`                                       | Add/remove API wallet authorization            | `apiWallet`, `name`                                                    | `apiWallet` must be `address(0)` (remove) or a fresh core user with no state                   |
| `APPROVE_BUILDER_FEE`             | `approveBuilderFee`                                  | Set builder fee settings                       | `maxFeeRate`, `builder`                                                | `maxFeeRate > 0`, `builder != address(0)`                                                      |
| `BRIDGE_TO_CORE`                  | HyperEVM -> HyperCore transfer path (`bridgeToCore`) | Move EVM assets into HyperCore spot balance    | `token`, `evmAmount`                                                   | If called via `Account.execute`, `_token/_amount` must exactly match encoded action data       |
| `BRIDGE_TO_EVM`                   | HyperCore -> HyperEVM transfer path (`bridgeToEvm`)  | Exit HyperCore spot back to HyperEVM           | `token`, `amountWei`                                                   | Amount must round-trip convert cleanly between EVM and core units                              |
| `BRIDGE_PERPS_SPOT`               | `transferUsdClass` (L1 `usdClassTransfer`)           | Move USDC notionals between perps and spot     | `ntl`, `toPerp`                                                        | `ntl > 0`                                                                                      |
| `CANCEL_ORDER_BY_CLOID`           | `cancelOrderByCloid` (L1 `cancelByCloid`)            | Cancel by client order id                      | `asset`, `cloid`                                                       | `cloid > 0`                                                                                    |
| `CANCEL_ORDER_BY_OID`             | `cancelOrderByOrderId` (L1 `cancel`)                 | Cancel by exchange order id                    | `asset`, `orderId`                                                     | Uses onchain order id path; ensure app tracks order ids correctly                              |
| `PLACE_LIMIT_ORDER`               | `placeLimitOrder` (L1 `limit`)                       | Submit GTC/IOC/ALO limit orders                | `asset`, `isBuy`, `limitPx`, `sz`, `reduceOnly`, `encodedTif`, `cloid` | `limitPx > 0`, `sz > 0`, `cloid > 0`, `encodedTif` must be ALO/GTC/IOC                         |
| `SEND_ASSET`                      | `sendAsset` (L1 `sendAsset`)                         | Move balances across HIP-3/perps/spot buckets  | `sourceDex`, `destinationDex`, `token`, `amountWei`                    | `sourceDex != destinationDex`, non-zero token/address                                          |
| `SEND_HYPE_TO_EXTERNAL_RECIPIENT` | `spotSend` (L1 `spotSend`)                           | Send spot HYPE to immutable external recipient | `amountWei`                                                            | Recipient is immutable deployment config (`externalSpotHypeRecipient`)                         |
| `SEND_TO_ACCOUNT`                 | Local token/native transfer to parent `Account`      | Escape hatch / fund return                     | `token`, `amount`                                                      | Always available via owner path (`executeOwner`) even after restrictive admin config           |
| `STAKING_DELEGATE`                | `delegateToken` (L1 `tokenDelegate`)                 | Delegate or undelegate to validator            | `validator`, `amountWei`, `undelegate`                                 | Non-zero validator and amount required                                                         |
| `STAKING_DEPOSIT`                 | `depositStake` (L1 `cDeposit`)                       | Move HYPE spot -> staking balance              | `amountWei`                                                            | Non-zero amount required                                                                       |
| `STAKING_WITHDRAW`                | `withdrawStake` (L1 `cWithdraw`)                     | Move HYPE staking -> spot balance              | `amountWei`                                                            | HyperCore staking withdrawal lockup still applies                                              |
| `VAULT_TRANSFER`                  | `vaultTransfer` (L1 `vaultTransfer`)                 | Deposit/withdraw to perps vaults (e.g. HLP)    | `vault`, `isDeposit`, `usdAmount`                                      | Non-zero vault and amount required                                                             |
| `BORROW_LEND`                     | `borrowLend` (L1 `borrowLend`)                       | **BLP supply/withdraw** (new in this doc)      | `operation`, `token`, `amountWei`                                      | `operation` must be `SUPPLY` or `WITHDRAW`; `amountWei=0` is allowed for full-balance behavior |

### CoreWriter and HyperCore References

* CoreWriter action list and L1 action naming: [Hyperliquid Docs - Interacting with HyperCore](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/hyperevm/interacting-with-hypercore)
* HyperCore <-> HyperEVM transfer behavior and caveats: [Hyperliquid Docs - HyperCore <> HyperEVM transfers](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/hyperevm/hypercore-hyperevm-transfers)

## CoreWriter Rate Limit

**Important:** This Connector enforces 1 CoreWriter interaction per block.

This is a security restriction placed on CoreWriter.

**Mitigation:**

* Users can operate Multiple HyperCore Connectors under the same Valantis Prime Account. This means Valantis Prime is the owner of multiple HyperCore addresses, each having its own 1 action-per-block restriction. UX of multiple HyperCore accounts can be abstracted away- user only interacts through parent account execute() function.
* Use API Wallets.

### API Wallet Trust

API wallets have pre-defined HyperCore permissions, and are not bottlenecked by CoreWriter 1-block rate limit:

* Place orders
* Cancel orders

API wallets can place trading actions directly on HyperCore at HyperCore level latency. Although, they they avoid the extensive permission checks possible on EVM.

One-way to mitigate API wallet controls/exposure in Valantis Prime is to use Guardian/EVM-permissions to control bridging/flow of funds to API-wallet accessible balances. This way, we can use API-wallets while limiting WHEN it has access to funds.

For example, PrimeDCA only allows a certain amount of HyperCore balance at a time, limits bridging to follow the order timeline and limit price. This makes it difficult (but not impossible) for API-wallets to violate the DCA-order preferences of the user.

If tuned permissions are needed, API wallets whitelisting can be blocked, and all relevant trading functions can be exposed through EVM CoreWriter calls with traditional guardian checks.


# Staking Discounts Risk Matrix

## Operating States Control Matrix

`SHUTDOWN_NOTICE` keeps the same live trading permissions as `ACTIVE`, so the matrix below focuses on the steady-state `ACTIVE` split and the combined rights of the stHYPE protocol during the `SHUTDOWN` cycle.

#### `ACTIVE` Trading Phase

**Trader Controls** via CoreWriter.

| Action                  | What the Trader controls                                  |
| ----------------------- | --------------------------------------------------------- |
| `ADD_API_WALLET`        | Add or replace trading API wallets                        |
| `BRIDGE_TO_CORE`        | Move assets from HyperEVM into HyperCore                  |
| `BRIDGE_TO_EVM`         | Move assets from HyperCore back to HyperEVM               |
| `BRIDGE_PERPS_SPOT`     | Move balances between perps and spot                      |
| `CANCEL_ORDER_BY_CLOID` | Cancel orders by client order id                          |
| `CANCEL_ORDER_BY_OID`   | Cancel orders by exchange order id                        |
| `PLACE_LIMIT_ORDER`     | Submit limit orders                                       |
| `SEND_ASSET`            | Move assets across supported HyperCore balance buckets    |
| `VAULT_TRANSFER`        | Deposit to or withdraw from supported vaults              |
| `BORROW_LEND`           | Run supported borrow/lend supply or withdraw actions      |
| `SEND_TO_ACCOUNT`       | Withdraw assets back to the parent Valantis Prime Account |

Deposit/Withdraw from core workflows can either be managed through the [Valantis Prime Account](/prime/developers/account) or through Transfers to/from an external HyperCore funding address.

**stHYPE controls**

| Action                  | What stHYPE controls                                  |
| ----------------------- | ----------------------------------------------------- |
| `updateStakeDelegation` | Delegate or undelegate the managed staking balance    |
| `approveBuilderFee`     | Approve builder-code fee settings for the sub-account |
| `startShutdownNotice`   | Start the timed shutdown path if commercial terms end |

During `SHUTDOWN_NOTICE`, the Trader keeps the same onchain action set as `ACTIVE`. stHYPE additionally gains `cancelShutdownNotice` and `beginShutdownUnwind` once the notice maturity and guard delay are satisfied.

#### `SHUTDOWN`: stHYPE controls

Controls are only changed after time lock passes, and stHYPE calls `beginShutdownUnwind`. Here, the Trader loses access to all HyperCore functions- only retaining access to EVM balances accessible through their Valantis Prime Account.

These are the controls that stHYPE has over the HyperCore account after shutdown has begun.

| Action                    | What stHYPE controls                                                                                                                                                                                                               |
| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `updateStakeDelegation`   | Undelegate from validators only                                                                                                                                                                                                    |
| `delistApiWallet`         | Remove previously listed external API wallets                                                                                                                                                                                      |
| `attestApiWalletsCleared` | Attest that external API wallets have been cleared                                                                                                                                                                                 |
| `installTrustedApiWallet` | Install a trusted cleanup wallet for controlled closeout. Primarily to remove DEX Abstraction.                                                                                                                                     |
| `removeTrustedApiWallet`  | Remove the trusted cleanup wallet                                                                                                                                                                                                  |
| `withdrawStake`           | Withdraw matured stake back into spot HYPE                                                                                                                                                                                         |
| `recallHype`              | Recall LST-managed HYPE from the Trader's account. Only the HYPE staking balance at the start of unwind can be withdrawn by the LST. This ensures potentially left-over balances are returned to the trader after `finalizeDetach` |
| `finalizeDetach`          | Detach management and return the account to normal ownership                                                                                                                                                                       |

## Main Risks and Trust Assumptions

#### Wind down is a real control right for the LST

Under a closure of the relationship, stHYPE can start the managed exit path after the configured time locks.

A trader integrating this model should explicitly underwrite the risk that access can be removed during wind down.

The trader should understand when stHYPE will issue a wind down notice, how to measure/verify if and when an account will enter unstaking, and how to operationally clean up an account during notice period to prevent losing temporary access to funds.

#### Shutdown takes at least seven days

Wind down is not immediate.

Undelegation timing, staking withdrawals, API-wallet cleanup, and HyperCore mechanics all affect how long it takes to fully recover the managed HYPE and detach the manager.

Shutdown takes at least seven days. It is expected to complete within seven to eight days, but there is no guaranteed maximum duration.

Close positions, cancel open orders, and withdraw trading balances during the notice period to avoid leaving them inaccessible during shutdown.

After wind-down completes, the same HyperCore address returns to the trader’s control and the restrictions imposed by the stHYPE management relationship are removed. The trader retains ownership throughout the lifecycle.

#### During Shutdown stHYPE cannot Withdraw Trader's Balances

It is advised that Traders do not leave balances or positions open once shut down is initiated. They will become inaccessible for a minimum of 7-days during the shutdown lifecycle.

Although, `recall` by stHYPE only pulls HYPE at the measured staking balance at the start of shutdown. This protects against over-reaching into balances that should not be treated as managed staking capital. These balances left by the trader will be returned to the trader after the shutdown is complete.

Open positions MAY be closed if they put the recalled staked HYPE at risk of cross-margin liquidation as it transits through the spot balance temporarily. stHYPE cleanup process prioritizes isolating the risk of the spot balance being subject to liquidation risk during the unstaking process.

In the future, stHYPE operators may expose an API which can process withdrawals/trades on behalf of the user during the shutdown process, but currently the expectation is the account is inaccessible.

## What to Monitor

Monitoring should be run on the trader's side to ensure they cannot lose access to account functions unexpectedly. The system is designed to be transparent and measurable on-chain without trust in LST off-chain infrastructure as a counter party.

#### Read functions to monitor shutdown risk

**How healthy is the active account (has shutdown`Notice` been issued)**

* `getManagedAccountInfo(...)`: current lifecycle state, notice timing, managed principal, and recall target
* `canBeginShutdownUnwind(...)`: If this returns `true`, the notice period and guard delay have elapsed and shutdown can begin. The trader loses HyperCore access when `beginShutdownUnwind` is called; no additional notice period is required.

**How Soon will the Account be returned (`Shutdown` status checks)**

* `getShutdownUnwindStatus(...)`: How close is the account to being returned during shutdown. Whether API-wallet cleanup is attested, whether a trusted shutdown wallet is active, and whether flatness is attested.
* `canEnterShutdownExecution(...)`: whether execution entry conditions tracked on-chain are satisfied


# For Builder Code Apps

This page describes how Builder Code Applications and Trading Terminals can integrate Valantis Prime for API wallet trading from [LST-Staking Discount HyperCore Accounts](/prime/discounts) to enable your user's to access lower fees, and [Customize User HyperCore Account Permissions](/prime/developers/hypercore-connector) to build better UX and security in your application.

### Allowing Smart Contract Account Imports

Most HyperCore Trading Applications already support Valantis Prime. The criteria is simple:

**There must be a way to import an API wallet capable of trading, without needing to sign a message from the parent account.**

The parent account is unable to sign a transaction or a message, since it is a smart contract. Instead- the parent account interacts through HyperCore via CoreWriter and API wallets.

For example, Valantis Prime is fully compatible with Hyperliquid.xyz QR code login method.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2F2ZkF9wWhflLjTp1jQgcr%2Fimage.png?alt=media&amp;token=c9291287-2421-4172-9dcf-d4d835c02386" alt=""><figcaption></figcaption></figure>

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2FM9CrPk34xrwJimO13Pvi%2Fimage.png?alt=media&amp;token=fc19b7dd-27b5-42db-89aa-e2350c677412" alt=""><figcaption></figcaption></figure>

Hyperliquid.xyz QR code login method allows Builder Code's to import: `Parent Account Address` and `API Wallet Private Key` Without strictly requiring a signature from the Parent Account.

If your application uses a custom QR code method to handle API wallet logins, we will be able to support it natively on Valantis Prime tooling- please reach out to us.

For desktop applications, there are several valid authentication flows

#### Allowing a user to paste credentials (user imports API wallet)

`HyperCore Account Address:`

`API Wallet Private Key:`

> Valantis tooling will enable the user to generate & approve an API wallet address externally.

#### Prompting user to approve a pre-generated API wallet address (generate new API wallet)

Paste `HyperCore Account Address:`

Approve API wallet: `{0xAppGeneratedAPIWalletAddress}`

> Valantis tooling will enable the user to approve a pre-generated API wallet address using CoreWriter externally.

It's important for builder code apps that already prompt user's for API wallet approvals do not require/expect user signature before proceeding. Instead, querying Hyperliquid API to check if the API wallet has been approved should allow them to proceed, as they can approve via CoreWriter externally with Valantis tooling:

```
curl -X POST https://api.hyperliquid.xyz/info \                                                                                 
    -H "Content-Type: application/json" \                                                                                         
    -d '{"type": "extraAgents", "user": "<HYPERCORE_ACCOUNT_ADDRESS>"}'
```

Valantis Prime user's are able to approve the exact agent address, name, and expiry that your application expects or needs.

#### Allowing a user to connect a pre-approved API wallet via Browser Wallet

Paste `HyperCore Account Address:`

`Connect API wallet via Browser Wallet`

This solution is not compatible with session signatures, since the user retains custody of the API wallet private key in a self-custody browser wallet.

### Builder Code Signature

Most frontends require that user's approve the builder code of their application to proceed with login. API wallets cannot sign builder code approvals.

Valantis Prime approves Builder Codes through CoreWriter.

For integrators who apply Builder Codes on user trades, this means: *Do not force/expect the Parent Account to approve the Builder Code in your UI, instead check check if the parent account has approved your Builder Code with the appropriate commands before prompting for a Parent Account signature*. This allows accounts to approve your builder code externally.

Example API query to check Builder Code state of Parent Account

```
curl -s -X POST https://api.hyperliquid.xyz/info -H "Content-Type: application/json" -d '{"type":"maxBuilderFee","user":"{Parent Account Address}","builder":"{Builder Code Address}}"}'
```

This will tell you if the user has already approved your Builder Code with the appropriate `maxBuilderFee`.

In practice, Valantis will host tooling for user's to simply approve the Builder Code of popular Builder Apps- reach out for an integration. Optionally, Builder Code Apps are welcome to support the flow for Builder Approval on Valantis Prime directly in their user interface, but it is not required for a successful integration.

### Terms & Service Signature

Smart contracts are not able to sign messages directly. If you wish to collect T\&C signatures from Valantis Prime User's:

**Option 1**: Allow a valid API wallet to accept the T\&C on behalf of the Parent Account. **Option 2**: Integrate EIP-1271; allowing the Parent Account to sign T\&C messages through `isValidSignature` function.

***

## Improving UX with Valantis Prime

Valantis Prime allows any HyperCore User Signed Action to become accessible to an Agent Wallet/Session Key. This requires a one-time signature from the user, and apply any restrictions to the API wallets capabilities over the action.

The first use case we are building is whitelisted transfers- where an API wallet can call `Spot send` through CoreWriter if and only if `destination` is an address which the owner has pre-approved through an EVM transaction (onchain whitelist on HyperEVM).

The design space for abstracting away user signed actions through Valantis Prime can be better understood through the [HyperCore Connector Actions](/prime/developers/hypercore-connector) and [Guardian Transaction Policies](/prime/developers/architecture). Interacting with the Account on EVM and basic outline of SDK methods can be reviewed at [Account Documentation](/prime/developers/account).

Please reach out for support on your unique use case.


# Prime DCA

Prime DCA is the first cross HyperEVM + HyperCore order type built on Valantis Prime.

The Product is live at <https://app.valantis.xyz/dca>


# Audits, Contract Addresses, and Resources

{% content-ref url="/pages/8KqOw98bc24NXmcvUVf6" %}
[Audits](/resources/audits)
{% endcontent-ref %}

{% content-ref url="/pages/XAbZ4JLbAeNeyREedUkb" %}
[Contract Addresses](/resources/deploy-and-build)
{% endcontent-ref %}

{% content-ref url="/pages/T6jgyKJPrvK6HOCJGNyU" %}
[Socials](/resources/links)
{% endcontent-ref %}

{% content-ref url="/pages/0Xyk0qrNkt9Cb0D4cuHz" %}
[How to buy and stake HYPE](/resources/get-hype-on-hyperevm)
{% endcontent-ref %}


# Audits

Collection of all audits performed on Valantis Labs products (Updated October 2026)

## stHYPE

[Three Sigma - February 2025](https://github.com/ValantisLabs/audits/blob/main/Three_Sigma_Feb_25.pdf)

[Pashov, October 2025](https://github.com/pashov/audits/blob/master/team/pdf/stHYPE-security-review_2025-10-13.pdf)

[Pashov - November 2025](https://github.com/ValantisLabs/audits/blob/main/pashov_nov_2025.pdf)

[Guardian - November 2025](https://github.com/ValantisLabs/audits/blob/main/guardian_nov_2025.pdf)

[Guardian - January 2026](https://github.com/ValantisLabs/audits/blob/main/guardian_jan_2026.pdf)

[Obsidian - April 2026](https://github.com/ValantisLabs/audits/blob/main/obsidian_april_2026.pdf)

[stHYPE Restaking Audit](https://github.com/ValantisLabs/audits/blob/main/stakedhypeescrow-security-review-2026-10-18.pdf)

## Valantis Prime

[Obsidian - February 2026](https://github.com/ObsidianAudits/audits/blob/main/2026-02-valantis.pdf)

## Valantis Core Protocol

[Hexens, January 2024](https://github.com/ValantisLabs/valantis-core/blob/main/audits/hexens_Jan24.pdf)

[Statemind, March 2024](https://github.com/ValantisLabs/valantis-core/blob/main/audits/Valantis%20Core%20report.pdf)

### Valantis Periphery

[Statemind, September 2024](https://github.com/ValantisLabs/valantis-periphery/blob/main/audits/statemind_audit_report.pdf)

### Stake Exchange (stHYPE AMM and kHYPE AMM)

[Hexens, March 2025](https://github.com/ValantisLabs/valantis-stex/blob/main/audits/hexens-march-25.pdf)

[Zenith, March 2025](https://github.com/ValantisLabs/valantis-stex/blob/main/audits/zenith-march-25.pdf)

[Hexens, May 2025](https://github.com/ValantisLabs/valantis-stex/blob/main/audits/hexens-may-25.pdf)

### HOT AMM

[Watchpugg, March 2024](https://github.com/ValantisLabs/valantis-hot/blob/main/audits/watchpug_report.pdf)

[Statemind, April 2024](https://github.com/ValantisLabs/valantis-hot/blob/main/audits/statemind_report.pdf)

[Sherlock, July 2024](https://github.com/ValantisLabs/valantis-hot/blob/main/audits/sherlock_report.pdf)

### Validly

[Hexens, September 2024](https://github.com/ValantisLabs/Validly/blob/main/audits/valantis-audit-sept-2024\(Public\).pdf)


# Contract Addresses

## stHYPE Contract Addresses

### Mainnet

| Contract      | Proxy                                        |
| ------------- | -------------------------------------------- |
| stHYPE        | `0xfFaa4a3D97fE9107Cef8a3F48c069F577Ff76cC1` |
| OverseerV1    | `0xB96f07367e69e86d6e9C3F29215885104813eeAE` |
| wstHYPE proxy | `0x94e8396e0869c9F2200760aF0621aFd240E1CF38` |

### Testnet

| Contract   | Proxy                                        |
| ---------- | -------------------------------------------- |
| stHYPE     | `0xe2FbC9cB335A65201FcDE55323aE0F4E8A96A616` |
| OverseerV1 | `0x371de8EBDA2ebB627a4f6d92bD6d01eC385A309b` |
| wstHYPE    | `0x13d76D68170bD5e75eaa18eb074a2f0562f3e6ca` |

This section lists the addresses of Valantis' core protocol contracts and Module factories. It also provides examples on how to deploy working Pools with Modules.

## **Valantis Protocol Contracts HyperEVM**

Protocol Factory: [0x7E028ac56cB2AF75292F3D967978189698C24732](https://hyperevmscan.io/address/0x7E028ac56cB2AF75292F3D967978189698C24732)\
Sovereign Pool Factory: [0xe105af173402b07100aE5648385E1F182bCE21B6](https://hyperevmscan.io/address/0xe105af173402b07100ae5648385e1f182bce21b6)\
Valantis Swap Router: [0x100e18f951b6e200d47303deab838da132f4cfe8](https://hyperevmscan.io/address/0x100e18f951b6e200d47303deab838da132f4cfe8)\
*stHYPE protocol contracts can be found in the* [*Understanding stHYPE*](/stakedhype/stake-accounts) *and* [*Contract Addresses*](/stakedhype/integrate/contract-addresses) *sections.*

## **Valantis Pool Deployments**

### **STEX Pools**

STEXLENS (HyperEVM): [0x95e88072c3fe908101a13584d7A0ff87DaDd88f3](https://hyperevmscan.io/address/0x95e88072c3fe908101a13584d7A0ff87DaDd88f3/contract)

### **stHYPE AMM (HyperEVM)**

stHYPE AMM Pool (stHYPE/WHYPE): [0x5365b6EF09253C7aBc0A9286eC578A9f4B413B7D](https://hyperevmscan.io/address/0x5365b6EF09253C7aBc0A9286eC578A9f4B413B7D)\
STEX AMM (LP Token): [0x39694eFF3b02248929120c73F90347013Aec834d](https://hyperevmscan.io/address/0x39694eFF3b02248929120c73F90347013Aec834d)\
Withdrawal Module: [0x69e487aA3132708d08a979b2d07c5119Bb77F698](https://hyperevmscan.io/address/0x69e487aa3132708d08a979b2d07c5119bb77f698)\
Swap Fee Module (Stepwise): [0x75d85d081E189F72d5C189e94d1c2cc0026AFB70](https://hyperevmscan.io/address/0x75d85d081E189F72d5C189e94d1c2cc0026AFB70/contract)\
Lending Module (MultiMarket): [0x994F02D07B4ed4117701ff4b0197A45c6BC59464](https://hyperevmscan.io/address/0x994F02D07B4ed4117701ff4b0197A45c6BC59464)

Deprecated Lending Module August 2025: Lending Module: [0xf2CE1b504205557e9Ae700Ea480Ce2d633430be1](https://hyperevmscan.io/address/0xf2CE1b504205557e9Ae700Ea480Ce2d633430be1/contract)

### kHYPE AMM (HyperEVM)

kHYPE AMM Pool (kHYPE/WHYPE): [0x88B214eC94276B825E641820D5C97a9042F9Dd60](https://hyperevmscan.io/address/0x88B214eC94276B825E641820D5C97a9042F9Dd60)\
STEX AMM (LP Token): [0xbf747D2959F03332dbd25249dB6f00F62c6Cb526](https://hyperevmscan.io/address/0xbf747D2959F03332dbd25249dB6f00F62c6Cb526)\
Withdrawal Module: [0x3D0737C7FFa223bFbDB228B9ceab85293F16Da12](https://hyperevmscan.io/address/0x3D0737C7FFa223bFbDB228B9ceab85293F16Da12)\
Swap Fee Module (Stepwise): [0x14EFe613b8a1fce7142286D0bC70723519bc4485](https://hyperevmscan.io/address/0x14EFe613b8a1fce7142286D0bC70723519bc4485/contract)\\

Deprecated Lending Module March 2026: Lending Module: [0xdFcAeD3ff2C15dd5d95B3191670F21E73f21c22F](https://hyperevmscan.io/address/0xdFcAeD3ff2C15dd5d95B3191670F21E73f21c22F/contract)

## Valantis Core Deployments For Builders

Valantis Core is generalized infrastructure for building smart contract DEXes- our protocol is deployed on several chains as open source DeFi tooling across the evm ecosystem. If you'd like to build using Valantis on another chain, please reach out to us.

### **Ethereum Mainnet**

Protocol Factory: [0x29939b3b2aD83882174a50DFD80a3B6329C4a603](https://etherscan.io/address/0x29939b3b2aD83882174a50DFD80a3B6329C4a603#code)\
Sovereign Pool Factory: [0xa68d6c59Cf3048292dc4EC1F76ED9DEf8b6F9617](https://etherscan.io/address/0xa68d6c59Cf3048292dc4EC1F76ED9DEf8b6F9617#code)\
Validly Factories: [Deploy a Validly pool on Ethereum Mainnet](/amms-and-vaults/design-space/validly/deployments)\
\
HOT AMM WETH/USDC \[Deprecated]: [0xD9a406DBC1a301B0D2eD5bA0d9398c4debe68202](https://etherscan.io/address/0xD9a406DBC1a301B0D2eD5bA0d9398c4debe68202#code)

### **Arbitrum**

Protocol Factory: [0x7c4fdA6476c0fd90ef9FB13919615F37Fb61dC3A](https://arbiscan.io/address/0x7c4fdA6476c0fd90ef9FB13919615F37Fb61dC3A#code)\
Sovereign Pool Factory: [0x8392E8F0fffE031B841Ba6db06c44F7Be3EE8F26](https://arbiscan.io/address/0x8392E8F0fffE031B841Ba6db06c44F7Be3EE8F26#code)\
Validly Factories: [Deploy a Validly pool on Arbitrum](/amms-and-vaults/design-space/validly/deployments)

HOT AMM WETH/USDC \[Deprecated]: [0xc0c80150750d7a2852147b06c4fbc065bf1e0838](https://arbiscan.io/address/0xc0c80150750d7a2852147b06c4fbc065bf1e0838)

### Ink

Protocol Factory: [0xe00eC9684c1f140a7E7319F66FdD4c99989FE330](https://explorer.inkonchain.com/address/0xe00eC9684c1f140a7E7319F66FdD4c99989FE330?tab=read_contract)\
Sovereign Pool Factory: [0xb2bB5c89aF186D88De011042063BB4e924031cbF](https://explorer.inkonchain.com/address/0xb2bB5c89aF186D88De011042063BB4e924031cbF?tab=contract)\
Validly Factories: [Deploy a Validly pool on Ink](/amms-and-vaults/design-space/validly/deployments)

### **Base**

Protocol Factory: [0x739714B766b0e4Af30794980c4CB2A9150E6AeeC](https://basescan.org/address/0x739714B766b0e4Af30794980c4CB2A9150E6AeeC#code)\
Sovereign Pool Factory: [0xcAC5E476a3cbE6545FB726ea4c583ace92fd5aab](https://basescan.org/address/0xcAC5E476a3cbE6545FB726ea4c583ace92fd5aab#code)

### **Mantle**

Sovereign Pool Factory: [0x739714B766b0e4Af30794980c4CB2A9150E6AeeC](https://explorer.mantle.xyz/address/0x739714B766b0e4Af30794980c4CB2A9150E6AeeC?tab=contract)

## Sovereign Pool: Build your own DEX

This example is for developers wanting to use Valantis' Sovereign Pool as base smart contract infrastructure in order to build a custom DEX on Ethereum mainnet.

```solidity
// Valantis Protocol Factory on Ethereum mainnet
// IProtocolFactory can be imported from valantis-core: 
// https://github.com/ValantisLabs/valantis-core/blob/main/src/protocol-factory/interfaces/IProtocolFactory.sol
// Similar process for other EVM chains, only requires changing factory addresses.
IProtocolFactory protocolFactory = IProtocolFactory(0x29939b3b2aD83882174a50DFD80a3B6329C4a603);

// Initialize struct containing pool's initialization parameters.
// Can be imported from valantis-core:
// https://github.com/ValantisLabs/valantis-core/blob/main/src/pools/structs/SovereignPoolStructs.sol#L8-L20
SovereignPoolConstructorArgs poolArgs;

// Address of pool's token0 and token1.
poolArgs.token0 = 0x...;
poolArgs.token1 = 0x...;

// Address of pool manager
// This is only required to whitelist the Liquidity Module address after deployment,
// It can be reset to zero address afterwards (yielding an immutable pool)
poolArgs.poolManager = 0x...;

// This is the address where pool reserves are stored
// (e.g. any external Vault or Singleton).
// In this example we want to use the pool as the location of token0 and token1 reserves,
// similar to traditional DEXes which have pools as token pairs,
// hence pass it as zero address.
poolArgs.sovereignVault = address(0);

// The pool is configured with a constant swap fee of 5 basis-points.
// Pool manager can change this at any time by adding a custom Swap Fee Module.
poolArgs.defaultSwapFeeBips = 5;

// Deploy Sovereign Pool
address pool = protocolFactory.deploySovereignPool(poolArgs);

// As a developer, the pricing logic of your custom DEX was built as a Liquidity Module.
// See Sovereign Pool docs for more details about its required interface.
address liquidityModule = 0x...;

// Initialize the pool with the custom Liquidity Module deployment
pool.setALM(liquidityModule);

// (Optional), set other modules in the pool, such as Oracle Module or Swap Fee Module
// This is helpful in case there are other domain specific modules whose logic
// can be reused and composed with the Liquidity Module without any changes.

/// ...

// Make pool immutable by revoking pool manager role
pool.setPoolManager(address(0));
```

## Validly Module: Deploy an AMM

Example on how to deploy a Sovereign Pool setup with the Validly Liquidity Module, configured to use Solidly's stable invariant formula, allowing low-slippage trading between USDC and USDT on Ethereum mainnet:\
\\

```solidity
// Validly Factory address, 5 bips fee tier, on Ethereum mainnet
// IValidlyFactory can be imported from:
// https://github.com/ValantisLabs/Validly/blob/main/src/interfaces/IValidlyFactory.sol
IValidlyFactory validlyFactory = IValidlyFactory(0x1896d56F083ec50988d7F9edf204c2AE08b4409a);


// IMPORTANT: Ensure that token0 and token1 are ordered (token0 < token1)
// USDC
address token0 = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
// USDT
address token1 = 0xdAC17F958D2ee523a2206206994597C13D831ec7;

// Deploys the AMM logic using Solidly's stable invariant formula,
// suitable for low slippage trading between stablecoins
// See Validly docs and https://github.com/ValantisLabs/Validly/blob/main/src/Validly.sol#L347-L353
address isStable = true;

// Automatically deploys a Sovereign Pool with the Validly Liquidity Module
address validly = validlyFactory.createPair(token0, token1, isStable);

// Retrieve address of its respective Sovereign Pool
bytes32 poolKey = keccak256(abi.encode(token0, token1, isStable));
address pool = validlyFactory.pools(poolKey);
```


# Socials

[X/Twitter](https://x.com/ValantisLabs)

[Discord](https://discord.com/invite/9cUzQ7EgJQ)

[GitHub](https://github.com/ValantisLabs)

[Mirror](https://mirror.xyz/valantisxyz.eth/)


# How to buy and stake HYPE

A 0-to-1 guide for acquiring HYPE and staking it for stHYPE.

## Buying HYPE <a href="#buy-hype" id="buy-hype"></a>

If you don't already hold HYPE on hyperliquid.xyz, here are step-by-step instructions to getting spot HYPE balance before transferring to EVM

1. Navigate to [Hyperliquid](https://app.hyperliquid.xyz/join/VALANTIS)
2. Connect your wallet, click accept terms, and sign the message in your wallet

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-752cab0afca0ca8320eaf6a8239706a192d5a4ec%2Fconnect.png?alt=media" alt=""><figcaption></figcaption></figure>

3. Deposit USDC
   1. USDC via Arbitrum: You must have USDC on Arbitrum in the connected wallet to complete this step, and ETH on Arbitrum to pay gas fees. Deposit at least 10 USDC directly from the deposit button shown below
   2. USDC via other EVM chains: <https://app.across.to/> supports USDC deposits from most EVM chains.
   3. USDC via Centralized Exchange: Most exchanges (OKX, Bybit, KuCoin, BitGet, and many more) today support Hyperliquid. You can process USDC withdrawals from these exchanges to the Hyperliquid network by withdrawing directly to your wallet address.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-b52372bf21877b9ffa358b2ab0745239377962ab%2Fdeposit.png?alt=media" alt=""><figcaption></figcaption></figure>

*Note: Hyperliquid now supports a variety of native deposit options, including BTC, ETH, SOL, and much more. These balances can be deposited and received as such, before being sold for USDC/USDH to then purchase HYPE.*

4. Navigate to "Portfolio". Transfer your deposited USDC from "Perps" to "Spot."

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-ad1ca2fd613e4e9b4cac608e2779cc239617234c%2Fno%20balance.png?alt=media" alt=""><figcaption></figcaption></figure>

4. Navigate to the HYPE/USDC spot market, enable trading, and complete your trade to buy HYPE

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-78e4bf24e93c26f84ce49f86ce90a465365cdc3b%2Fcomplete%20trade.png?alt=media" alt=""><figcaption></figcaption></figure>

## Transfer HYPE to HyperEVM

1. Locate your spot HYPE assets under "Balances."
2. Click on "Transfer to EVM" and select your desired amount

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-bcadc3024c932659b6274d9057e1b81a5840e07d%2Ftransfer%20to%20evm.png?alt=media" alt=""><figcaption></figcaption></figure>

#### (Optional) Adding HyperEVM as a network to your wallet. <a href="#bridging-from-arbitrum-sepolia-to-hyperliquid-l1-testnet" id="bridging-from-arbitrum-sepolia-to-hyperliquid-l1-testnet"></a>

*Note: Most major wallets now support HyperEVM out of the box. The following info is only for wallets that do not recognize HyperEVM balances after completing step 4.*

Network Details:

* Network Name: Hyperliquid
* ChainID: 999
* RPC URL: <https://rpc.hyperliquid.xyz/evm>
* Currency Symbol: HYPE

## Staking HYPE for stHYPE

1. Navigate to <https://app.valantis.xyz/staking>
2. Connect your wallet

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2FXxxMKz0VEFCPSmRMOJ8U%2Fconnect.png?alt=media&amp;token=dcde34b2-abf6-404a-a443-39f442721554" alt=""><figcaption></figcaption></figure>

3. Input your desired amount
   1. (optional) Select your validator per the [community codes program](/stakedhype/community-codes)
4. Click Stake

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2FCGTWmUKfY28YxWuyLOug%2Fstake.png?alt=media&amp;token=9e4162c0-7d4a-46a7-ad4d-eaf7071674e1" alt=""><figcaption></figcaption></figure>

*Note: It's recommended to leave a small amount of HYPE in your wallet when staking to ensure you are able to cover gas fees for future actions*

6. You now have stHYPE
   1. (optional) Explore the [stHYPE ecosystem](https://app.valantis.xyz/staking?tab=ecosystem) to lend, borrow against, earn additional yield on, and more with your stHYPE


# AMMs and Vaults

Valantis began its journey solely as a smart contract stack to develop bespoke AMMs. The thesis still permeates the Valantis product stack today.

*Liquidity is more efficient when it exploits crypto's properties of composability. DeFi structures should be rethought as asset-specific.*

This was Valantis' vision and purpose with AMMs.

Currently, the only maintained AMM built on the Valantis stack is STEX, a custom AMM built for LSTs (specifically stHYPE).

Valantis-Core is an MIT-licensed open-source stack that uses role-specific modules to reconstruct AMM primitives from first principles, enabling anyone to use the liquidity infrastructure to bootstrap a bespoke system.

{% content-ref url="/pages/tnJQzutJ0Ni6eS7LSEBv" %}
[Embedded Liquidity](/amms-and-vaults/embedded-liquidity)
{% endcontent-ref %}

{% content-ref url="/pages/wR1kJYQIUuCkI8H2TdE6" %}
[The Modular AMM Protocol](/amms-and-vaults/design-space)
{% endcontent-ref %}

{% content-ref url="/pages/80IcolxK6U8cWXyCaxW6" %}
[STEX AMM: Liquidity custom built for LSTs](/amms-and-vaults/staked-amm)
{% endcontent-ref %}


# Embedded Liquidity

A step back on what makes Valantis special

## What is Embedded Liquidity?

Liquidity becomes exponentially more efficient when it is **embedded** — when liquidity venues are designed in deep collaboration with the unique traits of the assets they serve and the ecosystems they exist within.

This is the principle of **Embedded Liquidity:** the concept of structuring trading, yield, and collateral environments around the specifics of an asset's logic, behavior, and economic purpose.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-c65d974c20922d25504e18de54b5ae2bd7b35504%2Fimage%20(4).png?alt=media" alt=""><figcaption></figcaption></figure>

Hyperliquid presents a particularly compelling ecosystem in which to build embedded liquidity solutions. Valantis can embed itself into the Hyperliquid Stack not just by unlocking net new functionality using existing DeFi primitives, but also by integrating with the Hypercore Layer. DeFi's most robust orderbook allows for the creation of liquidity infrastructure that is not possible anywhere else.


# Our Thesis

We believe that the existence of a highly modular, credibly neutral, and immutable core protocol for building embedded liquidity pools will lead to the proliferation of secondary liquidity markets in a way that hasn't been done since Uniswap v2 first launched.

Valantis, as a protocol, poses a few key implications:

1. **Liquidity should be asset-specific.** Designing AMMs, pools, and risk models around individual asset characteristics unlocks deeper liquidity.
2. **Liquidity should be ecosystem-specific.** The lending markets, yield products, and, in some cases, order books available to a DeFi protocol are unique. Assets have flows and dynamics on external venues, so liquidity needs to be embedded within its environment.
3. **Composability is multiplicative.** Each embedded pool should build on top of the others as an integrated system that drives different market participants to different layers of the stack.
4. **Programmable primitives outperform static ones.** ERC20 tokens can embed logic (via wrappers or tokenized LPs) to interface natively with the liquidity stack.


# Why Valantis?

Building custom liquidity solutions from scratch is inherently very difficult. Monolithic DEXs are often designed with core assumptions that limit the design space; this limitation can lead to extensibility becoming a security vulnerability. High complexity, non-reusable components, technical debt, audits, and re-audits all make building custom embedded liquidity venues infeasible for token deployers and developers. Teams find their runway exhausted by the time a solution is production-ready and audit-secured.

The core protocol behind Valantis makes embedded liquidity possible today. The [**Sovereign Pool**](/amms-and-vaults/design-space) approach enables the abstraction of different functions into role-specific and interchangeable Modules, drastically reducing development timelines and exponentially increasing code reusability. Battle-tested Modules can be used and reused, custom functionality can be built into any arbitrary function without affecting the rest of the system, and new custom pools can be shipped to production in weeks, not years.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-0f5cd65bf5db986280a2680e812bd8105ce7de5e%2FSwap%20Steps%20Animation.gif?alt=media" alt=""><figcaption><p>A high level overview of the steps involved in a swap with the Sovereign Pool design.</p></figcaption></figure>

A modular smart-contract basis for Decentralized Exchange design has not been tried before. Previous attempts at creating an extensible basis for DEX development have left the design space small and achieved programmability through insecurity. Valantis Sovereign Pool walks the perfect tradeoff line between max programmability through generality and security through reusability. The modular design thesis begins by addressing the entire design space, establishing a foundation that accommodates it; then it zooms in on a specific use case and builds a module for it.


# The Modular AMM Protocol

How Valantis pools are built, and what has been built so far.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-789514e5977144a3ab6242ec0f82b3a811abb548%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>

Valantis is built on **Sovereign Pools**. Sovereign Pools are a novel modular framework for constructing decentralized exchanges. This architecture introduces a paradigm shift by embracing composability, allowing developers to assemble customized DEX designs through reusable [**Modules**](/amms-and-vaults/design-space/modules). In contrast to monolithic implementations that require building each new AMM iteration from the ground up, Sovereign Pools facilitate the integration of various components responsible for functions such as pricing logic, fee calculation, oracle services, and liquidity management strategies.

In practice, this design space allows for:

* A pool built for LSTs that can exchange its reserves using staking contracts, [**STEX**](/amms-and-vaults/staked-amm)**.**
* An AMM that shares its liquidity between an MEV-Resistant AMM and Offchain RfQ/Order book systems, [**HOT**](/amms-and-vaults/design-space/hot)**.**
* Recovering **ANY** AMM design in less code, for example, Solidly ([**Validly**](/amms-and-vaults/design-space/validly)).

By embracing modularity and composability, Sovereign Pools empower Valantis to innovate on AMM designs while leveraging battle-tested components, reducing implementation complexity, and promoting security through independent module audits.


# The Modules

Sovereign Pool hosts the following reusable core modules:

<table data-view="cards"><thead><tr><th></th><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th><th data-hidden data-card-cover data-type="files"></th></tr></thead><tbody><tr><td><strong>Liquidity Module</strong></td><td><br><br>Customize pricing logic between any assets.</td><td><p><br></p><p><a href="/amms-and-vaults/design-space/modules/liquidity-module">Explore Docs ></a></p></td><td><a href="/amms-and-vaults/design-space/modules/liquidity-module">Liquidity Module</a></td><td><a href="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-9e9a0ed958e7e0a230ecb475487e38f30c7b2a0b%2FLiqudity%20Module%20Icon.png?alt=media">Liqudity Module Icon.png</a></td></tr><tr><td><strong>Pool Manager</strong></td><td><p><em>(Optional)</em></p><p><br>Set up, manage &#x26; update the modules in the pool.<br></p></td><td><br><br><a href="/amms-and-vaults/design-space/modules/pool-manager">Explore Docs ></a></td><td><a href="/amms-and-vaults/design-space/modules/pool-manager">Pool Manager</a></td><td><a href="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-d3f1423fb0092a22d870b2c17ae669fe508d5cc5%2FPool%20Manager%20Icon.png?alt=media">Pool Manager Icon.png</a></td></tr><tr><td><strong>Swap Fee Module</strong></td><td><p><em>(Optional)</em><br></p><p>Customize swap fee logic that can be re-used across liquidity pools.</p></td><td><br><br><a href="/amms-and-vaults/design-space/modules/swap-fee-module">Explore Docs ></a></td><td><a href="/amms-and-vaults/design-space/modules/swap-fee-module">Swap Fee Module</a></td><td><a href="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-1cc4770373fe71b0fdcf60999f1c46e3589ff6f4%2FSwap%20Fee%20Module.png?alt=media">Swap Fee Module.png</a></td></tr><tr><td><strong>Verifier Module</strong></td><td><p><em>(Optional)</em></p><p><br>Arbitrary logic applied before key actions such as swap, deposit, or withdrawal. Can be used to gate certain functions or give different execution modes based on the callers credentials.<br><br></p></td><td><br><a href="/amms-and-vaults/design-space/modules/verifier-module">Explore Docs ></a></td><td><a href="/amms-and-vaults/design-space/modules/verifier-module">Verifier Module</a></td><td><a href="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-da34c37e40232ee6d710407ed9957dd032c02dbb%2FVerifier%20Module%20Icon.png?alt=media">Verifier Module Icon.png</a></td></tr><tr><td><strong>Oracle Module</strong></td><td><em>(Optional)</em></td><td><p><br>Native in-pool data accumulators. Can create custom TWAP or volatility oracle implementations that are reused across liquidity pools.<br><br><br><br></p><p><br><a href="/amms-and-vaults/design-space/modules/oracle">Explore Docs ></a></p></td><td><a href="/amms-and-vaults/design-space/modules/oracle">Oracle Module</a></td><td><a href="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-7a1d90863ec6d626c0be50146094b8e779682fdd%2FOracle%20Module%20Icon.png?alt=media">Oracle Module Icon.png</a></td></tr><tr><td><strong>Sovereign Vault</strong></td><td><em>(Optional)</em><br><br>Custom vault for storing the liquidity pool's reserves. Enables opt-in multi-token singleton architectures, native integrations with yield aggregators, and passive use of the liquidity pool’s funds. The pool natively supports rebase tokens and 0 fee flash loans.</td><td><a href="/amms-and-vaults/design-space/modules/sovereign-vault">Explore Docs ></a></td><td><a href="/amms-and-vaults/design-space/modules/sovereign-vault">Sovereign Vault</a></td><td><a href="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-bdbb0f4a3ed56a461faf4fc45a8294ae637a14a7%2FSovereign%20Vault%20Icon.png?alt=media">Sovereign Vault Icon.png</a></td></tr><tr><td><strong>Gauge</strong></td><td><em>(Optional)</em><br><br>Manage protocol emissions.</td><td><a href="/amms-and-vaults/design-space/modules/gauge">Explore Docs ></a></td><td><a href="/amms-and-vaults/design-space/modules/gauge">Gauge</a></td><td><a href="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-fca8725c3a4309869761eb4acb138a54d39ca46f%2FGauage%20Icon.png?alt=media">Gauage Icon.png</a></td></tr></tbody></table>


# Pool Manager

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-975af2781df6a2870fdec206b6be9a50f34950da%2FPool%20Manager%20Fig.%201_V2%20(1).jpg?alt=media" alt=""><figcaption><p>Pool Manager in context</p></figcaption></figure>

`poolManager` is the role responsible for assembling the most fundamental modules in the pool. The `poolManager` also has the ability to update certain pool-level parameters, such as applying an optional Pool Manager Fee.

Only `poolManager` can call the following functions in Sovereign Pool:

* `setALM` Sets the Liquidity Module. To be called only once.
* `setSwapFeeModule` Sets the Swap Fee Module. This can be called once every 3 days.
* `setSovereignOracle` Sets the Oracle Module. This can be called only once.
* `setPoolManager` can assign the Pool Manager role to another address, or revoke the manager altogether to create an immutable Sovereign Pool implementation. In this case the `poolManager` is reset to the zero address, manager fees are set to 0, and any unclaimed manager fees are transferred to `msg.sender`.
* `setPoolManagerFeeBips` Sets basis point amount of swap fees to be assigned to `poolManager`. This is represented as a percentage of the fees calculated by the Swap Fee Module. Pool Manager Fees cannot exceed 50% of fees earned by LPs.
* `claimPoolManagerFees` Claim all portion of trading fees which are due for `poolManager`. Upon calling this function, the `poolManager` can optionally share a portion of the claimable fees to the pool's `gauge`. There will be a Valantis Protocol `gauge` implementation that allows a pool to participate in VAL-incentive mechanisms. Custom gauges implementations allows the pool to participate in any external scheme that relies on fee collection/measurement. **NOTE: This method works differently in case of rebase tokens:**
  * If reserves are not meant to be stored in the pool (`sovereignVault ≠ address(this)`, and the token to be claimed is a rebase token, this method will not work since earned swap fees are not tracked in the pool. In this scenario, `sovereignVault` would need to implement a custom method to allow `poolManager` to claim due amount of rebase token fees.
  * If reserves are meant to be stored in the pool (`sovereignVault == address(this)`), the pool manager fees would be transferred on every swap, hence no need to use a claim function.


# Liquidity Module

*The Liquidity Module implementation for **STEX** is detailed* [*here*](/amms-and-vaults/staked-amm/swap)*.*

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-5f3dca6f9541ca22da2ab28c98c7f2b7233eadb4%2FLiqudity%20Module%20Fig.%201_V2%20(1).jpg?alt=media" alt=""><figcaption><p>Liquidity Module in context</p></figcaption></figure>

A Liquidity Module (LM) is a mandatory contract in a Valantis Sovereign Pool construction. LMs handle the underlying pricing logic for swaps. A Liquidity Module can host whatever internal logic it wants for asset pricing and it communicates with the Sovereign Pool by implementing the function `getLiquidityQuote`. During a swap, a call is made to the LM function `getLiquidityQuote` which returns an `ALMLiquidityQuote` struct.

There are two callback functions an LM must implement which allow the contract to update its internal state and execute logic post-swap and post-deposit.

## getLiquidityQuote

The Liquidity Module’s `getLiquidityQuote` function hosts the logic for swap pricing and is defined as follows:

```solidity
    /** 
        @notice Called by the Sovereign pool to request a liquidity quote from the ALM.
        @param _almLiquidityQuoteInput Contains fundamental data about the swap.
        @param _externalContext Data received by the pool from the user.
        @param _verifierData Verification data received by the pool from the verifier module
        @return almLiquidityQuote Liquidity quote containing tokenIn and tokenOut amounts filled.
    */
    function getLiquidityQuote(
        ALMLiquidityQuoteInput memory _almLiquidityQuoteInput,
        bytes calldata _externalContext,
        bytes calldata _verifierData
    ) external returns (ALMLiquidityQuote memory);
```

### Inputs

#### Liquidity Quote Struct

This struct contains the user's requested swap along with the fees deducted from the Swap Fee Module.

```solidity
struct ALMLiquidityQuoteInput {
    bool isZeroToOne;
    uint256 amountInMinusFee;
    uint256 feeInBips;
    address sender;
    address recipient;
    address tokenOutSwap;
}
```

`ALMLiquidityQuoteInput` contains the following fields:

* `isZeroToOne` Direction of the swap
* `amountInMinusFee` Amount of input token that `sender` intends to swap, excluding the fee.
* `feeInBips` Fee in bips, returned by Swap Fee Module. **Note:** This fee will be applied to `ALMLiquidityQuote.amountInFilled`
* `sender` Address of `msg.sender` during the swap (the user).
* `recipient` Address which is meant to receive output tokens by the end of the swap
* `tokenOutSwap` Token which the user is meant to receive. This will not necessarily be one of the tokens in the pool in case the LM contains logic that handles more than 2 tokens.

#### External Context

Optional context passed by the user initiating the trade. This context is used by the Sovereign Pool to inform the Swap Fee Module, Verifier Module, and/or Liquidity Module about some external conditions that might affect the user's execution. This field allows the LM to directly implement special logic based on external data, such as: Signed Quotes, Oracle Data, Onchain credentials, etc.

#### Verifier Data

This is optional context produced by the Verifier Module which can be used to inform the Liquidity Module about different swap conditions based on the user's credentials. This allows the Verifier Module to provide the user with different execution based on the external context provided.

### Output Struct

The `getLiquidityQuote` function outputs a quote for the user's trade and returns it to the Sovereign Pool to execute.

```solidity
struct ALMLiquidityQuote {
    bool isCallbackOnSwap;
    uint256 amountOut;
    uint256 amountInFilled;
}
```

`ALMLiquidityQuote` contains the following fields:`amountOut` worth of them to `_almLiquidityQuoteInput.recipient`

* `isCallbackOnSwap` True if the LM requires a callback at the end of the swap.
* `amountOut` Amount of token out which the LM commits to transfer to the user.
* `amountInFilled` Amount of input token which the LM expects from the user, excluding the swap fee portion.

## Callbacks

The liquidity module contains two functions that can be called if the LM is configured to require callbacks. Arbitrary data can be returned back to the LM to update its internal state upon deposits

### Swap Callback

At the end of a swap, the pool can pass data back to the Liquidity Module by calling `onSwapCallback`. This allows a Liquidity Module to update its internal state post-swap, or execute any other necessary logic. The Liquidity Module can request a callback by specifying `isCallbackOnSwap` as True when returning from the `getLiquidityQuote` call. It is important this is set correctly if the LM requires a callback to function properly. The function can execute any logic necessary post-swap.

```solidity
/**
        @notice Callback to ALM after swap into liquidity pool.
        @dev Only callable by pool.
        @param _isZeroToOne Direction of swap.
        @param _amountIn Amount of tokenIn in swap.
        @param _amountOut Amount of tokenOut in swap. 
     */
    function onSwapCallback(bool _isZeroToOne, uint256 _amountIn, uint256 _amountOut) external;
```

### Deposit Callback

Deposits are initially made directly to the LM, and the LM forwards the funds to the proper reserve address (either directly to the Sovereign Pool or a custom Sovereign Vault). The LM can request a callback from the address where the reserves are held by setting `onDepositCallback` to true when calling the `depositLiquidity` on the proper reserve address. The Liquidity Module is responsible for implementing a user-facing deposit function, handling internal accounting/tokenization of LP funds, and forwarding reserves to the proper address.

```solidity
/**
        @notice Callback function for `depositLiquidity` .
        @param _amount0 Amount of token0 being deposited.
        @param _amount1 Amount of token1 being deposited.
        @param _data Context data passed by the ALM, while calling `depositLiquidity`.
    */
    function onDepositLiquidityCallback(uint256 _amount0, uint256 _amount1, bytes memory _data) external;
```


# Swap Fee Module

*The Swap Fee Module implementation for **STEX** is detailed* [*here*](/amms-and-vaults/staked-amm/swap)*.*

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-51eb0ac00ad31effb0a8f73473415a6bb90fa45a%2FSwap%20Fee%20Module%20Fig.%201_V2%20(1).jpg?alt=media" alt=""><figcaption><p>Swap Fee Module in context</p></figcaption></figure>

The Swap Fee Module is responsible for calculating the fees applied at swap time. It is an optional module. When Swap Fee Module is not set, the pool will use the default constant swap fee set at construction.

At the beginning of each swap, the following function gets called:

```solidity
struct SwapFeeModuleData {
    uint256 feeInBips;
    bytes internalContext;
}

function getSwapFeeInBips(
        address _tokenIn,
        address _tokenOut,
        uint256 _amountIn,
        address _user,
        bytes memory _swapFeeModuleContext
    ) external returns (SwapFeeModuleData memory swapFeeModuleData);
```

It takes the following inputs:

* `_tokenIn` Input token for the swap.
* `_tokenOut` Output token for the swap.
* `_amountIn` Input token amount which `_user` wants to trade.
* `_user` address of `msg.sender` in the pool’s swap function.
* `_swapFeeModuleContext` Optional bytes encoded calldata for the case where the Swap Fee Module leverages off-chain or external data to function. For example, this can be used to provide signed price feeds or volatility estimates.

The module returns the fee amount to be charged in basis points (`swapFeeModuleData.feeInBips`) and arbitrary internal context as bytes for the case where the Swap Fee Module needs to be called once again at the end of the swap (`swapFeeModuleData.internalContext`). **IMPORTANT:** Since the Swap Fee Module gets queried before the Liquidity Module, there is no way to know in advance how much liquidity will be filled when quoting fees. Hence the `swapFeeModuleData.feeInBips` should be understood as follows:

First, we calculate `amountInMinusFee` as follows:

```solidity
uint256 amountInMinusFee = Math.mulDiv(_amountIn, 1e4, 1e4 + swapFeeModuleData.feeInBips);
```

Note that `swapFeeModuleData.feeInBips` must not be greater than `1e4`, meaning that the maximum possible swap fee is 50%.

Then, once the Liquidity Module gets queried and returns `liquidityQuote.amountInFilled`, the `effectiveFee` is calculated as follows:

```solidity
uint256 effectiveFee = Math.mulDiv(liquidityQuote.amountInFilled, swapFeeModuleData.feeInBips, 1e4, Math.Rounding.Up);
```

We round up to ensure that fee calculation goes in favor of the pool.

So the total amount that the user gets changed in tokenIn will be `liquidityQuote.amountInFilled + effectiveFee`

`swapFeeModuleData.feeInBips` should be interpreted as the fee multiplier in basis points which gets applied to the tokenIn amount filled by the liquidity module, not the user’s initial `_amountIn`

If `swapFeeModuleData.internalContext` is a non-empty byte encoded payload, the following function gets called after execution of the swap:

```solidity
function callbackOnSwapEnd(
        uint256 _effectiveFee,
        uint256 _amountInUsed,
        uint256 _amountOut,
        SwapFeeModuleData memory _swapFeeModuleData
    ) external;
```

This allows the Swap Fee Module to make any required internal state updates.

Swap Fee Modules can be reusable across both Universal and Sovereign pools without requiring developers to re-write nor replace Liquidity Modules. They can implement any kind of fee calculation logic, as long as they do not quote a fee above 50% of the input token amount on each swap.

**Alternatively**, in the case where a Swap Fee Module is not added to the pool (`swapFeeModule = address(0)`), the pool will use an immutable fee multiplier to calculate swap fees, lowering gas costs. Even after whitelisting a swap fee module, `poolManager` can always reset it to `address(0)`, in which case a default constant swap fee would be applied.

**Alternatively**, both the Swap Fee Module and the immutable default fee can be ignored and the Liquidity Module can consider fee accounting logic when providing price quotes. Though this removes the ability for a Pool Manager to collect fees.

**NOTE:** The Swap Fee Module can only be changed by the Pool Manager once every 3 days. This prevents unexpected changes in Swap Fee logic.


# Verifier Module

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-955c8d84f41154fd0f38d0764ed61ed2ec1055d5%2FVerifier%20Module%20Fig.%201_V2%20(1).jpg?alt=media" alt=""><figcaption><p>Verifier Module in context</p></figcaption></figure>

The Verifier Module is an optional module that individually manages authentication and access to the following pool functions:

* `swap`
* `depositLiquidity`
* `withdrawLiquidity`

The Verifier Module passes verification bytes encoded data to Liquidity Modules, allowing for different swap logic for different parties. The verifier module can also be used for simply gating access to these functions in a permissioned setup.

`verifierModule` can be set in the constructor as an immutable value. If set as `address(0)` the pool will be completely permissionless, and none of the functions described below would apply.

`verifierModule` has to implement the following function:

```solidity
function verify(
        address _user,
        bytes calldata _verificationContext,
        uint8 accessType
    ) external returns (bool success, bytes memory returnData);
```

* `_user` The address of msg.sender which is calling either `swap`, `depositLiquidity` or `withdrawLiquidity` in the Sovereign Pool. This is used as a convenient way to perform authentication of external callers.
* `_verificationContext` Optional byte encoded calldata. This can be used to pass off-chain or external data which is critical to the module's logic.
* `accessType` Flag which tells the Verifier Module through which pool function it is being called:
  * `accessType=0` if `verify` is being called via `swap`
  * `accessType=1` if `verify` is being called via `depositLiquidity`
  * `accessType=2` if `verify` is being called via `withdrawLiquidity`

The verify function returns two variables:

* `success` If True, the pool’s execution control flow will continue uninterrupted, otherwise it will revert.
* `returnData` Byte encoded data to be passed to Liquidity Module’s `getLiquidityQuote` function, in the case of `success=True`

Verifier modules make it straightforward to constrain/customize access to liquidity pools without requiring changes to the Liquidity Module or core protocol contracts. This allows for custom verification logic while preserving pre-established security assumptions.


# Oracle Module

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-219971c405f4ed807ea792890d5c3242c229f1b4%2FOracle%20Module%20Fig.%201_V2%20(1).jpg?alt=media" alt=""><figcaption><p>Oracle Module in context</p></figcaption></figure>

The Oracle Module enables the pool to checkpoint relevant data and state updates after each swap is concluded. Primitives such as TWAP price oracles or volatility oracles can be implemented as Oracle Modules. Oracle Modules implement the following interface:

```solidity
interface ISovereignOracle {
    function pool() external view returns (address);

    function writeOracleUpdate(
        bool isZeroToOne,
        uint256 amountInUsed,
        uint256 fee,
        uint256 amountOut
    ) external;
}
```

`writeOracleUpdate` contains the following inputs:

* `isZeroToOne` Direction of the swap
* `amountInUsed` total input token amount that has been transferred from the user.
* `fee` swap fee charged to the user.
* `amountOut` output token amount transferred to the user.

The Oracle Module is optional and only settable once by the `poolManager`. Once added to a pool, the Oracle Module cannot be removed or changed. This is to ensure that third-party protocols relying on this pool’s oracle can be made sure that the structure of this oracle’s functionality remains immutable.

Sovereign Oracle cannot be set in case reserves are stored outside of the pool (`sovereignVault` is not `pool`).

Developers wishing to rely on the Sovereign Oracle need to carefully understand the assumptions and risks inherent to all other modules in the pool. For example, a faulty or malicious `verifierModule` could censor swaps (thus preventing oracle updates), and a faulty or malicious Liquidity Module could provide inaccurate price data. Reliance on oracles must always be carefully assessed in the context of all its pool dependencies.


# Sovereign Vault

*The Sovereign Vault is currently not used in any Valantis Pools in production.*

*Though Sovereign Vault is a powerful tool for those looking to develop using the Valantis Protocol. Sovereign Vault is used to recover multi-token pool architectures, shared liquidity designs, external use of reserves in primatives like lending markets, singleton patterns for effecient multi-hop swaps, etc.*

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-7b50c3e5058e5dbb9b781c7a25ff0f1faa2441fc%2FSovereign%20Vault%20Fig.%201_V2%20(1).jpg?alt=media" alt=""><figcaption><p>Sovereign Vault in context</p></figcaption></figure>

## Usecases for Sovereign Vault

Sovereign Vault is an optional smart contract that holds all the pool’s token balances between interactions: such as deposits, withdrawals, and swaps. Any whitelisted contract that follows the Sovereign Vault interface can have authority over the pool reserves between these interactions.

Any use case that benefits from a shared accounting model between multiple pools and protocols, or benefits from having funds earning yield via external yields, can choose to leverage the Sovereign Vault interface.

Valantis permits the rise of microcosms of DEX ecosystems with shared rules and properties, as opposed to enforcing a single architecture upon all pools built on the protocol.

#### Singleton for Multi-token

Sovereign Vaults enable gas-efficient multi-hop swaps. A Sovereign Pool might have a custom Sovereign Vault which supports a large number of tokens and liquidity sources. When calling the Sovereign Pool’s swap function, the user can specify their desired `_swapTokenOut` which is not necessarily one of the pool's paired tokens. The pool's Liquidity Module can handle pricing logic between multiple token pairs, potentially even querying other external modules in the process. If multiple Sovereign Pools share the same Sovereign Vault, Valantis can support multi-hop swaps without needing to execute multiple token transfers.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-9bc95f44ee2827e5d493db9f05860fc894d0d9db%2Fshared-vault.png?alt=media" alt=""><figcaption></figcaption></figure>

#### Sovereign Vault for LP Strategies

Liquidity Management primitives built on top of Valantis can specify custom Sovereign Vault logic for sharing funds across multiple Sovereign pools and deploying reserves in external yield-bearing strategies with minimal gas overhead. For example, singleton reserves can be deployed in yield-bearing defi protocols, such as another DEX or lending protocols, and funds can atomically be made available as active liquidity at swap time.

## Using the Sovereign Vault

If `sovereignVault` is not set, funds will by default be stored in the Sovereign Pool itself. Following interactions reserves will be updated and tokens transferred into/out of the pool. If a `sovereignVault` is specified, funds are transferred to/from the specified vault contract and reserves are updated after every interaction. This custom vault can be a custom singleton shared amongst several Valantis and even non-Valantis pools or can be a vault where funds are stored for more complex DeFi, crosschain, or yield-bearing interactions. In other words, when specified, a `sovereignVault` can be any custom vault design, allowing LPs and pool managers to express a broad range of preferences when it comes to liquidity allocation, management, and passive use of funds. It must implement the following minimal interface:

```solidity
/**
    @title Minimal interface for Sovereign Pool's custom vault.
    @dev Sovereign Pools can choose to store their token0 and token1
         reserves in this contract.
         Sovereign Vault allows LPs to define where funds should be stored
         on deposits, withdrawals, and swaps. Examples:
         - A custom LP vault that can provide liquidity to multiple pools on request.
         - A singleton contract.
         - Any external protocol that provides liquidity to incoming swaps on request.
         Moreover, it supports any number of tokens.
    @dev This is meant to be a minimal interface, containing only the functions
         required for Sovereign Pools to interact with.
 */
interface ISovereignVaultMinimal {
    /**
        @notice Returns an array of tokens that can be swapped against for a given Sovereign Pool.
        @param _pool Sovereign Pool to query tokens for.
     */
    function getTokensForPool(address _pool) external view returns (address[] memory);

    /**
        @notice Returns reserve amounts available for a given Sovereign Pool.
        @param _pool Sovereign Pool to query token reserves for.
        @param _tokens Token addresses to query reserves for.
        @dev The full array of available tokens can be retrieved by calling `getTokensForPool` beforehand.
     */
    function getReservesForPool(address _pool, address[] calldata _tokens) external view returns (uint256[] memory);

    /**
        @notice Allows pool to attempt to claim the due amount of `poolManager` fees.
        @dev Only callable by a Sovereign Pool. 
        @dev This is required, since on every swap, input token amounts are transferred
             from the user into `sovereignVault`, to save on gas. Hence manager fees
             can only be claimed via this separate call.
        @param _feePoolManager0 Amount of token0 due to `poolManager`.
        @param _feePoolManager1 Amount of token1 due to `poolManager`.
     */
    function claimPoolManagerFees(uint256 _feePoolManager0, uint256 _feePoolManager1) external;
}
```

The interface above only contains the essential methods required for the Sovereign Pool to communicate with the Sovereign Vault, but custom LMs and external contracts are free to extend it to specify more custom ways to manage deposits, withdrawals, and even multi-hop swaps.

**Note:** In case `sovereignVault` is not the pool, `poolManagerFees` are retrieved from the external Sovereign Vault. The pool cannot guarantee the correct functioning of a Sovereign Vault's `claimPoolManagerFees` implementation, hence as a security measure the pool tracks the expected pool manager fees and enforces that the Sovereign Vault's returned tokens do not exceed this expected value during the claim process. This protects the Vault from leaking funds but does not ensure the Pool Manager receives the fair amount of manager fees. Attention should be paid to a Sovereign Vault's `claimPoolManagerFees` implementation.

**WARNING:** It is recommended that `sovereignVault` implements appropriate reentrancy protections. Depending on its intended use case, it might interact with multiple contracts via a non-trivial sequence of callbacks.


# Rebase token support

Sovereign Pool supports rebase tokens natively, such as stETH and aTokens. Rebase tokens play an important role in Defi, and Valantis aims to treat them as first-class citizens where possible without introducing additional complexity. Rebase tokens change account balances over time due to rebase mechanisms and can lead to rounding errors during transfers by accounting balances using shares.

Rebase tokens can be supported in a Sovereign Pool by setting either `isToken0Rebase=True` or `isToken1Rebase=True`. If one of the above flags is `True`, the following considerations are applied:

* Transfers tolerate rounding errors of up to `REBASE_TOKEN_ABS_ERROR_TOLERANCE`, currently set at `10`.
* Pool reserves are measured as raw token balances, in contrast to having fixed reserves that can only change on swaps, deposits, or withdrawals.
  * This assumes that swap fees are automatically re-compounded into reserves (balances). **WARNING:** This opens up donation attack vectors, since token transfers into the pool would directly increase token balances (hence reserves). It is up to each Liquidity Module to be aware of said risks and have appropriate internal checks and protections.

In addition to all of the above features, Liquidity Modules that handle rebase tokens must have their internal pricing logic robust to arbitrary changes in token balances.


# Submodules

Submodules are extensions of the core modules, designed to make a specific pool implementation reusable for new use cases.

Typically, submodules are most useful in the context of the Liquidity Module, the most general basis of Sovereign Pool. Further dividing the operations of the Liquidity Module into subcomponents allows for some components and operations to be reused while others are customized.

For example, in Stake Exchange (STEX), the STEX Liquidity Module defines two core sub-modules:

1. **Withdrawal Module**\
   processes staked asset -> base asset withdrawals using a direct integration with an LST protocol.
2. **Lending Module**\
   Uses a portion of the pool's reserves in an external yield strategy.

This means core operations of the STEX Liquidity Module such as LP token logic, LP deposits, and LP withdrawal logic can be inherited and reused, while extending pool logic to integrate with new LST Protocols, new Lending Market integrations, or net-new yield sources like HyperCore strategies.

The idea of submodules are extensible to any core designs within' Valantis: and follow along the thesis that building modular means maximizing customizability, reducing time to market, and preserving security.


# Gauge

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-bb0f7f5e528ce58b98e99164755a652cc408612a%2FGauge%20Fig.%201_V2%20(1).jpg?alt=media" alt=""><figcaption><p>Gauge in context</p></figcaption></figure>

`gauge` is an optional module that a pool manager can share a portion of `poolManagerFees` with.

The `gauge` plays an important role in the tentative Valantis token incentive mechanism.

`feeProtocol0` and `feeProtocol1` are the input variables in the Sovereign Pool function `claimProtocolManagerFees` that determine the percentage of pool manager fees shared with the gauge, represented in bips.

The initial Valantis incentive mechanism has not been launched, proper specs for this `gauge` will be released at this time. `gauge` can be set to any contract which benefits from having a portion of fees sent to it, such as an external protocol treasury or similarly designed token incentive mechanism. Any address can be set to `gauge` as long as it is able to call `claimProtocolFees` on the Sovereign Pool.

The Gauge’s only role is to call the `claimProtocolFees`. Protocol fees are incremented whenever `poolManager` calls the `claimPoolManagerFees` function, and if it chooses to allocate a non-zero portion of its earned fees into the `gauge`.

**Note:** Rebase tokens are not supported as protocol fees because pool manager fees are not incremented in the case of rebase tokens. This was a deliberate choice to yield a simpler design for the Sovereign Pool and peripheral governance contracts related to Gauges and VAL emissions.

Only `protocolFactory` can deploy and set a `gauge` for a Sovereign Pool, by calling `setGauge`, and it can do so only once.


# Interacting with Pools

Description of actions in the Sovereign Pool and subsequent interaction between Modules.


# Swap Parameters

The `swap` function contains `_swapParams` as input, whose type is the following struct:

```solidity
struct SovereignPoolSwapParams {
    bool isSwapCallback;
    bool isZeroToOne;
    uint256 amountIn;
    uint256 amountOutMin;
    uint256 deadline;
    address recipient;
    address swapTokenOut;
    SovereignPoolSwapContextData swapContext;
}
```

* `_swapParams.isSwapCallback` True if `msg.sender` expects a callback to claim input token amounts after all swap amounts have been determined (analogous to the swap callback in UniswapV3 pools). If False, input token claiming will happen via `ERC20.transferFrom`
* `_swapParams.isZeroToOne` Direction of the swap
* `_swapParams.amountIn` Maximum amount of input token which the user wants to trade.
* `_swapParams.amountOutMin` Minimum required amount of output token.
* `_swapParams.deadline` Block height at which the swap becomes invalid.
* `_swapParams.recipient` Address which should receive the output token amount.
* `_swapParams.swapTokenOut` Token which the user wants to receive as output. Does not necessarily need to be `token0` or `token1`.
* `_swapParams.swapContext` Struct containing external byte encoded calldata for the Liquidity Module, Swap Fee Module, Verifier Module and swap callback, if applicable.

## Swap Context

The `swapContext` struct includes 4 fields optionally utilized by different modules during swap execution.

```solidity
struct SovereignPoolSwapContextData {
    bytes externalContext;
    bytes verifierContext;
    bytes swapCallbackContext;
    bytes swapFeeModuleContext;
}
```

* `_swapParams.swapContext.externalContext` Is sent to the Liquidity Module during the `getLiquidityQuote` call, this context is likely used to inform the Liquidity Module about any external data it should use for pricing.
* `_swapParams.swapContext.verifierContext` Is sent to the Verifier Module before a swap is made. The verifier module can revert or produce `verifierContext` sent to the Liquidity Module during the `getLiquidityQuote` call.
* `_swapParams.swapContext.swapCallbackContext` Is sent to the Liquidity Module after a swap has been made. This allows the AMM to update state according to external data post swap.
* `_swapParams.swapContext.swapFeeModuleContext` Is sent to the Swap Fee Module before a swap to compute the fees.


# Swap Steps

A Sovereign Pool swap performs the following steps:

## 1. User initiates swap

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-924deea0f54e53ae3a7761cf9be281ced1c0b8ae%2FSwap%20Steps_01.jpg?alt=media" alt=""><figcaption><p>Step 1: User initiates swap</p></figcaption></figure>

* Lock all state modifying functions in the pool.
* Basic checks on `_swapParams`:
  * `_swapParams.amountIn` cannot be 0.
  * `_swapParams.recipient` must be non-zero.
  * `_swapParams.swapTokenOut` cannot be zero address nor input token.
  * In case the pool is meant to hold reserves (`sovereignVault == address(this)`), `_swapParams.swapTokenOut` must be either `token0` or `token1`, meaning that only token0 ↔ token1 swaps are supported. Only if an external vault is specified (`sovereignVault ≠ address(this)`) then multi-hop swaps are allowed (where `_swapParams.swapTokenOut` could differ from `token0` or `token1`).

## 2. Call Verifier Module

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-9db29932c700c02743dd4ad2c0171db6f8875fd4%2FSwap%20Steps_02.jpg?alt=media" alt=""><figcaption><p>Step 2: Call Verifier Module</p></figcaption></figure>

* If `_verifierModule` is non-empty , the Verifier Module is called with the relevant input data. If invalid, it triggers a revert, otherwise, the swap continues and caches any return data from `_verifierModule`.

## 3. Call Swap Fee Module

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-051f197cbb83d934d91c05d12839c49112465384%2FSwap%20Steps_03.jpg?alt=media" alt=""><figcaption><p>Step 3: Call Swap Fee Module</p></figcaption></figure>

* If Swap Fee Module is set, it gets called with the relevant input data to return the swap fee (since we do not yet know how much tokenIn liquidity will be filled, this fee will be applied after calling `getLiquidityQuote`). If Swap Fee Module is not set, a constant and immutable pool fee will be applied. Alternatively, both can be ignored and fees can be designed into a Liquidity Module's internal pricing.

## 4. Call Liquidity Module

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-e8d6f06816e9f4105b3adffad47590c07bb3219e%2FSwap%20Steps_04.jpg?alt=media" alt=""><figcaption><p>Step 4: Call Liquidity Module</p></figcaption></figure>

LM is called using `getLiquidityQuote` with all relevant inputs, including return data from Verifier Module if applicable, and returns the liquidity quote information.

## 5. Check Liquidity Quote Validity

Consistency checks for the liquidity quote are applied. The transaction reverts if one or more of the following are broken:

```
* LM cannot quote more tokenOut reserves than it has in the pool. Except in the case where the funds are not supplied from the pool itself (`sovereignVault ≠ address(this)`)
* LM’s quoted tokenOut amount to the user must be equal to or higher than the user’s `_swapParams.amountOutMin`
* LM’s quoted tokenIn amount + fee must not be greater than the maximum input amount specified by the user (`_swapParams.amountIn`)
* If tokenOut amount quoted is 0, the swap reverts.
```

## 6. Transfer tokenIn

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-3805f3551f00d88dcc53f303f56be182235d1b3d%2FSwap%20Steps_06.jpg?alt=media" alt=""><figcaption><p>Step 6: Transfer tokenIn</p></figcaption></figure>

Transfer the input token from `msg.sender` into `sovereignVault`. Moreover, in the case where `sovereignVault == address(this)`, the input token is a rebase token, and pool manager fees bips for input token are non-zero: we transfer a portion of the input token amount to the `poolManager` as a fee. This is done to simplify accounting of rebase tokens at the pool level.

```
**WARNING:** In case `sovereignVault != address(this)` and `_swapParams.isSwapCallback = true` , `sovereignVault` should implement appropriate reentrancy protections, since `ISovereignPool.sovereignPoolSwapCallback` can re-enter.
```

## 7. Update state variables

Update pool’s state variables, including: reserves of `token0` and `token1` (in case of non-rebase tokens), and `feePoolManager0` or `feePoolManager1` (in case of non-rebase tokens).

## 8. Call Oracle Module

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-cdc1dbe23671ca383a88f1a3c5abc4530366778c%2FSwap%20Steps_08.jpg?alt=media" alt=""><figcaption><p>Step 8: Call Oracle Module</p></figcaption></figure>

Update Oracle Module’s state with the latest swap data: `amountInUsed`, `amountOut` and `effectiveFee`.

## 9. Transfer tokenOut

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-79d6e57eea8ea0d7e81a4a888be42a131738ddbc%2FSwap%20Steps_09%20(1).jpg?alt=media" alt=""><figcaption><p>Step 9: Transfer tokenOut</p></figcaption></figure>

Transfer funds to `_swapParams.recipient` . If liquidity is stored in the pool the funds are transferred directly using ERC20 `transfer()`, otherwise `sovereignVault` is expected to approve the pool before hand, which then transfers funds to `_swapParams.recipient` to via ERC-20 `transferFrom(...)`

## 10. Callbacks

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-96b0a771e21a301a6787feeed4fb4fb19208d80f%2FSwap%20Steps_10.jpg?alt=media" alt=""><figcaption><p>Step 10: Callbacks</p></figcaption></figure>

Perform the following callbacks on swap end:

```
* Call swap fee module, if its returned data payload is non empty.
* Call LM, in case it needs to.
```

## 11. Unlock Pool

All state modifying functions in the pool are unlocked.


# Multi Token Support

## Input Tokens

**Note: Only token0 and token1 are supported as input tokens on every swap!**

## Output Tokens

If funds are meant to be stored in the pool (`sovereignVault == address(this)`): \* Only `token0` and `token1` are supported as output token on swaps.

Else:

Sovereign Pool can support any output token on swaps. To check supported tokens, anyone can call `getTokens` function in Sovereign Pool, which provides relevant information for multi-hop swaps, having the Sovereign Pool as the entry point.

#### Example of a multi-hop swap:

* There are two Sovereign Pools, `A` and `B`, with `token0` and `token1`, and `token1` and `token2`, respectively.
* Each pool has a different Liquidity Module , `LM A` and `LM B`, both sharing the same `sovereignVault`
* A swap for `token0 -> token2` can start in `pool A`, since input token `token0` belongs to `pool A`.
  * `pool A` queries `LM A`.
  * `LM A` understands that `tokenOut` is `token2`
  * `LM A` then query `LM B` to price the `token1 -> token2`
  * `LM A` now has a price for `token0 -> token1 -> token2`
* `sovereignVault` approves `pool A` to transfer the appropriate amount of `token2` to the user
  * `pool A` transfers the appropriate amount of `token0` from the user to `sovereignVault` and transfers the appropriate amount of `token2` from `sovereignVault` to the user.
  * `pool A` optionally makes a callback to update the state of `LM A` and `LM B` postswap.

This can be done in a coordinated way where `LM A` and `LM B` are able to safely update their respective reserves in `sovereignVault`, but the intermediate swap leg does not need a token transfer.

At the end of this process, `pool A` would be able to transfer `token0` from the user into `sovereignVault`, and `sovereignVault` would have approved `pool A` to transfer due amount of output token `token2` from itself to the recipient.

This achieves the same benefits that Singleton centric designs yield for multi-hop swaps, except that it is done through a different architecture that allows multiple Sovereign Pools and Liquidity Modules to decide what kind of vault they want to share. **Note** that the goal was to make multi-hop swaps possible through the Sovereign Pool architecture with custom `sovereignVault`, Valantis Labs has not yet released an implementation of a Singleton-like `sovereignVault`.


# Deposit Liquidity

A Liquidity Module can deposit liquidity into the sovereignVault by calling the `depositLiquidity` function on the Sovereign Pool. This is only true for the case where `sovereignVault` is the pool itself. Otherwise the `sovereignVault` must implement its own function for depositing liquidity.

```solidity
/**
        @notice Deposit liquidity into an ALM Position.
        @dev Only callable by its respective active ALM Position.
        @param _amount0 Amount of token0 to deposit.
        @param _amount1 Amount of token1 to deposit. 
        @param _verificationContext Bytes containing verification data required in case of permissioned pool.
        @param _depositData Bytes encoded data for deposit callback.
        @return amount0Deposited Amount of token0 deposited.
        @return amount1Deposited Amount of token1 deposited.
     */
    function depositLiquidity(
        uint256 _amount0,
        uint256 _amount1,
        address _sender,
        bytes calldata _verificationContext,
        bytes calldata _depositData
    ) external override onlyALM nonReentrant returns (uint256 amount0Deposited, uint256 amount1Deposited)
```

* This function can only be called by the Liquidity Module.
* Liquidity Module is allowed to deposit any amount of `token0` or `token1` to the pool.
* If the pool contains a `verifierModule`, `_sender` and `_verificationContext` would be checked for validity before accepting a deposit.
* This function supports rebase tokens.
* This function is disabled if reserves are meant to be stored outside of the pool (`sovereignVault` is not the pool).
* No pool-level role can pause deposits.

### Control Flow of a Withdrawal

`user` → `Liquidity Module` → Sovereign Pool’s `depositLiquidity`.

The Liquidity Module is free to decide how to interface with users and represent their deposits internally.

* **WARNING:** If `\_amount0` or `\_amount1` is exactly 0, post-deposit callback checks will be skipped (to save gas in case of single token deposits). **This means that if in one of these scenarios, the ALM transfers non-zero amounts, those would not be accounted in reserves and therefore permanently locked!**


# Withdraw Liquidity

A Liquidity Module can withdraw liquidity from the `sovereignVault` by calling the `withdrawalLiquidity` function on the Sovereign Pool. This is only true for the case where `sovereignVault` is the pool itself. Otherwise the `sovereignVault` must implement its own function for withdrawing liquidity.

```solidity
/**
        @notice Withdraw liquidity from this pool to an ALM Position.
        @dev Only callable by ALM Position.
        @param _amount0 Amount of token0 reserves to withdraw.
        @param _amount1 Amount of token1 reserves to withdraw.
        @param _recipient Address of recipient.
        @param _verificationContext Bytes containing verfication data required in case of permissioned pool.
     */
    function withdrawLiquidity(
        uint256 _amount0,
        uint256 _amount1,
        address _sender,
        address _recipient,
        bytes calldata _verificationContext
    ) external override nonReentrant onlyALM
```

* This function can only be called by the Liquidity Module.
* Liquidity Module is allowed to withdraw any amount of `token0` or `token1` from the pool, as long as it is less than the current reserves.
* If the pool contains a `verifierModule`, `_sender` and `_verificationContext` would be checked for validity before accepting a withdrawal.
* This function supports rebase tokens.
* This function is disabled if reserves are meant to be stored outside of the pool (`sovereignVault` is not the pool).
* No pool-level role can pause withdrawals.

### Control Flow of a Withdrawal

`user` → `Liquidity Module` → Sovereign Pool’s `withdrawLiquidity`.

The Liquidity Module is free to decide how to interface with users and account for withdrawals internally. Funds are transferred to the `recipient` specified by the Liquidity Module.


# Flash Loans

* When `sovereignVault == sovereignPool` Flash Loans are supported natively for pool reserves.
* Flash loans have 0 fees.
* Native support for Flash Loans is disabled if reserves are not meant to be stored in the pool (`sovereignVault` is not the pool). Though a `sovereignVault` may implement its own Flash Loan function.
* Flash Loans of rebase tokens are not supported when funds are stored in the pool.


# Hybrid Order Type (HOT)

*HOT was live on Ethereum Mainnet for a period of 6 months, accumulating nearly $6m in TVL and $300m in cumulative volume. It has since been deprecated.*

### About Hybrid Order Type (HOT)

Hybrid Order Type (HOT) is a special type of execution for a Valantis pool.

HOT-enabled pools have two swap execution modes:

* **A permissionless AMM**, closely mimicking a single concentrated liquidity position as implemented in UniV3. This AMM is endowed with a dynamic swap fee mechanism (to be described below) and offers native support for rebase tokens (such as stETH and aTokens).
* **Hybrid Order Type (HOT)** Quotes. Solvers obtain an HOT Quote from the pool’s Liquidity Manager via an API, as a signed intent. These quotes include a volume and price the Solver can directly fill from the pool before expiry. The HOT Quotes also contain an update to the AMM state: spot price and fee parameters are reset after processing the HOT swap.

A Liquidity Manager Protocol exposes an API to market-make directly to Solvers. The Liquidity Manager can include AMM spot price and volatility-dependent swap fee updates inside these quotes.

### AMM Stale-Quote Fee

A time-based dynamic fee ensures that AMM swaps receive a minimum fee following a spot price update. The pool is protected against arbitrage opened up by the spot price becoming stale. The AMM fee increases at a rate defined by the Liquidity Manager, corresponding to the pairs current expected volatility.

**Benefits**

* Solvers integrate with a deterministic source of liquidity (no slippage), providing competitive pricing net gas. This source of liquidity offers a fixed price and partially fillable order for a reasonable amount of time.
* LPs receive extra non-toxic volume from filling Solvers directly, which otherwise might have not been accessible to them.
* Any actor can execute low-gas AMM swaps at a minimum fee if the signed HOT quote quickly lands onchain. This is because, upon a HOT swap being quickly executed onchain, the AMM's spot price will reset to the most accurate and recently observed value (as observed off-chain by the Liquidity Manager), and the swap fee parameter will be reset to its minimum possible value.
* LPs can maximize their non-toxic volume while reducing exposure to Top-of-Block arbitrage.
* Solvers can submit more than one HOT quote per block without worrying about reverted transactions, except on rare edge cases where the wrong input data is signed or the proposed price is significantly different from a reference onchain Oracle.

***

### What's covered in these Hybrid Order Type (HOT) Docs?

\
The following documentation covers the HOT smart contract architecture, which acts as both a Liquidity Module and a Swap Fee Module, plugged into a Valantis Sovereign Pool. Moreover, we also describe the API which connects Liquidity Managers and Solvers for the broadcasting of HOT Quotes as intents.


# Understanding HOT: A Graphical Overview

Hybrid Order Type (HOT) is a new type of liquidity pool built on the Valantis protocol. Designed by Arrakis Finance in collaboration with Valantis Labs, HOT-enabled pools have two execution modes: a permissionless AMM and an RfQ system based on signed HOT quotes. By applying a dynamic fee for traditional AMM swaps as well as adjusting the spot price on HOT quote fulfillment, this design provides robust guarantees of LVR reduction for LPs.\
\
This mechanism is illustrated in the following diagrams:

### Step 1: Solvers Request a Quote.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2F7d0GXR42oUF0H2gKq83g%2F01.png?alt=media&amp;token=61f9a0e6-22b1-4594-84ed-8fe6f95656f1" alt=""><figcaption></figcaption></figure>

***

### Step 2: Liquidity Manager responds with a signed HOT quote bundled with an AMM state update.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2FhVuFxfxfEaYBQ1PLzgo0%2F02.png?alt=media&amp;token=1c1c85bb-5a07-462b-823c-5328885863ed" alt=""><figcaption></figcaption></figure>

***

### Step 3: Solver sends the signed HOT quote to Valantis Pool.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2FSTomPyxP9tPzs4EPPQC2%2F03.png?alt=media&amp;token=8e681aa5-2db8-4bed-abf0-69c42ec9c35c" alt=""><figcaption></figcaption></figure>

***

### Step 4: AMM spot price updated and spread significantly lowered.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fyo5KvWSvaCxgrXlRIbsq%2F04.png?alt=media&amp;token=7e3f1938-2d59-417e-8668-e50f8dbfef50" alt=""><figcaption></figcaption></figure>

***

### Step 5: Permissionless AMM swaps happen at an updated price and lower spread for everyone else.

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2FqL3I1foLPrx5FxlOUNIU%2F05.png?alt=media&amp;token=921dd337-4835-4487-9971-6120782435f2" alt=""><figcaption></figcaption></figure>

***


# HOT Smart Contracts

This page details the functionality of the Hybrid Order Type (HOT) Liquidity Module in a Valantis Sovereign Pool construction.


# Interfaces

The HOT contract implements the two interfaces: `ISovereignALM` and `ISwapFeeModuleMinimal`

```solidity
import { ALMLiquidityQuoteInput, ALMLiquidityQuote } from '../structs/SovereignALMStructs.sol';

/**
    @title Sovereign ALM interface
    @notice All ALMs bound to a Sovereign Pool must implement it.
 */
interface ISovereignALM {
    /** 
        @notice Called by the Sovereign pool to request a liquidity quote from the ALM.
        @param _almLiquidityQuoteInput Contains fundamental data about the swap.
        @param _externalContext Data received by the pool from the user.
        @param _verifierData Verification data received by the pool from the verifier module
        @return almLiquidityQuote Liquidity quote containing tokenIn and tokenOut amounts filled.
    */
    function getLiquidityQuote(
        ALMLiquidityQuoteInput memory _almLiquidityQuoteInput,
        bytes calldata _externalContext,
        bytes calldata _verifierData
    ) external returns (ALMLiquidityQuote memory);

    /**
        @notice Callback function for `depositLiquidity` .
        @param _amount0 Amount of token0 being deposited.
        @param _amount1 Amount of token1 being deposited.
        @param _data Context data passed by the ALM, while calling `depositLiquidity`.
    */
    function onDepositLiquidityCallback(uint256 _amount0, uint256 _amount1, bytes memory _data) external;

    /**
        @notice Callback to ALM after swap into liquidity pool.
        @dev Only callable by pool.
        @param _isZeroToOne Direction of swap.
        @param _amountIn Amount of tokenIn in swap.
        @param _amountOut Amount of tokenOut in swap. 
     */
    function onSwapCallback(bool _isZeroToOne, uint256 _amountIn, uint256 _amountOut) external;
}
```

```solidity
/**
    @notice Struct returned by the swapFeeModule during the getSwapFeeInBips call.
    * feeInBips: The swap fee in bips.
    * internalContext: Arbitrary bytes context data.
 */
struct SwapFeeModuleData {
    uint256 feeInBips;
    bytes internalContext;
}

interface ISwapFeeModuleMinimal {
    /**
        @notice Returns the swap fee in bips for both Universal & Sovereign Pools.
        @param _tokenIn The address of the token that the user wants to swap.
        @param _tokenOut The address of the token that the user wants to receive.
        @param _amountIn The amount of tokenIn being swapped.
        @param _user The address of the user.
        @param _swapFeeModuleContext Arbitrary bytes data which can be sent to the swap fee module.
        @return swapFeeModuleData A struct containing the swap fee in bips, and internal context data.
     */
    function getSwapFeeInBips(
        address _tokenIn,
        address _tokenOut,
        uint256 _amountIn,
        address _user,
        bytes memory _swapFeeModuleContext
    ) external returns (SwapFeeModuleData memory swapFeeModuleData);
}
     
```

The HOT does not implement the following method:

* `ISwapFeeModule.callbackOnSwapEnd` Not implemented, since the SOT does not need to perform any post-swap state updates regarding its fee calculation logic.

For more information regarding each of the modules and methods, see [Sovereign Pool Documentation](https://www.notion.so/3483f7b2867a4b20950afc5ca964e6f3?pvs=21)


# State variables and roles

* `_ammState`

  Struct containing the AMM’s square-root spot price, lower range price and upper range price, each being a `uint160` (In Q64.96 format). The AMM is modelled as a single UniswapV3 range order but without discrete price ticks. In order to save gas on storage ops, the three variables are packed into two `uint256` slots as follows:

  ```solidity
  /**
      @notice Packed struct that contains all variables relevant to the state of the AMM.
      
      * a: sqrtSpotPriceX96
      * b: sqrtPriceLowX96
      * c: sqrtPriceHighX96
          
      This arrangement saves 1 storage slot by packing the variables at the bit level.
      
      @dev Should never be used directly without the help of the TightPack library.

      @dev slot1: << 32 free bits | upper 64 bits of b | all 160 bits of a >>
           slot2: << lower 96 bits of b | all 160 bits of c >>
   */
  struct AMMState {
      uint256 slot1;
      uint256 slot2;
  }
  ```
* `HotWriteSlot`

  Struct containing parameters that get updated on every HOT swap.

  ```solidity
  /**
      @notice Packed struct containing state variables which get updated on HOT swaps.

      * lastProcessedBlockQuoteCount: Number of HOT swaps processed in the last block.
      * feeGrowthE6Token0: Fee growth in pips, per second, of AMM swap fee for token0.
      * feeMaxToken0: Maximum AMM swap fee for token0.
      * feeMinToken0: Minimum AMM swap fee for token0.
      * feeGrowthE6Token1: Fee growth in pips, per second, of AMM swap fee for token1.
      * feeMaxToken1: Maximum AMM swap fee for token1.
      * feeMinToken1: Minimum AMM swap fee for token1.
      * lastStateUpdateTimestamp: Block timestamp of the last AMM state update from an HOT swap.
      * lastProcessedQuoteTimestamp: Block timestamp of the last processed HOT swap (not all HOT swaps update AMM state).
      * lastProcessedSignatureTimestamp: Signature timestamp of the last HOT swap which has been successfully processed.
      * alternatingNonceBitmap: Nonce bitmap (see AlternatingNonceBitmap library and docs).
   */
  struct HotWriteSlot {
      uint8 lastProcessedBlockQuoteCount;
      uint16 feeGrowthE6Token0;
      uint16 feeMaxToken0;
      uint16 feeMinToken0;
      uint16 feeGrowthE6Token1;
      uint16 feeMaxToken1;
      uint16 feeMinToken1;
      uint32 lastStateUpdateTimestamp;
      uint32 lastProcessedQuoteTimestamp;
      uint32 lastProcessedSignatureTimestamp;
      uint56 alternatingNonceBitmap;
  }
  ```
* `hotReadSlot`

  Struct containing parameters that get read, but not updated, during HOT swaps:

  ```solidity
  /**
      @notice Contains read-only variables required during execution of an HOT swap.
      * isPaused: Indicates whether the contract is paused or not.     
      * maxAllowedQuotes: Maximum number of quotes that can be processed in a single block.
      * maxOracleDeviationBipsLower: Maximum deviation in bips allowed when, sqrtSpotPrice < sqrtOraclePrice
      * maxOracleDeviationBipsUpper: Maximum deviation in bips allowed when, sqrtSpotPrice >= sqrtOraclePrice
      * hotFeeBipsToken0: Fee in basis points for all subsequent hot for token0.
      * hotFeeBipsToken1: Fee in basis points for all subsequent hot for token1.
      * signer: Address of the signer of the HOT.
   */
  struct HotReadSlot {
      bool isPaused;
      uint8 maxAllowedQuotes;
      uint16 maxOracleDeviationBipsLower;
      uint16 maxOracleDeviationBipsUpper;
      uint16 hotFeeBipsToken0;
      uint16 hotFeeBipsToken1;
      address signer;
  }
  ```

  `signer`is responsible for signing the `HybridOrderType` struct during HOT swaps. It can be either a EOA or an EIP-1271 compliant smart contract wallet.
* `maxOracleDeviationBipsLower` is the maximum allowed deviation in basis points term between the square root of the oracle price, and the square root of the spot price when sqrtSpotPrice < sqrtOraclePrice. If during deposits or HOT swaps, this deviation threshold is exceeded, then we assume that the spot price is manipulated currently, and we revert the action.
* `maxOracleDeviationBipsUpper` works exactly like maxOracleDeviationBipsLower, but is used when sqrtSpotPrice >= sqrtOraclePrice
* `maxToken{0,1}VolumeToQuote` Maximum amount of volume that `signer` is allowed to quote on each HOT swap.

  These have been implemented as absolute bounds on the per-swap volume, instead of as a fraction of current pool reserves, in order to reduce the attack surface due to how pool reserves are easy to manipulate. `manager` is expected to update these bounds as frequently as necessary, as deposits and withdrawals change reserves in the pool.

  **WARNING:** The higher these values are, the more flexibility `hotReadSlot.signer` has in filling larger HOT swaps, but it also increases the risk of losses for LPs in case of mis-priced quotes. The HOT contract trusts that `manager` sets these values appropriately according to the needs of `liquidityProvider`.
* `manager`

  Address which is responsible for:

  * Updating all parameters in `hotReadSlot`
  * Pausing the HOT contract, hence acting as a circuit-breaker
  * Updating maximum volume of each HOT swap (`maxToken0VolumeToQuote` and `maxToken1VolumeToQuote`)

  **WARNING:** In order to maximise the effectiveness of `manager` as a circuit breaker, and placing reasonable bounds on the amount of volume that `signer` is allowed to quote on each HOT swap, `manager` should not collude with `signer` nor `liquidityProvider`.
* `liquidityProvider`

  Set as immutable upon initialization.

  Liquidity provider is responsible for:

  * Depositing reserves.
  * Withdrawing reserves.
  * Set AMM position’s price bounds.

**WARNING:** The HOT contract makes no assumptions with regards to how reserves are managed or tokenized, and assumes that `liquidityProvider` is a smart contract that implements sufficient internal protections. `manager` can pause the contract at any time, should `liquidityProvider` be faulty.


# AMM

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-9fb3fe3a75bb08e456539a9fece97f20de1733f8%2FAMM.png?alt=media" alt=""><figcaption><p>The AMM</p></figcaption></figure>

The AMM is a single CPMM range order managed by `liquidityProvider`. The AMM achieves lower gas execution than traditional concentrated liquidity AMMs through a simpler implementation.

The `liquidityProvider` can delegate a partial AMM state update to an HOT quote.

## Dynamic AMM Swap Fee

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-106a32ce601a245e331eaf89fda8ac65ee05878c%2FSpread%20Increase.png?alt=media" alt=""><figcaption></figcaption></figure>

HOT Quotes include a parameter `feeGrowth` . This is the per-second growth, in percentage points per second, of the fee percentage applied to AMM swaps.

AMM swap fee for each input token:

$$
\mathrm{fee\mathrm{Bips}\mathrm{Token0}} = \mathrm{feeMinToken0} + \mathrm{feeGrowthE6Token0} \times \frac{(\mathrm{blockTimestamp} - \mathrm{lastProcessedSignatureTimestamp})}{1000000}
$$

$$
\mathrm{fee\mathrm{Bips}\mathrm{Token1}} = \mathrm{feeMinToken1} + \mathrm{feeGrowthE6Token1} \times \frac{(\mathrm{blockTimestamp} - \mathrm{lastProcessedSignatureTimestamp})}{1000000}
$$

Where `lastProcessedSignatureTimestamp` is the UNIX timestamp at which the previously processed HOT quote has been signed (set off-chain, but validated to be within reasonable bounds by the smart contract).

AMM swap fees are capped at their respective maximum value (`feeToken0Max` or `feeToken1Max`).

### **Dynamic fee preventing stale price arbitrage**

The above shows a fee which grows linearly as the last processed AMM state update becomes stale.

`feeGrowthInPipsToken{0,1}` becomes the expected per-second change in spot price, in percentage points. `signer` can update this parameter to reflect the current expected volatility of an asset pair across external markets. Therefore the AMM spot price +- fee (or spread) should be sufficient to prevent arbitrage opened up by large block times, which might cause the HOT quotes to land onchain later than expected, and would therefore update the AMM towards a stale price. The higher the value of `feeBipsToken{0,1}`, the more error tolerance we allow `signer` to have in its proposed AMM spot price update, although significantly lowering the chances that subsequent AMM swaps will get executed (since at this stage the AMM would be quoting worse prices compared to all over venues).

This dynamic fee also ensures AMM swaps occurring directly after an HOT quote is processed receive a minimum fee. The minimum fee can be reasonably lower than comparable AMMs, because a recently and accurately signed AMM spot price price reduces the probability of stale-price arbitrage.

This dynamic fee allows the pool to protect itself from Top-of-Block arbitrage without applying an explicit lock on permissionless swaps. In practice, the AMM swap fee growth should outpace the divergence between the “true” market price (say, from a CEX) and the AMM’s spot price, to minimize exposure to toxic order flow. It is up to the `signer` to constantly update these parameters in response to changing market conditions such as volatility. When HOT quotes do not land in the next block, it is still possible to update the AMM spot price, but the fee (spread) that grows over time accounts for the fact that the staleness of AMM spot price grows over time, hence it acts as a counter-measure against latency arbitrage opportunities.

As a protection measure, the smart contract enforces that `feeToken0Min` and `feeToken1Min` cannot be below some pre-determined value (`minAmmFee`). This is a minimum error assumed to the signer’s prices, and the minimum fee reduces the exposure to unwanted arbitrage opportunities right after AMM updates.

**Operating without the offchain components**

If the offchain API is removed, the pool becomes a low gas single range order AMM (similar to a UniV3 position) with a default maximum fee. This can be useful for long-tail assets which are in the process of bootstrapping sufficient liquidity and volume. Then, as soon as there are two USD-denominated Chainlink price feeds (one for each token in the pool), the HOT mode can be enabled, allowing Solvers and Market Makers to easily list such tokens while benefitting from greater capital efficiency and significantly reduced order-flow toxicity. While the current version of HOT contracts only supports Chainlink price feed as reference onchain oracles, it is possible to integrate other oracles dependencies with minimal smart contract code changes.


# HOT Swap

Given a struct `hot` of type H`olverOrderType`, an HOT swap involves the following steps:

1. `hot.authorizedSender` calls `pool` the Sovereign Pool containing the HOT Liquidity Module.
2. `pool` performs basic validation of input data (see [Sovereign Pool Documentation](https://app.gitbook.com/s/iOJNlAGq0UzMdIB6012x/sovereign-pool-actions/swap-steps)).
3. `pool` calls `HOT` `getSwapFeeInBips` , which calculates the correct swap fee to charge on this HOT swap. In order to trigger the correct branch in the HOT contract, which is both a Liquidity Module and Swap Fee Module, `authorizedSender` should pass a non-empty bytes payload as its `_externalContext` . The authentication of the HOT and the choice of fee path will be performed later.
4. `HOT` checks that `authorizedSender` has chosen the correct Swap Fee Module execution path in step 3. Revert otherwise.
5. Check that the number of HOT swaps on this block does not exceed the maximum limit. Revert otherwise.
6. Determine price to be quoted to `hot.recipient`
7. Validate that `hot` AMM fee parameters meet the correct bounds and criteria:

```
* `feeToken0Min` and `feeToken1Min` cannot be smaller than `minAmmFeeBips`
* All other fee related parameters should be in Bips and consistent with the previously outlined assumptions.
```

8. Validate fundamental parameters in the `hot` struct:

```
* `hot.authorizedSender` must be `msg.sender` in the pool’s swap function
* `hot.authorizedRecipient` must be `_recipient` in the pool’s swap function
* `_amountIn` requested to the pool’s swap function must not be greater than `hot.amountInMax`, therefore bounding the amount of input token that can be exchanged.
* `hot.expiry` must be less than the maximum (constant) delay set in the `HOT` contract. This is to prevent signed HOT quotes from becoming perpetually valid.
* `hot.signatureTimestamp` must not be greater than `block.timestamp` (since the HOT quote must have been signed in an earlier UNIX timestamp), and also `block.timestamp` must be less or equal than `hot.signatureTimestamp + hot.expiry`
* tokenOut amount quoted in the HOT must not exceed `maxToken{0,1}VolumeToQuote`, depending on which token is the output token.
* `hot.nonce` must have the expected value of `expectedFlag` (either 0 or 1). (See HOT bitmap nonces)
```

9. Validate proximity between all square-root prices against the square-root oracle price.
10. Check that EIP-712 signature of `hot` is valid and has been signed by `signer`. Revert otherwise.
11. Update `hybridWriteSlot` parameters.
12. In case the `hot` meets the criteria to update AMM spot price, AMM’s `sqrtSpotPriceX96` gets set to `hot.sqrtSpotPriceX96New`

<figure><img src="https://986147118-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1hNJeG4CApeBcE2NlR61%2Fuploads%2Fgit-blob-b732312ba0fa0be050289f05ae58003ee3821ab8%2FSOT%20Swap%20_%20Step%2012%20V2.png?alt=media" alt=""><figcaption><p>SOT Step 12</p></figcaption></figure>

13. Call returns to the pool’s swap function, which proceeds to exchange the correct input and output token amounts, as well as perform all required internal state updates.


# AMM Swap

One can think of the AMM as a standard UniV3 range order, where `sqrtPriceLowX96` and `sqrtPriceHighX96` represent the upper and lower bounds of the range. These ranges are determined and actively managed by the `liquidityProvider`, to provide the best risk-adjusted returns to its users.

The parameters for an incoming AMM swap can look like the following Solidity example:

```solidity
SovereignPoolSwapContextData memory data;
SovereignPoolSwapParams memory params = SovereignPoolSwapParams({
    isSwapCallback: false,
    isZeroToOne: true,
    amountIn: 1e18,
    amountOutMin: 0,
    recipient: address(this),
    deadline: block.timestamp + 2,
    swapTokenOut: address(token1),
    swapContext: data
});
```

**Note:** It is important to leave the `swapContext` field empty because the HOT differentiates between an HOT swap and an AMM swap by checking if the length of the `swapContext.externalContext` and the `swapContext.swapFeeModuleContext` is 0 or not.

**Effective Liquidity**

AMM swaps can only trade against the liquidity stored in the `_effectiveAMMLiquidity` variable. The remaining part of the reserves are considered passive ( more about this later ). So there might be cases where the reserves available to the the AMM are low, even though the total reserves deposited in the pool are high. This is intentional since `_effectiveAMMLiquidity` requires careful security checks before it can be updated, as described below.

## Effective AMM Liquidity

HOT assumes that at any point of time reserves can be in any arbitrary composition. This is because incoming HOT swaps can trade at any price and amounts (restricted by some configurable bounds), hence creating a misalignment of reserve amounts that would otherwise be implied by a standard UniV3 range order. Consequently, the fundamental invariants of CPMMs do not hold for the reserves.

To make sure that the AMM works correctly no matter what the reserve composition looks like, we decouple the reserves into 2 categories:

1. **Active Reserves** - These are balanced reserves that adhere to the xy=k invariant, and can be utilized by both the AMM and HOT swaps.
2. **Passive Reserves** - Any unbalanced reserves that are not part of the active reserves are considered passive. Only HOT swaps can access the passive reserves.

**Design Goals:**

1. Minimize the amount of passive reserves in the system, by rebalancing into active reserves at any opportunity we get.
2. Make sure that the liquidity remains constant (`_effectiveAMMLiquidity`) before and after any AMM swap.
3. Utilize the maximum possible amount of active reserves.

We achieve these design goals by calling the `_updateAMMLiquidity` internal function after any interaction that could potentially change the reserve composition, and if said interaction contains the appropriate number of invariant checks to mitigate the damage from AMM spot price manipulation.

More about the risks, and protections around `_updateAMMLiquidity` in a separate document.


# Hybrid Order Type (HOT) struct parameters

The Hybrid Order Type (HOT) struct is defined in the smart contract as follows:

````solidity
/**
    @notice The struct with all the information for a HOT swap. 

    This struct is signed by `signer`, and put onchain via HOT swaps.

    * amountInMax: Maximum amount of input token which `authorizedSender` is allowed to swap.
    * sqrtHotPriceX96Discounted: sqrtPriceX96 to quote if the HOT is eligible to update AMM state (see HOT).
    * sqrtHotPriceX96Base: sqrtPriceX96 to quote if the HOT isn't eligible to update AMM (can be same as above).
    * sqrtSpotPriceX96New: New sqrt spot price of the AMM, in Q96 format.
    * authorizedSender: Address of authorized msg.sender in `pool`.
    * authorizedRecipient: Address of authorized recipient of tokenOut amounts.
    * signatureTimestamp: Offchain UNIX timestamp that determines when this HOT intent has been signed.
    * expiry: Duration, in seconds, for the validity of this HOT intent.
    * feeMinToken0: Minimum AMM swap fee for token0.
    * feeMaxToken0: Maximum AMM swap fee for token0.
    * feeGrowthE6Token0: Fee growth in pips, per second, of AMM swap fee for token0.
    * feeMinToken1: Minimum AMM swap fee for token1.
    * feeMaxToken1: Maximum AMM swap fee for token1.
    * feeGrowthE6Token1: Fee growth in pips, per second, of AMM swap fee for token1.
    * nonce: Nonce in bitmap format (see AlternatingNonceBitmap library and docs).
    * expectedFlag: Expected flag (0 or 1) for nonce (see AlternatingNonceBitmap library and docs).
    * isZeroToOne: Direction of the swap for which the HOT is valid.
 */
struct HybridOrderType {
    uint256 amountInMax;
    uint160 sqrtHotPriceX96Discounted;
    uint160 sqrtHotPriceX96Base;
    uint160 sqrtSpotPriceX96New;
    address authorizedSender;
    address authorizedRecipient;
    uint32 signatureTimestamp;
    uint32 expiry;
    uint16 feeMinToken0;
    uint16 feeMaxToken0;
    uint16 feeGrowthE6Token0;
    uint16 feeMinToken1;
    uint16 feeMaxToken1;
    uint16 feeGrowthE6Token1;
    uint8 nonce;
    uint8 expectedFlag;
    bool isZeroToOne;
}

```

````

The HTTP response returned by Valantis API to the solver will include a pool-specific payload containing `HybridOrderType` and an EIP-712 signature by the liquidity manager. Parameters are described as follows:

* `amountInMax` - This is the maximum amount of input token which the solver is allowed to trade against the pool. Partially fillable orders are accepted.
* `sqrtHotPriceX96Discounted`- This is the improved price ( in sqrtX96 form ) that the solver gets if the HOT swap includes a valid AMM state update.
* `sqrtHotPriceX192Base` - This is the fallback price ( in sqrtX96 form ) that the solver gets if its HOT swap has been successfully validated, but did not meet the criteria to update the AMM’s state variables. To simplify the price dynamics and keep it deterministic, the liquidity manager can set it equal to `sqrtHotPriceX96Discounted` , thus giving the price discount to the solver whether or not it updates the AMM state.
* `sqrtSpotPriceX96New` - The most up-to-date AMM square-root spot price, as specified by the liquidity manager. After the HOT has been successfully validated, the AMM’s spot price will be updated towards this value.
* `authorizedSender` - Address of `msg.sender` who is allowed to call the Valantis pool with this payload. This flag in order to prevent front-running or other kinds of unwanted accesses.
* `authorizedRecipient` Address that must receive output token amounts after the AMM swap.
* `signatureTimestamp` Off-chain UNIX timestamp at which the liquidity manager signed the HOT quote.
* `expiry` Duration the HOT quote is valid. It becomes invalid once `blockTimestamp > signatureTimestamp + expiry`
* `feeMinToken0` Minimum AMM swap fee for swaps where token0 is the input token.
* `feeMaxToken0` Maximum AMM swap fee for swaps where token0 is the input token.
* `feeGrowthInPipsToken0` Growth rate per second, in percentage points, to interpolate between `feeMinToken0` and `feeMaxToken0` .
* `feeMinToken1` Minimum AMM swap fee for swaps where token1 is the input token.
* `feeMaxToken1` Maximum AMM swap fee for swaps where token1 is the input token.
* `feeGrowthInPipsToken1` Growth rate per second, in percentage points, to interpolate between `feeMinToken1` and `feeMaxToken1` .
* `nonce` Nonce used for replay protection, set as a bitmap on a `uint56` value.
* `expectedFlag` Expected value for bit at a certain position in a nonce bitmap. See (nonce explanation docs) for more details.
* `isZeroToOne` Direction of the swap. True if input token is pool's `token0` and output token is pool's `token1`, False otherwise.


# Alternating Nonce Bitmap

## **Overview**

To allow for more flexibility and easier future integrations with different solver networks we allow multiple solver quotes to land in the same block, but only the first one gets discounted execution.

Alternating Nonce Bitmap is a gas-efficient mechanism to prevent the replay of HOT attacks on chain.

## Simple Solution to Replay Attacks

The simple solution to this problem is to just store the hash of each solver quote in a mapping onchain. Every time a new quotes comes in, you check if this hash has already been used.

Another variation of this solution is to use unordered nonces, and store these nonces onchain whenever any one of them is used.

These solutions are great because they are simple and quick to implement, but they come with a major gas tradeoff.

Storing the nonce/hash on chain would require a cold storage write of a non-zero storage slot, which costs around **22,000 gas**.

One of our main design goals for the HOT swaps was to minimize gas, while providing a substantial amount of protection against mispriced HOT quotes, so that we can be competitive with cheaper AMMs like UniV2 and even some OTC RFQ smart contracts. Adding this cold storage write could be a substantial deviation from that goal.

It would also be cheaper for a liquidity manager to just update the oracle price in a separate transaction because the fixed cost of making a new transaction is 21,000 gas.

To solve this problem of adding a cold storage write to each solver swap, we aim to design a new replay protection mechanism with the following goal:

1. No additional cold storage writes.
2. As simple as possible to implement onchain
3. Does not add any new trust assumptions on the manager.

## Alternating Bitmap Nonce Solution

It is a fundamental principle that if the quotes persisted forever, then to make sure that no quote is replayed on chain, we would have to store the hashes of all processed quotes to date in a mapping, and check that mapping before any new quote is processed.

But our system has 2 unique properties, that allow us to bypass this:

1. All quotes will **definitely** expire within the expiry time signed by the manager. This expiry time is bounded to be less than a maximum value ( currently 10 minutes ) by the smart contract checks.
2. Each block will only process a maximum of N HOT quotes each block.

This means that we only have to store the nonce for the active quotes in the smart contract, all expired quotes can anyway never be replayed.

Therefore we can reduce the storage requirements of our nonce algorithm to just 1 slot, which is large enough to account for all active quotes currently in the system.

**Note:** By active quotes, we mean all quotes signed by the liquidity manager which have not expired yet. It does not matter if they have been put onchain or not, as long as the current time < expiry time of the quote, the quote is considered to be active.

We know for sure that a manager would never sign more than 256 quotes that haven’t expired, it won’t make any sense to do so, since only a few quotes can go on chain in the same block, and signing more than 3-4 quotes at the same time will most likely not happen in practice.

**HOT Storage**

We maintain a bitmap of 1 storage slot ( i.e 256 bits ) in the smart contract. Out of these, 56 bits are reserved for the Alternating Nonce Bitmap.

**HOT Struct**

We also add the following fields to the HOT quote struct:

* Nonce Value: N ( in the range 0 to 55 )
* Expected Flag: F ( {0,1} )

**Processing of Quotes**

1. When a new quote is put onchain, the HOT contract makes all necessary checks and ensures that the quote has not expired.
2. Check that the Nth bit should be equal to F. If this is true, then the quote is valid, otherwise, it is considered to be a replay and tx reverts.
3. Flip the Nth bit.

<figure><img src="https://github.com/ValantisLabs/valantis-documentation/blob/main/sot/sot-smart-contracts-subpages/.gitbook/assets/image.png" alt=""><figcaption></figcaption></figure>

## **Signer Nonce Selection**

At the time of signing a new quote, the backend first checks its list of all active quotes according to the current time.

Using this list it finds a **free nonce** value and assigns it to the new quote.

**Note:** A free nonce value means that either this nonce value was never used before, or the quote that was assigned this nonce value before has already expired.

It is trivial to make these checks on the backend because in practice we will never have more than 3-4 active quotes at the same time.

Once a free nonce ( N ) has been found for the new quote, the manager checks the current state of the bitmap onchain, and finds the flag value at the Nth bit.

It then assigns this flag value to the Expected Flag field in the HOT quote, and signs the quote to send to the solver.

Using this mechanism, we can guarantee that no solver quotes will be replayed on chain, under one assumption - The backend chooses the nonce correctly.

Also note that in practice this bitmap **won’t require any new storage writes,** because we will reduce the bitmap size to 56 bits ( a maximum of 56 active quotes is still more than enough for our current system ), and then tight pack it with the Solver Write Slot.


# Deposits

```solidity
/**
        @notice Sovereign ALM function to deposit reserves into `pool`.
        @param _amount0 Amount of token0 to deposit.
        @param _amount1 Amount of token1 to deposit.
        @param _expectedSqrtSpotPriceLowerX96 Minimum expected sqrt spot price, to mitigate against its manipulation.
        @param _expectedSqrtSpotPriceUpperX96 Maximum expected sqrt spot price, to mitigate against its manipulation.
        @return amount0Deposited Amount of token0 deposited (it can differ from `_amount0` in case of rebase tokens).
        @return amount1Deposited Amount of token1 deposited (it can differ from `_amount1` in case of rebase tokens).
        @dev Only callable by `liquidityProvider`.
        @dev It assumes that `liquidityProvider` implements sufficient internal protection against
             sandwich attacks or other types of spot price manipulation attacks. 
     */
    function depositLiquidity(
        uint256 _amount0,
        uint256 _amount1,
        uint160 _expectedSqrtSpotPriceLowerX96,
        uint160 _expectedSqrtSpotPriceUpperX96
    ) external onlyLiquidityProvider onlyUnpaused returns (uint256 amount0Deposited, uint256 amount1Deposited);
```

* Only `liquidityProvider` can deposit into `HOT`, which then calls the `depositLiquidity` function in `pool`
* No deposits can happen if `HOT` contract is paused.
* The `depositLiquidity` function offers some degree of protection against spot price manipulation attacks:
  * `liquidityProvider` can pass the expected lower and upper bounds of sqrt spot price. If sqrt spot price is beyond these, the transaction reverts.
  * `HOT` contract also checks that sqrt spot price is within allowed bounds relatively to sqrt oracle price. If sqrt spot price is beyond these, the transaction reverts.
* **WARNING:** It assumes that `liquidityProvider` is a contract that takes sufficient precautions to correctly tokenise liquidity shares (if applicable), prevent sandwich attacks and/or protections against AMM spot price manipulation, or other applicable protections such as timelocks.


# Withdrawals

```solidity
/**
        @notice Sovereign ALM function to withdraw reserves from `pool`.
        @param _amount0 Amount of token0 to withdraw.
        @param _amount1 Amount of token1 to withdraw.
        @param _recipient Address of recipient.
        @param _expectedSqrtSpotPriceLowerX96 Minimum expected sqrt spot price, to mitigate against its manipulation.
        @param _expectedSqrtSpotPriceUpperX96 Maximum expected sqrt spot price, to mitigate against its manipulation.
        @dev Only callable by `liquidityProvider`.
        @dev It assumes that `liquidityProvider` implements sufficient internal protection against
             sandwich attacks or other types of spot price manipulation attacks. 
     */
    function withdrawLiquidity(
        uint256 _amount0,
        uint256 _amount1,
        address _recipient,
        uint160 _expectedSqrtSpotPriceLowerX96,
        uint160 _expectedSqrtSpotPriceUpperX96
    ) external onlyLiquidityProvider
```

* Only `liquidityProvider` can withdraw from `HOT`, which then calls the `withdrawLiquidity` function in `pool`
* The `withdrawLiquidity` function offers some degree of protection against spot price manipulation attacks:
  * `liquidityProvider` can pass the expected lower and upper bounds of sqrt spot price. If sqrt spot price is beyond these, the transaction reverts.
* **WARNING:** It assumes that `liquidityProvider` is a contract that takes sufficient precautions to correctly tokenise liquidity shares (if applicable), prevent sandwich attacks and/or protections against AMM spot price manipulation, or other applicable protections such as timelocks.

#### Setting Price Bounds

```solidity
/**
        @notice Sets the AMM position's square-root upper and lower price bounds.
        @param _sqrtPriceLowX96 New square-root lower price bound.
        @param _sqrtPriceHighX96 New square-root upper price bound.
        @param _expectedSqrtSpotPriceLowerX96 Lower limit for expected spot price (inclusive).
        @param _expectedSqrtSpotPriceUpperX96 Upper limit for expected spot price (inclusive).
        @dev Can be used to utilize disproportionate token liquidity by tuning price bounds offchain.
        @dev Only callable by `liquidityProvider`.
        @dev It assumes that `liquidityProvider` implements a timelock when calling this function.
        @dev It assumes that `liquidityProvider` implements sufficient internal protection against
             sandwich attacks, slippage checks or other types of spot price manipulation.
     */
    function setPriceBounds(
        uint160 _sqrtPriceLowX96,
        uint160 _sqrtPriceHighX96,
        uint160 _expectedSqrtSpotPriceLowerX96,
        uint160 _expectedSqrtSpotPriceUpperX96
    ) external poolNonReentrant onlyLiquidityProvider
```

The `liquidityProvider` role can manage the lower and upper bound of the liquidity position using the `setPriceBounds` function, to provide a concentrated liquidity experience for its users.

**Note:** Although we assume that the LPs trust the `liquidityProvider` when they deposit their funds, the liquidity provider can additionally add a small timelock to the setPriceBounds function call, to prevent attack vectors, where a malicious liquidityProvider concentrates liquidity at a bad spot price.\
\
**WARNING:** `liquidityProvider` is expected to have appropriate internal protections against any kind of spot price manipulation attack, or other common attack vectors. ( More on this in the threats and roles document )


# Deployment Assumptions

**Sovereign Pool and HOT deployment assumptions**

After deploying an instance of the `HOT` contract bound to a Sovereign Pool `pool`, the following assumptions are made:

* `pool` cannot have an external Sovereign Vault (meaning that reserves are always kept in `pool`)
* `pool` cannot have a Verifier Module.
* Once an `HOT` instance is deployed, `poolManager` will set it as the Liquidity Module and Swap Fee Module in `pool`. `poolManager` should not change Swap Fee Module to any another address.


# Liquidity Manager Docs

The HOT AMM is a Liquidity Module (LM) attached to a Valantis Sovereign Pool. More information about the Sovereign Pool <> LM architecture can be found in the [Sovereign Pool documentation](/amms-and-vaults/design-space).

A Liquidity Module is the Sovereign Pool module that defines the pricing logic for swaps, as well as control of deposits and withdrawals into the pool.

Each Sovereign Pool has a unique and immutable Liquidity Module attached to it, in this case, it is the HOT AMM Liquidity Module.

The HOT AMM has the following roles:

1. It holds the business logic for swaps. Although users interact with the Sovereign Pool as the entry point for swaps, the Sovereign Pool internally refers to the HOT AMM for pricing logic, i.e. the amount of input and output token that a user sends and receives, respectively.
2. LPs deposit and withdraw liquidity through the HOT AMM contract. Although token reserves are stored in the Sovereign Pool itself.
3. The HOT AMM is a special case of a Liquidity Module that also controls the swap fee logic, hence it also implements the Valantis Swap Fee Module interface. This means Sovereign Pool’s Swap Fee Module address is also set to the HOT AMM address.

**Note:** An HOT sovereign pool should be constructed so that

`LiquidityModule address == SwapFeeModule address == HOT deployment address`

or the system may not function as intended.

This section provides a detailed description of the different roles which are relevant to the HOT Liquidity Module, as well as expanding on the most important integration aspects and security assumptions from the perspective of a Liquidity Manager (also known as Market Maker).


# Reference Oracle

Oracle price feeds are set in the HOT to give the system a reference source of manipulation-resistant prices. There are two Oracle price feeds, one for token0/USD price and another for token1/USD price. One can then calculate the square-root Oracle price for the HOT, which is implemented in the HOTOracle contract. The current implementation uses Chainlink oracles for both price feeds, but it is possible to replace them with alternative oracles by using wrapper contracts.

## Security

The use of oracles is purely a safety measure against a malicious/compromised Liquidity Manager and to protect against certain spot-price manipulation attacks. It achieves this by placing bounds on the price the HOT Signer can quote Solvers. Separately, there are bounds on both the volume a Manager can quote a Solver, and the number of HOT Quotes that can be processed per block.

Critical functions such as Liquidity Deposits, HOT swaps, and AMM spot price updates are checked against the Oracle price.

## Max Deviation

We do not assume that the oracle is precise, hence the `maxOracleDeviationBips` allows for reasonable deviation between the square-root spot price and the square-root oracle price.\
\
The deviation protects deposits and swaps against spot price manipulation attacks. We do no check the deviation during withdrawals, to ensure that they remain completely permissionless at all times. This means that LPs can safely withdraw from the pool, even in case of a faulty oracle.

During `depositLiquidity`, the call will revert with the error HOT`__depositLiquidity_spotPriceAndOracleDeviation` if the current spot price deviates too far from the reference oracle. This prevents front-running liquidity deposits within certain price manipulation bounds. Additionally, periphery contracts can set even stricter slippage protection conditions on deposits.

During `_hotSwap`, the call will revert with the error `HOTParams__validatePriceConsistency_hotAndSpotPriceNewExcessiveDeviation` if the Solver's quoted price deviates more than `hotMaxDiscountBips` from the new AMM spot price. This prevents a malicious or compromised HOT Signer from giving out exploitative HOT Quotes, beyond these prescribed deviation bounds.

Before updating AMM spot price using `setSqrtSpotPriceX96` inside `_hotSwap`, the call will revert with the error `HOTParams__validatePriceConsistency_newSpotAndOraclePricesExcessiveDeviation` if the new AMM spot price deviates from the oracle price by more than `maxOracleDeviationBips`. This prevents a compromised HOT Signer from making malicious AMM spot price shifts, beyond these prescribed deviation bounds.

A low `maxOracleDeviationBips` gives greater flexibility to the Signer to price HOT Quotes and flexibly update the AMM's spot price, at the cost of placing more trust in the Liquidity Manager. The manager should set this bound appropriately depending on the precision of the oracle and the volatility of the asset. Users who deposit through Liquidity Provider should be aware of all of the above price deviation bounds.

## Stale Price

The pool checks that the price feed has been updated recently. The error `HOTOracle___getOraclePriceUSD_stalePrice` means that it has been a long time since the oracle got updated, hence as a safety measure critical pool operations such as liquidity deposits, HOT swaps, and AMM state updates are closed. Users can still withdraw liquidity and swap via the AMM with constant fees.

The time after which the oracle price is considered stale is set during deployment with the help of these public variables: `maxOracleUpdateDurationFeed0` & `maxOracleUpdateDurationFeed1`


# Deposit

We only allow deposits from the `liquidityProvider` address. Any logic for handling user deposits needs to be implemented by the `liquidityProvider` itself. On each deposit, `liquidityProvider` should approve to HOT contract the amounts of token0 and/or token1 which should be deposited into the Sovereign Pool.

```solidity
    /**
        @notice Sovereign ALM function to deposit reserves into `pool`.
        @param _amount0 Amount of token0 to deposit.
        @param _amount1 Amount of token1 to deposit.
        @param _expectedSqrtSpotPriceLowerX96 Minimum expected sqrt spot price, to mitigate against its manipulation.
        @param _expectedSqrtSpotPriceUpperX96 Maximum expected sqrt spot price, to mitigate against its manipulation.
        @return amount0Deposited Amount of token0 deposited (it can differ from `_amount0` in case of rebase tokens).
        @return amount1Deposited Amount of token1 deposited (it can differ from `_amount1` in case of rebase tokens).
        @dev Only callable by `liquidityProvider`.
        @dev It assumes that `liquidityProvider` implements sufficient internal protection against
             sandwich attacks or other types of spot price manipulation attacks. 
     */
    function depositLiquidity(
        uint256 _amount0,
        uint256 _amount1,
        uint160 _expectedSqrtSpotPriceLowerX96,
        uint160 _expectedSqrtSpotPriceUpperX96
    ) external onlyLiquidityProvider onlyUnpaused returns (uint256 amount0Deposited, uint256 amount1Deposited)
```

* A common error while depositing is `HOT__depositLiquidity_spotPriceAndOracleDeviation` It means that the oracle price is too far away from the current AMM spot price (above `maxOracleDeviationBips`, in relative distance). To deposit more liquidity a user needs to wait for the oracle price to update, or correct the spot price by making an AMM swap. In the absence of Oracle failure, we can expect the spot and Oracle prices to stay within the set bounds by relying on HOT spot price updates or AMM swap arbitrageurs. (IMP)


# Withdraw

Withdrawals are always available in the HOT contracts. No role or component failure can prevent the `liquidityProvider` from withdrawing deposited funds.

Only the `liquidityProvider` can withdraw LP funds from the pool, it is the responsibility of this role to handle individual deposit’s liquidity shares (if applicable) and withdrawal accounting.

**Note:** The Pool Manager can withdraw its fees from the Sovereign Pool directly, this is the only other role that has the permission to withdraw any funds from the pool. The Sovereign Pool ensures, that the Pool Manager can only withdraw its fees and nothing more.


# Signature

HOT uses an [EIP 712](https://eips.ethereum.org/EIPS/eip-712) signature scheme. The signature verification is done through the `isValidSignatureNow` function in the Open Zeppellin `SignatureChecker` library.

```solidity
        bytes32 hotHash = hot.hashParams();
        if (!hotReadSlotCache.signer.isValidSignatureNow(_hashTypedDataV4(hotHash), signature)) {
            revert HOT___hotSwap_invalidSignature();
        }

```

To construct a valid signature the typehash and the domain separator are needed, both of which can be calculated offchain or retrieved from onchain public functions in the smart contract. A working foundry example is provided below:

```solidity
    function getEOASignedQuote(
        HolverOrderType memory hotParams,
        uint256 privateKey
    ) public view returns (bytes memory signedQuoteExternalContext) {
        bytes32 digest = keccak256(
            abi.encodePacked(
                '\x19\x01',
                hot.domainSeparatorV4(),
                keccak256(abi.encode(HOTConstants.HOT_TYPEHASH, hotParams))
            )
        );

        (uint8 v, bytes32 r, bytes32 s) = vm.sign(privateKey, digest);

        bytes memory signature = abi.encodePacked(r, s, bytes1(v));

        signedQuoteExternalContext = abi.encode(hotParams, signature);
    }
```

The complete work-flow of a HOT swap can be found in the [`scripts/SepoliaHOTSwap.s.sol`](https://github.com/ValantisLabs/valantis-sot/blob/main/scripts/SepoliaSOTSwap.s.sol)file.


# Swap

Full documentation on the Sovereign Pool swap function and corresponding Parameters can be viewed in [Sovereign Pool Documentation: Swap Parameters](/amms-and-vaults/design-space/modules/sovereign-pool-actions/swap-params).


# Swap Context

The HOT utilizes `swapContext` to pass HOT Quotes and AMM state updates to the HOT Liquidity Module, full documentation can be viewed in [Sovereign Pool Documentation: Swap Context](/amms-and-vaults/design-space/modules/sovereign-pool-actions/swap-params#swap-context). In an HOT-enabled pool, the presence of non-empty `swapContext` differentiates between the two types of swaps:

1. **AMM Swaps:** Permissionless swaps for all users, happening against a single concentrated liquidity position, according to a UniswapV3 like constant-product AMM (CPAMM) logic. Includes empty `swapContext`.
2. **Hot Swaps:** Permissioned swaps that are only available to the solver with a valid HOT Quote that includes an EIP-712 signature from the HOT Signer. Includes non-empty `swapContext`.

We will now discuss how to set the `swapContext` correctly for each of these swap types.


# AMM Swap

For AMM swaps, the swap context should be left completely empty. The rest of the swap params can be set according to the user’s order.

**Example AMM Swap Params**

```solidity
        // To be left empty
        SovereignPoolSwapContextData memory data;
        SovereignPoolSwapParams memory params = SovereignPoolSwapParams({
            isSwapCallback: false,
            isZeroToOne: true,
            amountIn: 1e18,
            amountOutMin: 0,
            deadline: block.timestamp + 2,
            recipient: address(this),
            swapTokenOut: address(token1),
            swapContext: data
        });

        pool.swap(params);

```


# HOT Swap

To configure an HOT swap correctly, one needs to set the following two parameters in `_swapParams.swapContext`:

1. **swapFeeModuleContext** - Set this to any value that is not empty. The exact value does not matter, the only requirement is that the length of this array should not be 0. Any value such as “0x01” will work.
2. **externalContext** - The value should be the concatenation of the ABI-encoded HOT struct and signature received from the HOT signer. For example: `bytes memory externalContext = abi.encode(hotParams, signature)`

### Hybrid Order Type Params

```solidity
/**
    @notice The struct with all the information for a HOT swap. 

    This struct is signed by `signer`, and put onchain via HOT swaps.

    * amountInMax: Maximum amount of input token which `authorizedSender` is allowed to swap.
    * sqrtHotPriceX96Discounted: sqrtPriceX96 to quote if the HOT is eligible to update AMM state (see HOT).
    * sqrtHotPriceX96Base: sqrtPriceX96 to quote if the HOT isn't eligible to update AMM (can be same as above).
    * sqrtSpotPriceX96New: New sqrt spot price of the AMM, in Q96 format.
    * authorizedSender: Address of authorized msg.sender in `pool`.
    * authorizedRecipient: Address of authorized recipient of tokenOut amounts.
    * signatureTimestamp: Offchain UNIX timestamp that determines when this HOT intent has been signed.
    * expiry: Duration, in seconds, for the validity of this HOT intent.
    * feeMinToken0: Minimum AMM swap fee for token0.
    * feeMaxToken0: Maximum AMM swap fee for token0.
    * feeGrowthE6Token0: Fee growth in pips, per second, of AMM swap fee for token0.
    * feeMinToken1: Minimum AMM swap fee for token1.
    * feeMaxToken1: Maximum AMM swap fee for token1.
    * feeGrowthE6Token1: Fee growth in pips, per second, of AMM swap fee for token1.
    * nonce: Nonce in bitmap format (see AlternatingNonceBitmap library and docs).
    * expectedFlag: Expected flag (0 or 1) for nonce (see AlternatingNonceBitmap library and docs).
    * isZeroToOne: Direction of the swap for which the HOT is valid.
 */
struct HybridOrderType {
    uint256 amountInMax;
    uint160 sqrtHotPriceX96Discounted;
    uint160 sqrtHotPriceX96Base;
    uint160 sqrtSpotPriceX96New;
    address authorizedSender;
    address authorizedRecipient;
    uint32 signatureTimestamp;
    uint32 expiry;
    uint16 feeMinToken0;
    uint16 feeMaxToken0;
    uint16 feeGrowthE6Token0;
    uint16 feeMinToken1;
    uint16 feeMaxToken1;
    uint16 feeGrowthE6Token1;
    uint8 nonce;
    uint8 expectedFlag;
    bool isZeroToOne;
}
```

This is the HOT struct, exact descriptions of all the fields can be found in the Natspec documentation above. Here we shall discuss the important things to keep in mind and common reverts. Most of these checks can be found in the **src/libraries/HOTParams.sol** file, we will only discuss some common ones in this document.


# HOT Quote Parameters

## expiry

```
The expiry determines how long the Signed HOT Quote is valid. If the Signed Quote lands onchain after expiry, the Quote is not valid and the swap will revert. Suppose the signatureTimestamp = 1000, and we want to make sure that this quote cannot be used after 2 mins, then the expiry = 2 * 60 = 120. 
The expiry is bounded by the `maxDelay` variable onchain, this means that expiry always has to be ≤ hot.maxDelay()
```

## signatureTimestamp

```
The timestamp at which the signer signs the quote offchain. A signature is only considered valid if: 

1. The signature timestamp is less than or equal to the current block timestamp
2. `block.timestamp <= hot.signatureTimestamp + hot.expiry`
```

## prices

```
The pool implements many checks to try to mitigate the damage caused by a malicious signer.

1.  Both the old and new square-root spot price values of the AMM cannot be too far away from the square-root oracle pricee. The allowed relative deviation is set by the `maxOracleDeviationBips` variable, and is configurable by the manager.
More precisely, this check is applied to both the new and old spot prices during an HOT swap AMM state update.
    
2. The price that the solver is receiving, cannot be too far away from the current spot price of the pool. The exact allowed relative deviation is set by the `solverMaxDiscountBips` parameter, which is set by the manager.

You can look at exactly how all price-related checks are enforced in the `validatePriceConsistency` function in the HOTParams library.
```

## Fee Values

```
All fee parameters are validated for basic consistency and bounded according to the public immutable values: `minAMMFee`, `minAMMFeeGrowthInPips`, and `maxAMMFeeGrowthInPips`.
Any fee value cannot be greater than 10_000, since they are in basis-points.
```

**NONCE** is discussed on the next page.


# Bitmap Nonce Instructions

This page is intended as instructions for a Liquidity Manager to construct valid nonce values compatible with the HOT bitmap. Full documentation for the HOT Nonce Bitmap can be found here: [HOT Quote replay protection](/amms-and-vaults/design-space/hot/hot-smart-contracts-subpages/bitmap).

The HOT contract has a bitmap of 56 nonces. The signer keeps track of all signed quotes that have not yet expired or landed onchain, these quotes are considered “active”.

A nonce assigned to an “active” quote is considered “taken”, all other nonces are “free”.

When a new solver quote request comes in through the API, the signer has to do the following things:

1. Identify a “free” nonce.
2. Set the `expected` flag to the current value of the bit currently present at the selected nonce index. For example, if the current Nonce Bitmap looks like the Old Bitmap shown above, then If nonce = 0, expectedFlag = 1 If nonce = 1, expectedFlag = 0 If nonce = 2, expectedFlag = 1, and so on.

When the HOT quote is processed, the bit present at the specified nonce index is checked against the expected flag. If the values are the same, the quote is valid and the swap is processed. After processing the swap, the bit on the specified nonce index is flipped to prevent a replay attack. The next time this nonce is used, the expected flag must correspond to the newly flipped bit value.

**Note**: When assigning a nonce that is already assigned to another “active” quote, there is a possibility that one of these quotes can be replayed onchain. It is important for a HOT Signer to make sure that the nonce they are including in a new quote is “free”.


# Risks and Trust Assumptions

The HOT is a hybrid AMM system with flexible repricing and rebalancing logic, given off-chain instructions signed by a designated HOT Singer.

Even though the HOT smart contract provides a substantial amount of protection mechanisms against known threats such as front-running of swaps and mispriced HOT quotes, as well as circuit breaker capabilities entrusted to the HOT Manager role, it cannot fully protect HOT Liquidity Provider and any respective passive LPs from all potential attack vectors if the on/offchain system is not set with appropriate bounds and precautions.


# Roles

The complete HOT system has 4 important roles:

* Sovereign Pool Manager
* HOT Manager
* HOT Signer
* HOT Liquidity Provider

This section will review the responsibilities, trust assumptions and security model for all four.


# Sovereign Pool Manager

### Functions

* **setALM**: Initializes the Liquidity Module (LM) address of the pool. Can only be called once.
* **setPoolManager:** Sets the address of poolManager.
* **setPoolManagerFeeBips:** Sets fee in BIPS for poolManager.
* **setSovereignOracle:** Sets Sovereign Oracle Module in this pool.
* **setSwapFeeModule:** Sets the Swap Fee Module for this pool.

### Security Model

1. The HOT should be set as the pool's LM and swapFeeModule. The manager can only set the ALM once, but the swap fee module can be changed. Therefore the Pool Manager should be a smart contract that cannot change the swapFeeModule once it is set to the HOT.
2. Adding a new Sovereign Oracle to the pool has no security implications for the HOT.
3. The Sovereign Pool Manager should not be able to change the pool manager address arbitrarily once it is set.

### Trust Assumptions

1. The Sovereign Pool Manager should set the poolManagerFeeBips reasonably. Setting this variable to a high value could lead to high fees being charged from LPs. This fee is also capped at 50% ( of all accumulated swap fees ) in the smart contracts.


# HOT Manager

### Functions

* **setManager:** Changes the `manager` of the HOT contract.
* **setSigner:** Changes the signer of the HOT contract.
* **setMaxTokenVolumes:** Changes the maximum token volumes available for a single HOT quote.
* **setMaxAllowedQuotes:** Updates the maximum number of HOT quotes allowed in a single block.
* **setMaxOracleDeviationBips:** Sets the maximum allowed deviation between AMM and Oracle price.
* **setPause:** Sets the pause flag, which instantly pauses all critical functions except withdrawals.

### Security Model

1. All HOT manager functions except `setPause` should be placed under an appropriate timelock. LPs should verify that they are comfortable with the timelock value before depositing into the pool.
2. The manager acts like a guardian over the security parameters of the pool. This role should be controlled by a neutral, independent entity, completely separate from the `signer` and `liquidityProvider` roles.
3. The manager should actively monitor HOT transactions and pause the pool if any malicious activity is observed.
4. The `maxAllowedQuotes` variable should be set to relatively low values considering the signer's needs and the chain's block time. Higher `maxAllowedQuotes` values could allow the signer to sign a malicious HOT and drain some portion of LP funds in a single block. In most practical systems, a `maxAllowedQuotes > 5` should not be needed.
5. The `maxTokenVolumes` values should be set to relatively low values, proportional to the reserves in the pool. It should be updated regularly as the reserves increase or decrease.
6. The `maxOracleDeviationBips` variable should be set to a relatively low value, considering the token pair's volatility and the oracle's latency.

### Trust Assumptions

If bounds are set incorrectly, then at least two known attacks could become possible:

1. [Malicious Signer Threat](/amms-and-vaults/design-space/hot/risks-and-trust-assumptions/threats/malicious-signer-threat)
2. [Deposit Sandwich Threat](/amms-and-vaults/design-space/hot/risks-and-trust-assumptions/threats/deposit-sandwich-threat)


# HOT Signer

### Functions

* Can sign HOT Quotes for HOT swaps.

### Security Model

1. The signer is responsible for market-making for all incoming solver swaps on behalf of the LPs.
2. EOA signers should ensure their private key is managed securely, using industry-leading practices.

### Trust Assumptions

All LPs trust the signer to run a competitive market-making algorithm on the backend and ensure their private key is secure.

A bad signer could cause losses to LP funds because of LVR or [malicious signer](/amms-and-vaults/design-space/hot/risks-and-trust-assumptions/threats/malicious-signer-threat) attacks.

**Note**: The HOT AMM infrastructure is flexible and can support various mechanisms for improving decentralization, fault-tolerance and trust. The signer itself can be an Externally Owned Account (EOA) or a smart contract. While an EOA is simpler to implement and more gas-efficient, it is more centralized and subject to the trust assumptions outlined above. Without any contract changes, one can transition to smart contract-based signers, which are compatible with off-chain batch auctions, decentralized validator sets, validity proofs, multi-signature schemes, and other mechanisms. This flexibility allows the backend to adapt and incorporate multiple decentralized solutions over time, ensuring fair price discovery and robust performance for LPs


# Liquidity Provider

### Functions

* **setPriceBounds:** Sets the AMM position's square-root upper and lower price bounds.
* **depositLiquidity:** Sovereign LM function to deposit reserves into the `pool`.
* **withdrawLiquidity:** Sovereign LM function to withdraw reserves from the `pool`.
* Implementation of specific functions in the liquidity provider contract.

### Security Model

1. The liquidity provider contract has complete control over depositing, withdrawing, and managing user funds in the HOT. The HOT assumes that all deposited funds belong to a single liquidity provider controlled by the `liquidityProvider` address. Individual LPs should ensure that this contract is well-audited, and cannot maliciously drain user funds.
2. As the Liquidity Provider is a critical role with complete control over user funds, it is set as an immutable address at the time of deployment.
3. The Liquidity Provider is expected to have a safe rebalance function, which can manually rebalance the pool in case the reserve composition gets too skewed into one of the tokens.
4. The Liquidity Provider can optionally have a short Timelock before calling the `setPriceBounds` function.

### Trust Assumptions

Except for the common trust assumptions around deposits and withdrawals, the liquidity provider should ensure that:

1. The price bounds are set appropriately so that the liquidity is concentrated to achieve the ideal balance between capital efficiency and the lowest possible inventory risk.
2. Highly concentrated liquidity can increase the losses from AMM swaps, as described in the [malicious signer attack vector](/amms-and-vaults/design-space/hot/risks-and-trust-assumptions/threats/malicious-signer-threat).
3. Liquidity Providers should implement a Timelock before calling the`setPriceBounds` function in the HOT. Without proper Timelocks, [malicious price-bound attacks ](/amms-and-vaults/design-space/hot/risks-and-trust-assumptions/threats/malicious-price-bound-threat)could become possible.
4. `setPriceBounds` is called with the proper checks so that attacks similar to the [Deposit Sandwich Attack](/amms-and-vaults/design-space/hot/risks-and-trust-assumptions/threats/deposit-sandwich-threat) are not possible. Simply setting the `_expectedSqrtSpotPriceLowerX96` and `_expectedSqrtSpotPriceUpperX96` correctly while making the call should be enough to prevent the attack.


# Threats




---

[Next Page](https://docs.valantis.xyz/llms-full.txt/1)

