# Introduction

Welcome to the official Adrena documentation. Adrena is a GMX-inspired perpetual trading venue built on Solana, featuring an equitable tokenomic foundation and fast on-chain trade execution.

## Quick Links

* [Vision](/about-adrena/vision) - Core tenets and philosophy
* [What is Adrena?](/about-adrena/about-adrena) - Platform overview
* [Tokenomics](/tokenomics/tokenomics-overview) - Governance & Liquidity Provision token details
* [Technical Documentation](/technical-documentation/oracles-and-price-feeds) - Deep-dive into protocol mechanics
* [Guides](/guides/how-to-open-and-close-a-trade) - Step-by-step tutorials


# Vision

Below are some core tenets of focus on what we feel will make this project successful in the long term.

## BE EQUITABLE

Be part of a platform that is profitable and is long-term aligned with its users, including a strong and equitable tokenomic foundation. A few focus points: Allocate as much of the revenue as possible to LPs and token holders. There should be direct incentive to hold the token beyond just speculation. No gimmicks, no points, just tokens. Rewards should be direct, and easy to understand, not shrouded by complexity. Have a linear, highly predictable emissions schedule for all. Everyone should be aligned for the long haul. Create a natural up-only environment driven by actual usage and scarcity. Reward early users and reward active users. All incentives should be driven to promote positive interactions with the protocol. Give users control over the project. Voting rights for all, more voting rights for long term believers.

## BE FAST AND EFFICIENT

Solana was chosen so trades can execute quickly and conveniently, backed by cutting edge infrastructure (like quality RPCs). Adrena prioritizes Tx handling with staked validators, optimised on-chain instructions, and the least amount of indirection/proxy possible. This means no "request fulfilment model" or delays that diminish the user experience and hinder composability.

## BE SIMPLE

Solana gives the ability to provide the best retail experience second to none. Be it for the UX/UI or for the codebase and Adrena was built keeping things simple and easy to use. When you want leverage, we want you to come to Adrena!

## BE COMPOSABLE AND WIDELY INTEGRATED

While there is an obligation to ensure alignment and quality > quantity, the goal should be a thriving ecosystem which Adrena is a part of. Thus Adrena could be integrated with as many projects in the community as possible. Adrena will have a strong grants opportunity that will power this system. Advanced features or integrations from external contributors are open to integration/inclusion/collaboration and anyone with ideas or efforts is encouraged to create a ticket in discord for progression.

## BE RESILIENT

A good platform should be built on trust. In our world that means trust in code. Consistent audits -when changes occur- are imperatively necessary.

## BE TRANSPARENT

Token holders have a vested long-term interest in the protocol. While the core team and early contributors have majority of decision-power in early days to ensure quick iteration, ADX emissions will slowly overtake these initial guard rails through platform usage, and the majority of tokens will be in the hands of the community. All vests, and governance power, is handled at the smart contract level: no bamboozle, full transparency (see Governance for more details).


# What is Adrena?

Adrena is a perpetual futures trading platform built on Solana. It uses an asset-backed (peer-to-pool) model inspired by GMX, enabling zero-slippage trades at oracle prices without an order book.

Key features:

* **Peer-to-Pool model** - Liquidity Providers (ALP and RWALP holders) act as the counterparty to traders
* **Fast execution** - Single-transaction trades with no keeper delay
* **Equitable tokenomics** - Revenue majority distributed to LPs and token holders

## Sections

* [Peer-to-Pool Perp Model](/about-adrena/about-adrena/peer-to-pool-perp-model)
* [Trading Competitions](/about-adrena/about-adrena/trading-competitions)
* [RPC and Trade Execution](/about-adrena/about-adrena/rpc-and-trade-execution)


# Peer-to-Pool Perp Model

Adrena uses an Asset Backed (or peer-to-pool) Perp Model (similar to what GMX introduced). This system removes a lot of risks usually present in order-book based Perp DEXs. One can think of this model as a PvE model rather than the usual PvP model, enabled by Liquidity Providers (ALP and RWALP holders) that provide liquidity to traders to leverage their trades.

## How It Works

In a typical order-book based Perp DEX, when a trader opens a position, the counterparty is another trader betting in the opposite direction. In the asset-backed model, traders' counterparty is themselves and the LP pool (depending on the direction of the trade).

### Long Trades

The user borrows long exposure of the asset based on their leverage from the Liquidity Pool (there is no actual borrowing - the trader locks assets in the pool to gain long exposure).

* **Trader is right** → Trader profits. The Liquidity Pool was deprived of the long exposure that goes to the trader instead. The pool does not lose capital, and accrues fees.
* **Trader is wrong** → Trader eventually gets liquidated on their initial collateral. The locked long exposure is released. The pool accrues fees.

### Short Trades

The user borrows stablecoins from the Liquidity Pool based on the platform's maximum profit (100%). Short positions have a limited upside - that's a limitation/security of this model.

* **Trader is right** → Trader profits. The Liquidity Pool pays out stablecoins to the trader but accrues fees.
* **Trader is wrong** → Trader eventually gets liquidated on their initial collateral. The locked short exposure is released. The pool accrues fees.

## Key Characteristics

* LP revenues originate from fees and trader losses - when a trader is liquidated or closes at a loss, their collateral accrues to the pool
* The model may not be as capital efficient as order-book, but oracle-based pricing makes it popular
* Limited by the size of the Liquidity Pool
* Pool Asset Ratios are an important parameter - maximizing volatile assets while controlling overall long exposure

## Risks for Liquidity Providers

As a Liquidity Provider (ALP and RWALP holder), you are partially exposed to trader PnL depending on trade direction. The pool's goal is to maximize fee revenue through high trading volume.


# Trading Competitions

Adrena runs periodic trading competitions for users. Check [adrena.trade/ranked](https://www.adrena.trade/ranked) for active competitions. More coming soon..


# RPC and Trade Execution

Adrena uses high-quality RPCs and staked validator connections for fast, reliable trade execution on Solana.


# Fees

Adrena charges fees in four categories:

| Fee Type                       | When Charged                             | Basis                                  |
| ------------------------------ | ---------------------------------------- | -------------------------------------- |
| **Close position**             | At trade exit                            | Flat % of position size at open        |
| **Borrow fee**                 | Ongoing while position is open           | Utilization-based (accrues per second) |
| **Virtual Funding Rate (VFR)** | Ongoing while position is open           | Hourly, OI-imbalance based             |
| **Swap / liquidity fee**       | Adding or removing ALP / RWALP liquidity | % of swap value                        |

***

## Close Fees

Close fees are a flat percentage of the **position size** (not collateral). Rates are set per asset on-chain and adjustable by governance.

**Main Pool**

| Asset | Close Fee (BPS) | Close Fee (%) |
| ----- | --------------- | ------------- |
| SOL   | 10              | 0.10%         |
| BTC   | 10              | 0.10%         |
| BONK  | 18              | 0.18%         |

**Commodities Pool**

| Asset | Close Fee (BPS) | Close Fee (%) |
| ----- | --------------- | ------------- |
| XAU   | 10              | 0.10%         |
| XAG   | 10              | 0.10%         |
| WTI   | 10              | 0.10%         |

## Borrow Fee (Two-Slope Model)

The borrow fee compensates liquidity providers for the pool assets locked against your position. It accrues continuously while the position is open and is settled at close.

Adrena uses a **two-slope borrow rate model** with a utilization kink:

* **Below optimal utilization**: Rate increases gradually from 0 to a midpoint rate - capital is available, so borrowing is cheap
* **Above optimal utilization**: Rate increases steeply from the midpoint to the maximum - scarcity of pool assets is reflected in cost

This makes borrowing cost efficient during normal conditions while strongly incentivizing position reduction when the pool is heavily utilized.

The optimal utilization level and rate bounds are configured per custody and adjustable by governance.

***

## Virtual Funding Rate

In addition to the borrow fee, positions accrue a **Virtual Funding Rate (VFR)** based on open interest imbalance between longs and shorts. The heavier side pays the lighter side hourly. This can partially offset the borrow fee for positions on the minority side.

See [Virtual Funding Rate](/technical-documentation/virtual-funding-rate) for details.

***

## Swap / Liquidity Fees

Fees apply when adding or removing liquidity through ALP / RWALP minting and redemption. Rates vary based on whether the swap moves the pool's asset ratios toward or away from their targets.

***

## Fee Distribution

All protocol fees are split across five buckets. Each bucket has its own BPS share; the split sums to 10,000 BPS (100%) per pool and is configurable per pool by governance.

**ALP**

| Bucket           | Recipient                                                    | Default BPS               |
| ---------------- | ------------------------------------------------------------ | ------------------------- |
| **LP fee**       | ALP holders (proportional to pool share)                     | 7,500 (75%)               |
| **Manager fee**  | Pool manager / creator (paid to a stable-mint token account) | 1,500 (15%)               |
| **Protocol fee** | Protocol treasury                                            | 5000 (5%)                 |
| **LM fee**       | Liquidity mining participants (ADX stakers)                  | 500 (5%)                  |
| **Referrer fee** | Active referrers                                             | 100 (see Referral System) |

**RW-ALP**

| Bucket           | Recipient                                                    | Default BPS               |
| ---------------- | ------------------------------------------------------------ | ------------------------- |
| **LP fee**       | RW-ALP holders (proportional to pool share)                  | 5,000 (50%)               |
| **Manager fee**  | Pool manager / creator (paid to a stable-mint token account) | 4,000 (40%)               |
| **Protocol fee** | Protocol treasury                                            | 5000 (5%)                 |
| **LM fee**       | Liquidity mining participants (ADX stakers)                  | 500 (5%)                  |
| **Referrer fee** | Active referrers                                             | 100 (see Referral System) |

Each bucket accrues independently on the pool state (`lp_fee_debt_usd`, `manager_fee_debt_usd`, `protocol_fee_debt_usd`, `lm_fee_debt_usd`, `referrers_fee_debt_usd`) and is distributed by the on-chain `distribute_fees` instruction. This five-bucket model replaced the single unified fee bucket used prior to Release 39.


# Achievements

More coming soon..


# Mutagen (Points System)

Mutagen is a dynamic and elusive resource that powers your progress on Adrena. It's designed to reward overall engagement and is distributed and scored off-chain, based on on-chain activity.

Mutagen points are coming again very soon!


# Referral System

Referrers can earn 100 bps of trading fees when their audience trades via their referral link.

Referrers are encouraged to create a ticket in discord to avail of a referral link.

Referral campaigns can also incur a rebate on fees for traders (refer-ees).


# Audits

Intrinsic risk in any Defi protocol and not to be underestimated - Adrena has ongoing Audits for any code update before deployment and has been successfully trading for over one year. V2 has been audited by Fidesium (February 2026) and Offside Labs (September 2025) and V1 has been audited by Ottersec (July 2024) and Offside Labs (December 2024).


# Useful Links

* **App**: <https://adrena.trade>
* **Docs**: See Github
* **GitHub**: <https://github.com/AdrenaFoundation>
* **Twitter/X**: <https://twitter.com/adrenaprotocol>
* **Discord**: <https://discord.gg/adrena>


# Governance

The Governance Shadow Token mechanism ensures that locked/vesting tokens still provide voting power, enabling the team and early contributors to guide the protocol during the early phases while remaining fully transparent and on-chain.

Realms is the upgrade authority for the smart contract. All administration functions and program upgrades require a majority DAO vote through Realms. All these actions have a 3 day timelock unless a quorum of 70% is reached. Execution is performed by the Realms PDA itself. The core team initiates it once majority vote and quorum is passed.


# Tokenomics Overview

Adrena has two core types of tokens:

1/ The governance and revenue-sharing token, **ADX**

2/ and the liquidity provider token (collateral backing trader positions),

* **ALP** - for the crypto pool
* **RWALP** - for the RWA pool

See Staking Details for distribution to ADX stakers and ALP holders.


# ADX

ADX is the core governance and utility token of Adrena.

Key properties:

* **Revenue sharing** - Stakers receive a share of all platform fees in USDC
* **Governance** - Voting rights for protocol decisions (more rights for long-term stakers)
* **Linear emissions** - Predictable, cliff-free emissions schedule for all participants (team, investors, community)
* **Vesting** - Team and investor tokens are locked but provide voting power

> ⚠️ Full ADX details (supply, emissions schedule, staking parameters) to be populated. Run the local scraper script for complete content.


# LP Tokens

ALP & RW-ALP are the platform collateral liquidity provider tokens - for the GMX-style Pool and for the Autonom Pool respectively. ALP & RW-ALP holders act as the counterparty to traders on Adrena.

By holding ALP & RW-ALP, you:

Provide liquidity for traders to open leveraged positions Earn a share of all trading fees (open, close, borrow) Are exposed to trader PnL (partially, depending on trade direction) For a deeper explanation of how the pool interacts with trader positions, see [Peer-to-Pool Perp Model](/about-adrena/about-adrena/peer-to-pool-perp-model).

***

## LP Sandwich Attack Mitigation

To prevent atomic mint-then-redeem attacks (where a bad actor adds liquidity and immediately removes it to extract value), Adrena enforces a time-based guard: **liquidity cannot be removed in the same slot that it was added**. The pool records the timestamp of the last deposit and rejects removal requests that arrive before it.


# Oracles and Price Feeds

Adrena uses oracle price feeds to determine trade execution prices. All trades execute at oracle price with zero slippage.

***

## Multi-Provider Oracle System

As of Release 39, Adrena sources prices from **multiple independent oracle providers**. Each provider covers a distinct feed ID range:

| Provider        | Feed ID Range | Mechanism                                                       |
| --------------- | ------------- | --------------------------------------------------------------- |
| **ChaosLabs**   | 0 - 29        | Off-chain signed batch prices (secp256k1)                       |
| **Autonom**     | 30 - 141      | Off-chain signed batch prices (secp256k1) + market session data |
| **Switchboard** | 142 - 255     | On-chain quote account verification (ed25519 precompile)        |

Switchboard prices are verified entirely on-chain via the ed25519 precompile. ChaosLabs and Autonom deliver signed price batches that are secp256k1-recovered and validated on-chain before use.

***

## Multi-Oracle Consensus

A `MultiOracleConfig` is attached to each pool, controlling how prices from multiple providers are reconciled:

| Parameter                  | Description                                                      |
| -------------------------- | ---------------------------------------------------------------- |
| `min_agree`                | Minimum number of providers that must agree on a price (1-3)     |
| `price_diff_threshold_bps` | Maximum allowed price deviation between providers (100 BPS = 1%) |
| `staleness_seconds`        | Maximum age of an accepted price (default: 7 seconds)            |

### Default configurations

Both pool types ship with the same baseline multi-oracle config. Governance can tune these post-migration via `set_pool_oracle_config`.

**Standard (GMX style) Pools** - crypto assets:

* Providers order: Autonom → Switchboard → ChaosLabs
* `min_agree`: 1
* `price_diff_threshold_bps`: 100
* `staleness_seconds`: 7
* `asymmetric_liquidation`: disabled
* `circuit_breaker_enabled`: disabled

**Autonom Pools** - RWA/synthetic assets:

* Providers order: Autonom → Switchboard → ChaosLabs
* `min_agree`: 1
* `price_diff_threshold_bps`: 100
* `staleness_seconds`: 7
* `asymmetric_liquidation`: disabled
* `circuit_breaker_enabled`: disabled

***

## Conservative Pricing

To protect the liquidity pool against adverse price selection:

* **Long positions** are priced using the oracle's **lower bound** - the worst case for a long entry/exit
* **Short positions** are priced using the oracle's **upper bound** - the worst case for a short entry/exit

This means traders always transact at the conservative end of the oracle's confidence interval, reducing the pool's exposure to oracle manipulation.

***

## Price Staleness and Timestamp Validation

* Prices older than `staleness_seconds` (7s default) are rejected
* Prices with a timestamp more than **2 seconds in the future** are also rejected (prevents pre-dated manipulation)
* The staleness window is intentionally set to 7 seconds to accommodate legitimate on-chain latency while maintaining a tight replay-attack surface

***

## Switchboard On-Chain Verification

Switchboard prices undergo full on-chain validation:

* Queue matching (feed must be registered to the expected queue)
* Quote account freshness check
* Data format validation

This requires Switchboard quote accounts to be passed as remaining accounts in relevant instructions.

***

## Liquidation Safety Mechanisms

### Asymmetric Liquidation Defense

For pools that temporarily fall back to a single oracle provider, **asymmetric liquidation** is available. When enabled, a liquidation can only proceed if a backup oracle has also provided a recent, confirming price for that asset. This prevents liquidations being triggered by a single stale or manipulated feed.

### Circuit Breaker

When enabled, the circuit breaker **pauses all liquidations** if no backup oracle has delivered a fresh price within the configured window (default: 300 seconds). This is a safety valve for infrastructure outages - protecting traders from being liquidated on stale prices when oracle redundancy is temporarily unavailable.

| Parameter                 | Description                                         |
| ------------------------- | --------------------------------------------------- |
| `asymmetric_liquidation`  | Enable/disable asymmetric liquidation defense (0/1) |
| `circuit_breaker_enabled` | Enable/disable the circuit breaker (0/1)            |
| `circuit_breaker_seconds` | Freshness window for the backup oracle (seconds)    |

Both defenses are **disabled by default** on both pool types; governance can enable them per pool via `set_pool_oracle_config` once the operator is comfortable with oracle coverage.

***

## Oracle Capacity

The oracle account supports up to **50 simultaneous price slots** (expanded from 20 in Release 39 via `migrate_oracle_v38_to_v39`). This accommodates the full range of assets across crypto (ChaosLabs/Autonom/Switchboard) and RWA/synthetic (Autonom/Switchboard) markets.


# Asset Mix and Weights

## Why This Matters

Every ALP token is backed by a basket of underlying assets in defined proportions. Two questions determine the LP experience: **what's in the basket** and **in what proportions**. Both are decisions the protocol makes on behalf of LPs, and both should be made by discipline rather than discretion.

This page documents the methodology that produces the target weights, the bands within which the pool operates, and the mechanism that keeps weights in line with target.

## The Four Principles

The target weights derive from four principles applied jointly.

**1. Volatility-weighted allocation.** Among the volatile assets, weight is inversely proportional to volatility relative to the lowest-volatility asset (BTC). More volatile assets receive smaller weights so that no single asset's price swings dominate the LP token's NAV.

* SOL is 1.5-1.7x BTC volatility → strict weighting puts SOL at \~60-70% of BTC weight
* BONK is 1.7-2.8x BTC volatility → strict weighting puts BONK at \~35-60% of BTC weight

**2. SOL-dominance compromise.** Pure volatility weighting would produce a BTC-dominant pool, but ALP is positioned as a Solana-ecosystem product. The deliberate compromise is to overweight SOL relative to its volatility-implied weight, accepting moderate additional NAV volatility for product coherence.

**3. USDC anchor at 30%.** USDC presence in the pool serves three purposes: it enables short positions, it reduces overall pool volatility through diversification, and it provides the redemption-friendly asset for LP exits. 30% is the lower bound that keeps the pool feeling balanced without diluting fee-generating capacity from volatile assets.

**4. Correlation as secondary filter.** When evaluating new additions or rebalances, correlation to existing assets is a tiebreaker, not a gate. In crypto, baseline correlations are high in absolute terms; the framework looks for relative differences.

## Target Weights and Bands

| Asset | Target | Min | Max |
| ----- | ------ | --- | --- |
| USDC  | 30%    | 25% | 40% |
| SOL   | 35%    | 28% | 42% |
| BTC   | 25%    | 20% | 30% |
| BONK  | 10%    | 7%  | 15% |

The Min/Max bands define the operating perimeter. Within the band the protocol does not intervene - mint and redeem fees naturally incentivize arbitrage back toward target. Sustained breaches (>14 days outside band) trigger a governance review of whether the target itself should adjust.

Band widths are asymmetric per asset:

* **USDC** has a wider upper band because in stress events traders close positions and the pool naturally accumulates USDC; defending a tight cap there would be counterproductive.
* **BONK** has the widest relative band because its volatility makes weight maintenance costly; tighter bands would generate excessive rebalancing trades.

## Volatility Window

All volatility computations - both initial weight derivation and future rebalancing decisions - use a **90-day rolling window**. Shorter windows are too sensitive to single events; longer windows lag market regime changes and produce stale weights.

## Dynamic Mint and Redeem Fees

The pool migrates toward target weights through a fee mechanism rather than protocol-side swaps.

* When an asset is **below** target, its mint fee is **lower** (incentive to deposit) and its redeem fee is **higher** (disincentive to withdraw)
* When an asset is **above** target, its mint fee is **higher** and its redeem fee is **lower**

The primary tool during the relaunch period is **zero mint fee on under-weighted assets**, channeling new deposits toward whichever assets the pool needs. The team monitors weights against bands and adjusts fee parameters via governance as conditions evolve.

If natural flow does not converge the pool toward target within a reasonable window, a manual rebalance via Jupiter Swap can be executed as a fallback.

## Review Cadence

* Target weights reviewed **quarterly** via governance proposal
* Bands reviewed **annually** unless breached
* Volatility data refreshed at every quarterly review

## Parameter Summary

| Parameter                      | Value                      |
| ------------------------------ | -------------------------- |
| Volatility window              | 90 days rolling            |
| Band breach review trigger     | >14 days outside band      |
| Target review cadence          | Quarterly                  |
| Band review cadence            | Annual (unless breached)   |
| Primary rebalancing mechanism  | Dynamic mint/redeem fees   |
| Fallback rebalancing mechanism | Manual swap via governance |


# Custody Addition Framework

## Why a Framework

ALP's custody slots are a finite resource. The pool can hold up to 8 custodies; 4 are currently used (USDC, SOL, BTC, BONK). Adding a new tradable asset is a real product lever - more custodies means more trader pairs and more potential volume - but each addition also dilutes existing weights, changes the LP token's volatility profile, and consumes a slot that's hard to free up.

This page sets out the rules for when an addition is justified, what weight a new asset should receive, and how the pool migrates to accommodate it.

## Addition Justification Test

A custody addition is considered when both of the following are met.

**Volume test.** The candidate has demonstrated trader demand on comparable platforms, measured as the candidate's trading volume as a percentage of the most-traded asset on that platform. A reading of **15-25% or more** of the leader's volume is a meaningful signal that the asset commands real trader interest in relative terms. Below 15%, the addition risks being a vanity slot - present but undertraded.

**Reserve sufficiency test.** The pool's current TVL must produce a custody reserve large enough to support typical trade sizes for that specific asset on comparable platforms. The check is asset-specific: a long-tail asset with smaller typical trade sizes needs a meaningfully smaller reserve than a major asset where trades routinely run into hundreds of thousands.

There is no fixed minimum TVL gate. As an indicative reference, a custody reserve of around $100k can support meaningful trading for less liquid assets; major assets typically require several hundred thousand or more. The protocol verifies sufficiency on a case-by-case basis by comparing the implied reserve (current TVL × proposed weight) against typical and high-percentile trade sizes observed on comparable platforms.

**Correlation as tiebreaker.** When multiple candidates pass the volume and reserve tests, preference goes to assets that bring lower correlation to the existing basket. In crypto, baseline correlations are high in absolute terms - the framework uses correlation as a relative preference among qualifying candidates, not as a hard gate.

## Weight Determination

A new asset's target weight is determined by:

1. Compute the asset's volatility relative to BTC over the 90-day window
2. Apply the volatility-weighting principle (see [Asset Mix and Weights](/technical-documentation/asset-mix-and-weights))
3. Cap the new weight at **12.5%** initially, regardless of what volatility-weighting suggests, to limit risk during the asset's first integration period
4. After 90 days of operation, the cap is removed and the asset can rebalance to its volatility-implied weight if justified

## Rebalancing Path

Adding an asset means reducing existing weights. The protocol does not dump existing assets to fund the new custody.

1. The new asset's initial target weight is determined per the rules above
2. Existing volatile assets reduce pro-rata to make room - USDC anchor remains at 30%, the volatile basket goes from 70% to (70% - new\_weight)%
3. Market mint/redeem flow migrates the pool composition over a 30-day window, with mint and redeem fees adjusted to incentivize correct flow (same dynamic fee mechanism as standard rebalancing)
4. Protocol-driven swaps are reserved as a fallback if the 30-day market-driven path fails to converge

## Worked Example

A hypothetical addition of a 5% custody at a point when ALP TVL is $2M. This sizing reflects an asset where typical trades are smaller than for the existing basket - the 5% allocation produces a $100k reserve, sufficient for that asset's trade-size profile.

| Asset     | Pre-Addition Weight | Post-Addition Weight | Pre-Addition $ | Post-Addition $ |
| --------- | ------------------- | -------------------- | -------------- | --------------- |
| USDC      | 30%                 | 30%                  | $0.60M         | $0.60M          |
| SOL       | 35%                 | 32.5%                | $0.70M         | $0.65M          |
| BTC       | 25%                 | 23.2%                | $0.50M         | $0.46M          |
| BONK      | 10%                 | 9.3%                 | $0.20M         | $0.19M          |
| New asset | -                   | 5%                   | -              | $0.10M          |

Existing volatile assets reduce pro-rata at \~7% relative reduction each. The actual weight for any candidate would be computed against current 90-day volatility data and reserve sufficiency at the time of evaluation, capped at the 12.5% initial-period limit.

## Parameter Summary

| Parameter                    | Value                                                              |
| ---------------------------- | ------------------------------------------------------------------ |
| Maximum custodies            | 8                                                                  |
| Current custodies            | 4 (USDC, SOL, BTC, BONK)                                           |
| Volume test threshold        | 15-25% of platform leader's volume                                 |
| Reserve sufficiency          | Case-by-case; sized to typical trade sizes on comparable platforms |
| Initial weight cap           | 12.5%                                                              |
| Initial period (cap applies) | 90 days                                                            |
| Rebalancing window           | 30 days market-driven, swap fallback                               |


# TVL Management

## Why TVL is Managed

LP returns are mechanically a function of fees divided by capital deployed. When TVL grows faster than trading volume, every LP earns a smaller share of the same fee stream - the pool dilutes its own yield.

ALP operates with a **soft cap on TVL that grows in step with realized fees**. The protocol commits to a target LP yield band, and the cap is adjusted upward - only on rule, only when justified - such that yield stays inside that band.

This is not a yield guarantee. Fees can fall and APY can dip. What the framework guarantees is that the protocol won't make things worse by allowing fresh capital to dilute already-stressed yields, and won't squander high-fee periods by leaving capacity frozen.

## Reference APY

Every TVL decision anchors to a single, publicly computable metric.

```
                   (F_W × 365/W × 0.75) - TraderPnL_W - ULP_W
Reference APY  =  ────────────────────────────────────────────
                                  TVL_W avg
```

* **F\_W** - total fees over the trailing window (W = 30 or 15 days)
* **0.75** - LP share of protocol revenue
* **TraderPnL\_W** - net trader P\&L impact on the pool (positive = pool drag)
* **ULP\_W** - Assets Unlocked Performance, the impact of price moves on assets not currently locked in trader positions
* **TVL\_W avg** - time-weighted average TVL over the window

The formula captures realized LP return, not headline fee yield. A pool can generate strong fees while losing capital to trader PnL or market drift on unutilized assets - Reference APY accounts for both.

The metric is computable from on-chain data, so any LP can verify the protocol's reported number.

## Operating Bands

| Band            | APY       | Action                                       |
| --------------- | --------- | -------------------------------------------- |
| 🟦 Critical     | < 5%      | Pause new minting                            |
| 🟨 Below-Target | 5% - 25%  | No protocol action                           |
| 🟢 Green        | 25% - 35% | Normal operation; lifts considered above 30% |
| 🟥 Blue         | > 35%     | Lift cap per formula                         |

Green is the design target. There is no mechanism for protocol-driven TVL reduction - at 20% APY the pool is still productive, and forcing capacity contraction would signal unwarranted distress. The mint pause trigger sits at <5%, the level at which the pool is genuinely unviable.

## Cap Lift Formula

```
                                                    F_run-rate
New Cap  =  min (  Current Cap × 1.30  ,  ─────────────────────  )
                                                    APY_target
```

Where **F\_run-rate** : annualized fee run rate net of trader PnL and ULP drag, after the 75% LP share (USD per year); computed as (F\_30 × 365/30 × 0.75) - TraderPnL\_30 - ULP\_30, **APY\_target = 27%** (Green band midpoint, buffered against downside drift).

Two triggers:

* **Standard** - first Monday of each month. Trailing 30-day Reference APY above 30% across two consecutive reviews.
* **Expedited** - 15-day trailing Reference APY above 35%. Upward only.

The expedited path exists because fee growth can outpace a monthly window, especially at relaunch.

## Why +30% Per Lift

The step-size cap is the most important parameter for LP experience.

| Pre-lift APY | Post-lift APY (constant fees, +30% TVL) |
| ------------ | --------------------------------------- |
| 30%          | 23.1%                                   |
| 35%          | 26.9%                                   |
| 40%          | 30.8%                                   |

A lift from 35% lands at 27% - the middle of Green. A larger step (e.g., +50%) would land that same pre-lift reading at 23%, a meaningful negative LP experience. +30% is the constraint that prevents this.

## Notice and Transparency

* Cap adjustments announced at least 7 days before taking effect
* Current TVL, cap, trailing Reference APY, and band are displayed on the ALP page
* A historical log of every cap adjustment is maintained
* Parameter changes require a governance proposal with at least 14 days' notice

## Parameter Summary

| Parameter                | Value                                   |
| ------------------------ | --------------------------------------- |
| LP fee share             | 75%                                     |
| Target band              | 25% - 35% APY                           |
| Lift trigger (standard)  | > 30% for 2 consecutive reviews         |
| Lift trigger (expedited) | 15-day > 35%                            |
| Max lift per adjustment  | +30%                                    |
| Post-lift APY target     | 27%                                     |
| Reference window         | 30 days (standard), 15 days (expedited) |
| Review cadence           | Monthly, first Monday                   |
| Mint pause trigger       | < 5%                                    |
| Notice period            | 7 days                                  |


# Autonom Pools (RWA & Synthetic Assets)

## Overview

Autonom Pools are a new pool type in Adrena that enables trading on **real-world assets (RWA)** and **synthetic instruments** - such as equities, commodities, and indices - directly on Solana. Unlike standard GMX-style pools, Autonom pools hold no on-chain token reserves for the traded assets. Instead, positions are entirely USD-denominated and settled against stable collateral.

***

## Differences from Standard (GMX) Pools

| Feature                            | GMX Pool                              | Autonom Pool                               |
| ---------------------------------- | ------------------------------------- | ------------------------------------------ |
| Assets                             | Native crypto tokens (SOL, BTC, ETH…) | Synthetic: equities, commodities, RWA      |
| Custody                            | Holds actual tokens                   | No token custody - synthetic PDA only      |
| Collateral                         | Token or stablecoin                   | Stablecoin only                            |
| Oracle providers (default)         | Autonom → Switchboard → ChaosLabs     | Autonom → Switchboard → ChaosLabs          |
| Multi-oracle `min_agree` (default) | 1                                     | 1                                          |
| Market hours                       | 24/7                                  | Subject to underlying market trading hours |
| Position settlement                | In underlying token                   | USD-denominated                            |

Both pool types ship with identical default `MultiOracleConfig` (Autonom primary, `min_agree=1`, `staleness_seconds=7`). Governance can tune each pool's provider order, min\_agree, and liquidation defenses independently via `set_pool_oracle_config`.

***

## Synthetic Custodies

Each tradable asset in an Autonom Pool is represented by a **synthetic custody** - an on-chain account that records the aggregate open interest and fee state for that asset, but holds no tokens. Key properties:

* Identified by a unique seed (not a token mint), allowing multiple synthetic assets per pool (up to 32)
* Tracks `cumulative_funding_paid_usd` and `cumulative_funding_received_usd` for [Virtual Funding Rate](/technical-documentation/virtual-funding-rate) accounting
* Uses a dedicated `oracle_feed_id` and `trade_oracle_feed_id` for price lookups

***

## Market Hours

Autonom Pool assets correspond to real-world instruments that only trade during certain hours (e.g., US equity market hours, 9:30 AM-4:00 PM ET on weekdays). The protocol enforces this:

* **`market_open_timestamp`** / **`market_close_timestamp`**: Define the active trading window for the pool
* **Opening a position** outside market hours returns a `MarketIsClosed` error
* **Existing positions** remain open through market close - they settle at next open or at the holder's discretion

***

## Market Special Events

Corporate actions such as **stock splits** and **dividends** can affect the fair value of a synthetic position. When such an event is scheduled:

* Affected feed IDs are recorded in `market_close_affected_feeds`
* The event timestamp is stored in `market_close_event_timestamp`
* Attempts to open new positions in affected assets will return a `MarketStockSpecialEvent` error until the event is processed
* Existing positions in affected assets are handled according to the protocol's event resolution procedure

***

## Oracle Configuration

Autonom Pools use the **Autonom oracle** as the primary price provider. This is an off-chain price feed that delivers signed batch prices (including market session data) on-chain.

Default multi-oracle config for Autonom Pools:

| Parameter                  | Value                          |
| -------------------------- | ------------------------------ |
| Primary provider           | Autonom                        |
| Backup providers           | Switchboard, ChaosLabs         |
| `min_agree`                | 1 (single provider sufficient) |
| `price_diff_threshold_bps` | 100 (1% tolerance)             |
| `staleness_seconds`        | 7                              |
| Asymmetric liquidation     | Disabled                       |
| Circuit breaker            | Disabled                       |

Because Autonom assets may not have broad multi-oracle coverage, a single-oracle consensus threshold is appropriate. The asymmetric liquidation and circuit breaker defenses used in GMX pools are therefore not enabled for Autonom Pools.

See [Oracles and Price Feeds](/technical-documentation/oracles-and-price-feeds) for the full oracle architecture.

***

## Liquidations

Liquidation mechanics for Autonom Pool positions follow the same margin rules as standard positions, with one addition: positions cannot be liquidated outside of market hours (since no reliable price is available). Liquidation resumes at market open.

***

## Collateral

All Autonom Pool positions use stablecoin collateral (USDC or equivalent). There is no token exposure on the collateral side - your profit/loss and collateral are both denominated in USD.


# Virtual Funding Rate

## Background

In a peer-to-pool perpetual model, open interest (OI) between longs and shorts is rarely balanced. When longs significantly outweigh shorts (or vice versa), the liquidity pool bears disproportionate directional risk. The **Virtual Funding Rate (VFR)** is a periodic payment mechanism that redistributes this imbalance cost directly between the two sides, keeping the pool's net exposure manageable over time.

This is analogous to the funding rate on centralized exchanges, but applied within Adrena's on-chain peer-to-pool architecture.

***

## How VFR Works

Funding flows from the heavier side to the lighter side every hour:

* If **longs > shorts**: long positions pay short positions
* If **shorts > longs**: short positions pay long positions

The rate scales with the imbalance - the more skewed OI is, the higher the funding obligation. Funding is **accrued continuously** and **settled at position close**, meaning it accumulates in the position's tracked state and is applied when the position is closed.

***

## Rate Calculation

The hourly funding rate is determined by OI imbalance and a configurable sensitivity:

1. **OI Imbalance** = |long OI - short OI| / total OI, expressed in BPS
2. **Scaled Imbalance** = imbalance × imbalance\_sensitivity\_bps / 10,000
3. **Funding Rate** = max\_hourly\_funding\_rate × scaled\_imbalance / 10,000
4. Rate is capped at `max_hourly_funding_rate`

The `min_total_oi_usd` threshold must be exceeded for VFR to activate - this prevents the rate from firing on negligible open interest.

### Parameters (per custody)

| Parameter                   | Description                                                            |
| --------------------------- | ---------------------------------------------------------------------- |
| `max_hourly_funding_rate`   | Hard cap on the hourly funding rate                                    |
| `min_total_oi_usd`          | Minimum total OI required to activate funding                          |
| `imbalance_sensitivity_bps` | Multiplier controlling how aggressively the rate responds to imbalance |

These are configured per-custody and can be adjusted by governance.

***

## Impact on Positions

Funding is tracked cumulatively at both the **custody level** (global index) and the **position level** (entry index). At position close:

* The difference between the current global index and the position's entry index is applied
* Net funding is either deducted from or added to the position's realized PnL
* Traders on the heavier side pay; traders on the lighter side receive

This means:

* **Paying side**: effective cost increases over time for holding a position on the crowded side
* **Receiving side**: positions on the minority side earn a passive income component on top of any trading PnL

***

## Comparison to Traditional Funding Rates

| Aspect               | CEX Funding Rate            | Adrena VFR                               |
| -------------------- | --------------------------- | ---------------------------------------- |
| Settlement frequency | Every 8 hours (typically)   | Continuous accrual, settled at close     |
| Counterparty         | Other traders               | LP pool acts as intermediary distributor |
| Transparency         | Published oracle            | On-chain, per-custody state              |
| Rate mechanism       | Index-mark price divergence | OI imbalance sensitivity                 |

***

## Relationship to Borrow Fees

VFR operates independently from the borrow fee. Both accrue while a position is open:

* **Borrow fee**: paid by all positions to compensate liquidity providers for locking pool assets (see [Fees](/about-adrena/fees))
* **VFR**: net transfer between longs and shorts based on OI imbalance - can partially offset borrow costs for positions on the minority side

See [Position Parameters](/technical-documentation/position-parameters) for how both fees interact with a position's overall cost.


# "Toxic Flow" Countermeasures

## Background

GMX-inspired perp venues have liquidity fuelled by passive liquidity providers, and trades execute at 0 slippage based on oracle price. In this context, informed traders can extract value from the platform (see the Avax manipulation incident on GMX Arbitrum). On a traditional order book based venue, this would not be possible, as the cost of liquidity would be impacted.

## How Other Platforms Handle It

* **GMX**: Splits trades into 2 transactions, introducing latency. This acts as a delay-based protection but harms UX significantly.
* **Jupiter Perps**: Uses a keeper model - receives trade intents and funds, then eventually submits trades. Heavy UX during high volatility (comparable to 4 seconds of latency).

## Adrena's Approach

Since inception, Adrena's ethos is to keep it simple and fair, and to provide a user experience on par with what Solana offers in terms of TX settlement speed. **Adrena does not use a keeper.** This allows for:

* Super snappy single-transaction trade execution
* Transparent, straight on-chain experience
* No detours or proxy hops

## Monitoring

Adrena monitors `markout_1m`, `5m`, and `10m` to see the PnL of trades 1/5/10 minutes after opening, allowing the team to identify and respond to toxic flow patterns.

***

See [Fees](/about-adrena/fees) for the full breakdown.


# Position Parameters

This page describes the parameters and mechanics that govern how positions are opened, maintained, and closed on Adrena.

***

## Leverage and Position Size

* Maximum leverage and minimum/maximum position size are set per asset
* A **maximum cumulative long position size** cap exists per custody, limiting the total long exposure the pool accepts in a single asset
* These limits protect the pool from excessive directional risk concentration

***

## Opening a Position

Trades execute at oracle price with zero slippage.

For positions in [Autonom Pools](/technical-documentation/autonom-pools) (RWA/synthetic assets), the position can only be opened during the asset's defined market hours.

***

## Ongoing Costs While a Position is Open

### 1. Borrow Fee

The borrow fee accrues continuously (per second) based on pool utilization. Adrena uses a **two-slope model**:

* Below the optimal utilization kink: low, gradually rising rate
* Above the optimal utilization kink: steep rate increase

This ensures cheap borrowing at normal utilization and reflects asset scarcity when the pool is heavily used. The optimal utilization level and rate bounds are set per custody.

### 2. Virtual Funding Rate (VFR)

Positions also accrue a [Virtual Funding Rate](/technical-documentation/virtual-funding-rate) based on the open interest imbalance between longs and shorts. The majority side pays the minority side at an hourly rate proportional to the imbalance. VFR is settled at position close.

***

## Closing a Position

A flat **close fee** (% of position size) applies at close.

### Open + Collateral Modification Locks

Two separate minimum-age gates apply before a position can be closed:

* **Minimum open time: 4 minutes** (`MIN_POSITION_OPEN_TIME_SECONDS = 240`). A freshly opened position cannot be closed in its first 4 minutes.
* **Minimum wait after collateral change: 2 minutes** (`MIN_POSITION_UPDATE_TIME_BEFORE_CLOSE_SECONDS = 120`). After adding or removing collateral, the position cannot be closed for 2 minutes.

Both gates prevent collateral manipulation to game the exit fee tiers.

***

## Liquidation

A position is liquidated when the remaining collateral falls to the liquidation margin threshold. Key properties:

* **Conservative pricing**: Liquidation prices use the oracle's conservative bound (low for longs, high for shorts)
* **Asymmetric liquidation defense** (GMX pools): Requires backup oracle confirmation before liquidating, preventing liquidations on single-oracle staleness
* **Autonom pool liquidations**: Cannot execute outside market hours (no reliable price available)

***

## Market Hours (Autonom Pools Only)

Positions in [Autonom Pools](/technical-documentation/autonom-pools) are subject to the trading hours of the underlying real-world asset. Opening a new position outside market hours returns a `MarketIsClosed` error.

***

## Fee Summary

| Fee                  | Timing     | Basis                         |
| -------------------- | ---------- | ----------------------------- |
| Borrow fee           | Continuous | Per-second, utilization-based |
| Virtual Funding Rate | Continuous | Hourly OI imbalance           |
| Close fee            | At exit    | Flat % of position size       |

See [Fees](/about-adrena/fees) for distribution details.


# Staking Implementation Details

Adrena is all about redistributing revenues as the core feature of the platform. A big chunk of that is done through ALP (pool's share) appreciation, as most of the fee revenues go back to the pool directly.

The exact distribution is as follow:

75% for ALP (liquid), shared with ALP Locked Stakers

50% for RW-ALP (liquid), shared with RW-ALP Locked Stakers

5% for ADX, shared with ADX Stakers (liquid and locked)

***

Adrena offers the possibility to Lock Stake, aligning with the protocol long term strategy. By doing so, users get amplified revenue share (at the detriment of non Locked Stakers on USDC yield, not for ADX bonuses).

Let's take the case of ALP for an example:

Starting conditions:

1000 ALP token circulating

800 un-Staked

100 Staked 180 days

100 Staked 360 days

\--

100$ of revenue is to be distributed this round to ALP.

800 ALP un-Staked <=> 800

100 ALP Staked 180 days <=> 100 \* 1.75 (175)

100 ALP Staked 360 days <=> 100 \* 2.50 (250)

\--

Total weight is 800 + 175 + 250 (1225)

\--

And so final distribution is

800/1225 \* 100$ -> $65.31 to the LP pool (all ALP appreciating)

175/1225 \* 100$ -> $14.28 going as bonus USDC yield to ALP 180 days Stakers

250/1225 \* 100$ -> $20.41 going as bonus USDC yield to ALP 360 days Stakers

***

Rewards accrue as time passes, and actions are carried on the platform. But the actual rewards are accumulated and distributed in rounds in order to batch operations together.


# TypeScript SDK

The Adrena TypeScript SDK provides a high-level interface for interacting with the Adrena Protocol on Solana - opening and closing perpetual positions, managing liquidity, staking tokens, and querying off-chain analytics.

Built on [@solana/kit](https://github.com/anza-xyz/kit) (Web3.js v2). All transactions are submitted via [Jito bundles](https://www.jito.network/) for MEV protection.

***

## Installation

```bash
# npm
npm install adrena-sdk@beta

# yarn
yarn add adrena-sdk@beta
```

***

## Configuration

All SDK functions require a `wallet` (transaction signer) and an `rpc` client. Use `createKitClient` to create both.

### Option 1 - `.env` file (recommended)

Create a `.env` file in your project root:

```env
PRIVATE_KEY_STR=<your-base58-private-key>
RPC_URL=https://your-rpc-url.com
WS_URL=wss://your-ws-url.com
```

> Never commit private keys. Add `.env` to your `.gitignore`.

Then in code:

```typescript
import { createKitClient } from 'adrena-sdk/clients';

const { wallet, rpc } = await createKitClient();
```

### Option 2 - Pass credentials directly

```typescript
import { createKitClient } from 'adrena-sdk/clients';

const { wallet, rpc } = await createKitClient({
  privateKey: 'your-base58-private-key',
  rpcUrl: 'https://your-rpc-url.com',
});
```

***

## Supported Assets

Adrena runs two separate on-chain pools. The SDK exposes both.

### Main Pool - Crypto Assets

| Symbol  | Role                   | Decimals |
| ------- | ---------------------- | -------- |
| JITOSOL | Principal / Collateral | 9        |
| WBTC    | Principal / Collateral | 8        |
| BONK    | Principal / Collateral | 5        |
| USDC    | Collateral / Liquidity | 6        |

**`PrincipalToken`** - the asset being traded: `"JITOSOL" | "WBTC" | "BONK"`

**`CollateralToken`** - the asset deposited as margin: `"USDC" | "JITOSOL" | "WBTC" | "BONK"`

> For **longs**, the collateral token must match the principal token (e.g. a JITOSOL long requires JITOSOL collateral). For **shorts**, the collateral token must always be `"USDC"`.

### Commodities Pool - Synthetic Assets

| Symbol | Name      | Decimals |
| ------ | --------- | -------- |
| XAU    | Gold      | 6        |
| XAG    | Silver    | 6        |
| WTI    | Crude Oil | 6        |

**`CommodityToken`** - `"XAU" | "XAG" | "WTI"`

Commodity positions are collateralised in USDC for both longs and shorts. There is no token swap - you deposit USDC and trade a price-feed-backed synthetic custody settled in USDC on close.

***

## Module Overview

The SDK is split into focused sub-packages. Import only what you need.

| Import path               | Purpose                                                |
| ------------------------- | ------------------------------------------------------ |
| `adrena-sdk/clients`      | Create the RPC + wallet client (`createKitClient`)     |
| `adrena-sdk/core`         | High-level trading, liquidity, and staking functions   |
| `adrena-sdk/instructions` | Low-level instruction builders for custom transactions |
| `adrena-sdk/helpers`      | PDAs, math, token accounts, transaction utilities      |
| `adrena-sdk/adrena-api`   | REST API client for off-chain data and analytics       |

***

## Sections

* [Trading](/sdk/sdk/trading)
* [Commodities](/sdk/sdk/commodities)
* [Liquidity & Swap](/sdk/sdk/liquidity-and-swap)
* [Staking](/sdk/sdk/staking)
* [Data API](/sdk/sdk/data-api)


# Trading

The SDK supports market orders, limit orders, and stop-loss / take-profit management for crypto perpetuals on the main pool. All functions return a `txSignature` and (where applicable) a `positionAddress`.

For synthetic commodity trading (XAU, XAG, WTI) see [Commodities](/sdk/sdk/commodities).

***

## Open a Long Position

For longs the `collateralToken` must match the `principalToken` - you deposit the asset you are trading.

```typescript
import { openMarketLong } from 'adrena-sdk/core';
import { createKitClient } from 'adrena-sdk/clients';

const { wallet, rpc } = await createKitClient();

const result = await openMarketLong({
  wallet,
  rpc,
  principalToken: 'JITOSOL',   // asset to trade
  collateralToken: 'JITOSOL',  // must match principal for longs
  collateralAmount: 10,         // human-readable units (10 JITOSOL)
  leverage: 3,                  // leverage multiplier
  stopLossPrice: 130,           // optional - trigger price in USD
  takeProfitPrice: 180,         // optional - trigger price in USD
});

console.log('tx:', result.txSignature);
console.log('position:', result.positionAddress);
```

***

## Open a Short Position

For shorts the `collateralToken` must be `"USDC"` regardless of which asset is being shorted.

```typescript
import { openMarketShort } from 'adrena-sdk/core';
import { createKitClient } from 'adrena-sdk/clients';

const { wallet, rpc } = await createKitClient();

const result = await openMarketShort({
  wallet,
  rpc,
  principalToken: 'JITOSOL',  // asset to short
  collateralToken: 'USDC',    // must be USDC for shorts
  collateralAmount: 50,        // 50 USDC
  leverage: 5,
  stopLossPrice: 175,          // optional - above entry price for shorts
  takeProfitPrice: 120,        // optional - below entry price for shorts
});
```

***

## Close a Long Position

Closes the existing long position for the given principal token. Defaults to the current oracle price.

```typescript
import { closeLong } from 'adrena-sdk/core';
import { createKitClient } from 'adrena-sdk/clients';

const { wallet, rpc } = await createKitClient();

const result = await closeLong({
  wallet,
  rpc,
  principalToken: 'JITOSOL',
  // price: 155.0,  // optional - override close price
});
```

***

## Close a Short Position

```typescript
import { closeShort } from 'adrena-sdk/core';
import { createKitClient } from 'adrena-sdk/clients';

const { wallet, rpc } = await createKitClient();

const result = await closeShort({
  wallet,
  rpc,
  principalToken: 'JITOSOL',
  collateralToken: 'USDC',
});
```

***

## Check Position Status

Fetch live P\&L, size, liquidation price, and other position metrics.

```typescript
import { getPositionStatus } from 'adrena-sdk/core';
import { createKitClient } from 'adrena-sdk/clients';
import {
  fetchPoolUtil,
  loadCustodies,
  getCustodyByMint,
  findPositionAddress,
  PRINCIPAL_ADDRESSES,
} from 'adrena-sdk/helpers';

const { wallet, rpc } = await createKitClient();

const principalToken = 'JITOSOL';
const side = 'long'; // or 'short'

// Derive the on-chain position address
const pool = await fetchPoolUtil('main-pool', undefined, rpc);
const custodies = await loadCustodies(pool.data, rpc);
const principalCustody = getCustodyByMint(
  custodies,
  PRINCIPAL_ADDRESSES[principalToken].address,
);

const positionAddress = (
  await findPositionAddress(pool.address, wallet.address, principalCustody!.address, side)
)[0];

const status = await getPositionStatus({ wallet, rpc, principalToken, positionAddress });

console.log(status);
// { pnl, sizeUsd, entryPrice, pythPrice, exitFee, totalInterest, liquidationPrice, ... }
```

### Returned fields

| Field           | Description                                  |
| --------------- | -------------------------------------------- |
| `entryPrice`    | Price at which the position was opened (USD) |
| `pythPrice`     | Current oracle price (USD)                   |
| `sizeUsd`       | Notional position size in USD                |
| `totalInterest` | Accumulated borrow interest owed             |
| `exitFee`       | Fee charged on close                         |
| `preFeePnl`     | P\&L before fees                             |
| `pnl`           | Net P\&L after fees                          |
| `openTime`      | Timestamp when the position was opened       |
| `updateTime`    | Timestamp of the most recent position update |

***

## Limit Orders

Place a conditional order that fills when the oracle price reaches a target level.

```typescript
import { addLimitOrder } from 'adrena-sdk/core';
import { createKitClient } from 'adrena-sdk/clients';

const { wallet, rpc } = await createKitClient();

const result = await addLimitOrder({
  wallet,
  rpc,
  principalToken: 'JITOSOL',
  collateralToken: 'JITOSOL', // matches principal for long; USDC for short
  collateralAmount: 0.5,
  leverage: 10,
  side: 'long',
  triggerPrice: 130,   // order fills when oracle price reaches this level
  limitPrice: null,    // null = market price at fill; set a value to cap fill price
});
```

***

## Cancel Stop Loss / Take Profit

Cancels an existing stop-loss and/or take-profit attached to an open position.

```typescript
import { cancelSLTP } from 'adrena-sdk/core';
import { createKitClient } from 'adrena-sdk/clients';

const { wallet, rpc } = await createKitClient();

const result = await cancelSLTP(
  wallet,
  rpc,
  'JITOSOL', // principalToken
  'long',    // side
  true,      // cancelStopLoss
  true,      // cancelTakeProfit
);
```

***

## Confirming Transactions

All core functions submit transactions via Jito bundles. Use `checkTransactionConfirmed` to poll for on-chain confirmation:

```typescript
import { checkTransactionConfirmed } from 'adrena-sdk/helpers';

const result = await openMarketLong({ ... });

const confirmed = await checkTransactionConfirmed(result.txSignature, rpc);
if (confirmed) {
  console.log('Position opened:', result.positionAddress);
} else {
  console.warn('Transaction did not confirm within timeout');
}
```

If the Jito tip endpoint is unreachable the SDK falls back to a standard RPC send automatically.


# Commodities

The SDK supports synthetic commodity perpetuals through the dedicated commodities pool - trade Gold (XAU), Silver (XAG), and Crude Oil (WTI) against price feeds sourced from Adrena's oracle system.

See [Oracles and Price Feeds](/technical-documentation/oracles-and-price-feeds) and [Autonom Pools](/technical-documentation/autonom-pools) for the underlying protocol mechanics.

***

## Key Differences from Crypto Trading

* **Collateral is always USDC** - for both longs and shorts, regardless of the commodity
* **`collateralAmount` is in native units** - multiply the human amount by `10^6` (USDC has 6 decimals)
* **Settlement in USDC** - closing a position always returns USDC
* **No token swap** - you deposit USDC and gain synthetic exposure to the price feed; no physical asset is involved

***

## Open a Commodity Long

Go long on a commodity price feed with USDC collateral.

```typescript
import { openCommodityLong } from 'adrena-sdk/core';
import { createKitClient } from 'adrena-sdk/clients';

const { wallet, rpc } = await createKitClient();

// Long Gold with 100 USDC at 5× leverage
const result = await openCommodityLong({
  wallet,
  rpc,
  commodityToken: 'XAU',
  collateralAmount: BigInt(100_000_000), // 100 USDC (6 decimals)
  leverage: 5,
  // price: 2_050,  // optional - override oracle price in USD
});

console.log('tx:', result.txSignature);
console.log('position:', result.positionAddress);
```

The same function handles both opening a new position and increasing an existing one.

***

## Open a Commodity Short

Short a commodity price feed with USDC collateral.

```typescript
import { openCommodityShort } from 'adrena-sdk/core';
import { createKitClient } from 'adrena-sdk/clients';

const { wallet, rpc } = await createKitClient();

// Short Gold with 100 USDC at 5× leverage
const result = await openCommodityShort({
  wallet,
  rpc,
  commodityToken: 'XAU',
  collateralAmount: BigInt(100_000_000), // 100 USDC (6 decimals)
  leverage: 5,
});
```

***

## Close a Commodity Long

Closes the open long position for the given commodity. USDC is returned to the wallet.

```typescript
import { closeCommodityLong } from 'adrena-sdk/core';
import { createKitClient } from 'adrena-sdk/clients';

const { wallet, rpc } = await createKitClient();

const result = await closeCommodityLong({
  wallet,
  rpc,
  commodityToken: 'XAU',
  // price: 2_100,  // optional - override oracle price
});
```

***

## Close a Commodity Short

```typescript
import { closeCommodityShort } from 'adrena-sdk/core';
import { createKitClient } from 'adrena-sdk/clients';

const { wallet, rpc } = await createKitClient();

const result = await closeCommodityShort({
  wallet,
  rpc,
  commodityToken: 'XAU',
});
```

***

## Supported Commodities

| Symbol | Asset     | Oracle feed ID |
| ------ | --------- | -------------- |
| XAU    | Gold      | 2056           |
| XAG    | Silver    | 2069           |
| WTI    | Crude Oil | 2035           |

All commodity feeds are sourced through the Autonom oracle provider. Prices execute at oracle price with zero slippage, consistent with the broader Adrena protocol.

***

## USDC Decimal Reference

Commodity functions accept `collateralAmount` as a `BigInt` in USDC native units (6 decimals).

| Human amount | Native units (`BigInt`) |
| ------------ | ----------------------- |
| 10 USDC      | `BigInt(10_000_000)`    |
| 100 USDC     | `BigInt(100_000_000)`   |
| 500 USDC     | `BigInt(500_000_000)`   |
| 1,000 USDC   | `BigInt(1_000_000_000)` |


# Liquidity & Swap

Liquidity providers deposit collateral into the ALP pool and receive ALP tokens representing their share. The pool earns trading fees distributed to ALP holders. The SDK also supports token swaps directly through the pool.

See [ALP](https://github.com/AdrenaFoundation/adrena-docs-v2/blob/main/tokenomics/alp/README.md) for tokenomics details.

***

## Add Liquidity (ALP)

Deposit a supported collateral token to receive ALP in return. Amounts are expressed in native token units.

```typescript
import { addLiquidity } from 'adrena-sdk/core';
import { createKitClient } from 'adrena-sdk/clients';

const { wallet, rpc } = await createKitClient();

const result = await addLiquidity({
  wallet,
  rpc,
  collateralToken: 'USDC',
  amountIn: BigInt(100_000_000),  // 100 USDC (6 decimals)
  minLpAmountOut: BigInt(0),      // minimum ALP to receive; set >0 for slippage protection
});
```

To deposit into the commodities pool instead of the main pool, pass `poolName: 'commodities-pool'`:

```typescript
await addLiquidity({
  wallet,
  rpc,
  collateralToken: 'USDC',
  amountIn: BigInt(100_000_000),
  minLpAmountOut: BigInt(0),
  poolName: 'commodities-pool',
});
```

***

## Remove Liquidity (ALP)

Burn ALP tokens to withdraw a collateral token from the pool.

```typescript
import { removeLiquidity } from 'adrena-sdk/core';
import { createKitClient } from 'adrena-sdk/clients';

const { wallet, rpc } = await createKitClient();

const result = await removeLiquidity({
  wallet,
  rpc,
  collateralToken: 'USDC',       // token to receive on exit
  lpAmountIn: BigInt(50_000_000), // ALP tokens to burn (6 decimals)
  minAmountOut: BigInt(0),        // minimum collateral to receive
});
```

***

## Swap

Swap between any two supported collateral tokens through the ALP pool.

```typescript
import { swap } from 'adrena-sdk/core';
import { createKitClient } from 'adrena-sdk/clients';

const { wallet, rpc } = await createKitClient();

const result = await swap({
  wallet,
  rpc,
  fromToken: 'USDC',
  toToken: 'JITOSOL',
  amountIn: BigInt(50_000_000),  // 50 USDC (6 decimals)
  minAmountOut: BigInt(0),       // set >0 for slippage protection
});
```

Swaps execute through the pool's internal price oracle - the same zero-slippage mechanism used for trades.

***

## Token Decimal Reference

Native unit amounts are required for liquidity and swap functions. Use the table below to convert human-readable amounts.

| Token   | Decimals | Formula                            |
| ------- | -------- | ---------------------------------- |
| USDC    | 6        | `amount * 10^6` (e.g. `100 * 1e6`) |
| ALP     | 6        | `amount * 10^6`                    |
| JITOSOL | 9        | `amount * 10^9`                    |
| WBTC    | 8        | `amount * 10^8`                    |
| BONK    | 5        | `amount * 10^5`                    |

***

## Slippage Protection

Set `minLpAmountOut` / `minAmountOut` to a non-zero value to reject the transaction if the pool price moves adversely between submission and execution.

A value of `BigInt(0)` disables the check - acceptable for testing but not recommended in production.


# Staking

ADX and ALP tokens can both be staked to earn protocol fee distributions in USDC plus ADX emissions. The SDK supports liquid staking (no lock-up) and locked staking (fixed duration with boosted rewards).

See [Staking Implementation Details](/technical-documentation/staking-implementation-details) for protocol-level mechanics.

***

## Staking Types

All staking functions accept a `stakingType` parameter:

| Value | Token |
| ----- | ----- |
| `1`   | ADX   |
| `2`   | ALP   |

***

## Liquid Staking

Liquid stakes have no lock-up period. You can unstake at any time.

### Add Liquid Stake

```typescript
import { addLiquidStake } from 'adrena-sdk/core';
import { createKitClient } from 'adrena-sdk/clients';

const { wallet, rpc } = await createKitClient();

// Stake 100 ADX (6 decimals)
await addLiquidStake({
  wallet,
  rpc,
  stakingType: 1,               // 1 = ADX, 2 = ALP
  amount: BigInt(100_000_000),  // 100 ADX in native units
});
```

### Remove Liquid Stake

```typescript
import { removeLiquidStake } from 'adrena-sdk/core';
import { createKitClient } from 'adrena-sdk/clients';

const { wallet, rpc } = await createKitClient();

await removeLiquidStake({
  wallet,
  rpc,
  stakingType: 1,
  amount: BigInt(100_000_000),
});
```

***

## Locked Staking

Lock a stake for a fixed duration to earn boosted rewards. Longer durations provide a higher multiplier.

### Add Locked Stake

```typescript
import { addLockedStake } from 'adrena-sdk/core';
import { createKitClient } from 'adrena-sdk/clients';

const { wallet, rpc } = await createKitClient();

// Lock 500 ADX for 90 days
await addLockedStake({
  wallet,
  rpc,
  stakingType: 1,
  amount: BigInt(500_000_000), // 500 ADX in native units
  lockedDays: 90,
});
```

### Supported lock durations

`7` · `30` · `60` · `90` · `180` · `360` · `540` · `720` days

***

## Remove Locked Stake

After the lock period expires, withdraw by providing the index of the lock in the `UserStaking` account (zero-based).

```typescript
import { removeLockedStake } from 'adrena-sdk/core';
import { createKitClient } from 'adrena-sdk/clients';

const { wallet, rpc } = await createKitClient();

await removeLockedStake({
  wallet,
  rpc,
  stakingType: 1,
  lockedStakeIndex: 0, // 0-based index in the UserStaking account
});
```

***

## Claim Staking Rewards

Claims all pending USDC fee rewards and ADX emissions for the given staking type.

```typescript
import { claimStakes } from 'adrena-sdk/core';
import { createKitClient } from 'adrena-sdk/clients';

const { wallet, rpc } = await createKitClient();

// Claim ADX staking rewards
await claimStakes({ wallet, rpc, stakingType: 1 });

// Claim ALP staking rewards
await claimStakes({ wallet, rpc, stakingType: 2 });
```


# Data API

The SDK includes a REST client for querying off-chain analytics - position history, pool statistics, leaderboards, oracle prices, and more. This is separate from the on-chain RPC interface.

***

## Setup

Full API reference is available at [datapi.adrena.trade/docs](https://datapi.adrena.trade/docs).

```typescript
import { AdrenaApi } from 'adrena-sdk/adrena-api';

const api = new AdrenaApi(); // defaults to datapi.adrena.trade
```

To point to a custom endpoint:

```typescript
const api = new AdrenaApi('https://your-custom-endpoint.com');
```

***

## Positions

Fetch the position history for a wallet address.

```typescript
const positions = await api.getPositions({
  userWallet: '8xMT...abc',
});
```

***

## Pool Analytics

Query pool-level statistics at various time resolutions.

```typescript
// Latest snapshot
const pool = await api.getPoolInfo();

// Hourly data
const hourly = await api.getHourlyPoolInfo();

// Daily data
const daily = await api.getDailyPoolInfo();
```

***

## Custody Analytics

Per-asset statistics (open interest, utilisation, fees collected).

```typescript
const custody = await api.getCustodyInfo();
const hourlyCustody = await api.getHourlyCustodyInfo();
const dailyCustody = await api.getDailyCustodyInfo();
```

***

## Trader Data

```typescript
// Performance metrics for a single trader
const trader = await api.getTraderInfo('8xMT...abc');

// Trader volume history
const volume = await api.getTraderVolume({ userWallet: '8xMT...abc' });

// Leaderboard
const profiles = await api.getTraderProfiles();
```

***

## Mutagen (Points)

```typescript
// Points for a wallet
const mutagen = await api.getMutagen('8xMT...abc');

// Full leaderboard
const leaderboard = await api.getMutagenLeaderboard();
```

See [Mutagen (Points System)](/about-adrena/mutagen-points-system) for details on how points are earned.

***

## Prices

```typescript
// ADX and ALP token prices
const prices = await api.getPrice();

// Latest oracle trading prices for all assets
const tradingPrices = await api.getLastTradingPrices();
```

***

## Available Methods

| Method                           | Description                                |
| -------------------------------- | ------------------------------------------ |
| `getPositions(params)`           | Position history for a wallet              |
| `getPoolInfo(params?)`           | Latest pool statistics                     |
| `getHourlyPoolInfo(params?)`     | Hourly pool statistics                     |
| `getDailyPoolInfo(params?)`      | Daily pool statistics                      |
| `getCustodyInfo(params?)`        | Per-asset custody statistics               |
| `getHourlyCustodyInfo(params?)`  | Hourly custody statistics                  |
| `getDailyCustodyInfo(params?)`   | Daily custody statistics                   |
| `getMutagen(userWallet)`         | Mutagen points for a wallet                |
| `getMutagenLeaderboard(params?)` | Full mutagen leaderboard                   |
| `getTraderInfo(userPubkey)`      | Performance metrics for a trader           |
| `getTraderProfiles(params?)`     | Trader leaderboard                         |
| `getTraderVolume(params?)`       | Volume history for a trader                |
| `getPrice()`                     | Current ADX and ALP token prices           |
| `getLastTradingPrices()`         | Latest oracle prices for all traded assets |

***

## Advanced: Building Instructions Manually

Every `core` function is a thin wrapper around an `instructions` builder that then submits via Jito. Use the builders directly when you need to compose custom transactions.

```typescript
import { getOpenLongIxs } from 'adrena-sdk/instructions';
import { sendTransactionWithJito, ADRENA_LOOKUP_TABLE_ADDRESS } from 'adrena-sdk/helpers';
import { createKitClient } from 'adrena-sdk/clients';

const { wallet, rpc } = await createKitClient();

const { ixns, positionAddress } = await getOpenLongIxs(
  wallet,
  'JITOSOL',  // principalToken
  'JITOSOL',  // collateralToken
  10,         // collateralAmount (human-readable)
  3,          // leverage
  rpc,
);

// Prepend/append your own instructions, then send
const txSig = await sendTransactionWithJito(
  ixns,
  wallet,
  rpc,
  false, // simulate only
  true,  // use Jito bundle
  [ADRENA_LOOKUP_TABLE_ADDRESS],
);
```

All liquidity and staking instruction builders follow the same pattern - see `src/instructions/` in the SDK repository for the full set.


# Terms and Conditions

> ⚠️ Full terms to be populated. Run the local scraper script for complete content.

See also: [Token Terms and Conditions](/terms-and-conditions/token-terms-and-conditions)


# Token Terms and Conditions

> ⚠️ Full token terms to be populated. Run the local scraper script for complete content.


# How to Change to Devnet in Phantom Wallet

> ⚠️ Full guide with screenshots to be populated. Run the local scraper script for complete content.

1. Open Phantom Wallet
2. Go to Settings
3. Select "Change Network"
4. Choose "Devnet"


# How to Get Devnet SOL

> ⚠️ Full guide to be populated. Run the local scraper script for complete content.

Use the Solana devnet faucet at [faucet.solana.com](https://faucet.solana.com) to get devnet SOL.


# How to Get Tokens to Trade

> ⚠️ Full guide to be populated. Run the local scraper script for complete content.

To trade on Adrena, you'll need SOL or supported tokens in your wallet. You can acquire them via:

* Centralized exchanges (Coinbase, Binance, Kraken)
* DEX aggregators like [Jupiter](https://jup.ag)


# How to Open and Close a Trade

> ⚠️ Full guide with screenshots to be populated. Run the local scraper script for complete content.

## Opening a Trade

1. Go to [adrena.trade](https://adrena.trade)
2. Connect your wallet
3. Select a market (e.g., SOL/USD)
4. Choose Long or Short
5. Set your collateral and leverage
6. Click "Open Position"

## Closing a Trade

1. Go to the Positions panel
2. Click "Close" on your position
3. Confirm the transaction in your wallet


