# What is Premia?

Other than the Premier DeFi Token Options Exchange (DTOX) 🙅‍♂️

To begin, we should make clear the distinctions between the different areas of "Premia", some of which may confuse new users.

#### <mark style="color:blue;">**The Premia Protocol**</mark>

A suite of upgradable smart contracts that together facilitates peer-to-peer market making and trading of options on ERC-20 tokens available on the Ethereum blockchain along with a settlement engine. This can be thought of as the “base” layer.

#### <mark style="color:blue;">**Premia Vault Depot**</mark>

A suite of in-house and third party smart contracts, composed *on top* of The Premia Protocol, that enables additional user functionality such as participation in automated strategies, leverage, and risk management on the Ethereum blockchain.

#### <mark style="color:blue;">**The Premia Interface**</mark>

A web interface that allows for easy interaction with the Premia protocol. The interface is only one of many ways one may interact with the Premia protocol.

#### <mark style="color:blue;">**Premia Governance**</mark>

A governance system for governing the Premia Protocol, enabled by staking PREMIA token and receiving vxPremia.


# Premia Origins


# History

Premia is a peer-to-peer options exchange and settlement engine built for the Ethereum Virtual Machine (EVM). The protocol is designed to provide a set of smart contracts that advance open finance by prioritizing security, self-custody, automatic execution without a trusted intermediary, and permissionless use of financial primitives.

There are currently three versions of the Premia protocol:

<mark style="color:blue;">**Premia v1:**</mark> Peer-to-peer order-book based options exchange

* Launched early 2021
* Deprecated late 2021

<mark style="color:blue;">**Premia v2:**</mark> AMM-based options exchange

* Launched late 2021

<mark style="color:blue;">**Premia v3:**</mark> Concentrated AMM-based options exchange w/ peer-to-peer order network

* Launched Q3 2023

The protocol has advanced in functionality and efficiency with each new iteration. Previous versions will remain accessible with 100% uptime (even post-deprecation) via the Ethereum blockchain (though some features might not be maintained, such as the volatility surface for each token).


# Principles

## Premia: Public Redux of Economic Market & Investment Access

One of the first principles of the Premia v3 protocol and a core part of the ecosystem's culture is to enable permissionless use by anyone worldwide. This design decision was inspired by Ethereum's core ideals and our commitment to open access as a requirement for a future in which anyone can access top financial services, no matter their life circumstances. - *Equity of opportunity*

### Conscious, Open, & Contestable Smart Markets&#x20;

#### Permissionless Smart Contract Design

Permissionless design in a protocol refers to its services being unrestricted and open in nature. Unlike traditional systems with barriers or limitations, a permissionless design ensures that anyone can freely access and utilize the services regardless of location, financial status, age, or other factors.

In a decentralized financial system, activities such as selling financial products, hedging risk with options, passive yield through algorithmic strategies, swapping assets, providing liquidity, or creating new markets are available to all users without approval or authorization. No gatekeeper or central authority can deny access based on arbitrary criteria.

{% hint style="info" %}
Permissionless is core to the Premian ethos; however, certain regulations restrict Premia ecosystem partners from providing services based on certain jurisdictions or sanctions. Thus, to remain compliant, some jurisdictions or domiciles may see limited services offered via the Premia Blue app, which an ecosystem partner operates.
{% endhint %}

This significantly differs from traditional financial services, where access is often tightly controlled. For example, traditional banks and investment platforms might restrict services based on a person's geography, requiring them to reside in a particular country or region. Wealth status might also be a barrier, with certain investment opportunities only available to those who meet specific income or net worth criteria. Age restrictions are also common, particularly for products and services considered higher in risk or complexity deemed only available for "sophisticated actors" or "accredited investors".

The permissionless design embodies the ethos of decentralization, promoting inclusivity and democratizing access to financial tools and opportunities. It breaks down barriers historically excluding large population segments from the global financial system, allowing for a more equitable distribution of resources and opportunities.

However, it's worth noting that this openness also comes with challenges and risks. The lack of restrictions means a higher potential for fraudulent or malicious activities. It also places a greater responsibility on individual users to understand and manage the risks associated with their actions, as no centralized entity oversees or regulates the activities.

In essence, permissionless design is both a revolutionary concept and a double-edged sword. It opens doors for many who have been left out of the traditional financial system but also requires a new level of awareness and responsibility from all participants. It represents a fundamental shift in how we think about access to financial services, moving from a system of gatekeeping and control to one of openness and individual empowerment.


# Mission, Vision, & Values

a disorganized manifesto-lite

## Vision

**Public Redux of Economic Market & Investment Access**: A world where financial markets are democratized, granting universal access to investment opportunities and economic empowerment.

## Mission

**Leading the Meta-Economy. Economics reNewed, reDefined, reClaimed**: Pioneering a new era of economics that is revitalized, reshaped, and reclaimed for the people by the people.

## Value Proposition

**Conscious, Open, & Contestable Smart Markets**: Creating transparent and competitive markets driven by conscious decision-making and open to all.

## Stakeholders

* **Community**: The heart and soul of our ecosystem.
* **Contributors**: The builders and innovators.
* **Participants**: The users and beneficiaries.

## Strategy

* `Empower` Finance: Democratizing finance for all.
* Open License to *Innovate*: Encouraging creativity and innovation.
* ~~Sufficiently~~ Egalitarian: Ensuring fairness and equality.
* Open reVolutionary: Leading a revolution in financial access.

## Priorities

* **Core Value Proposition - Optimal Dual Agency Markets**: Balancing for optimal market function.
* **For Contributors**: Encouraging moral courage, passion, and cooperative building.
* **For Participants**: Providing competitive, secure, and sufficient investment access. 😜

## Culture

> **Equality of Wealth, Equity of Opportunity, & Economic Justice**:&#x20;
>
> &#x20;   **- Premian Meta-Economic Virtues E^3**: Building a fair and just financial world.

## Core Contributor Values

* **Morally Courageous**: Standing for what's right.
* **Passionate**: Driven by a love for innovation.
* **Social Cultivation**: Growing together.
* **Auto-Didactic Idealism**: Self-learning and ideal-driven.
* **Open Revolution & Reform**: Changing the world.
* **Humanitas, Fides, Virtus**: Embracing humanity, faith, and virtue.
* **Philanthropy & Patronage**: Supporting education, truth, and virtue.
* **Apprenticeship + Sponsorship = Fellowship**: Mentoring the next generation.

**Prodaedal Systems, Antidaedalian Design - Bildung / Paideia**: Crafting complex systems with simplicity and education at the core.

## **Live It, The Open Gate Manifesto: A Charter for Inclusive Innovation and Economic Democracy**

\
**OPEN MARKETS, NO BARRIERS** At Premia, we don't just advocate for open markets; we embody them. Championing the democratization of financial access is our core mission, and we relentlessly pursue it. All opportunities, whether internal collaborations or external engagements, are accessible by default. There are no hidden agendas, no insurmountable walls. We fear no challenge in being transparent and honest with ourselves, our contributors, and our community, we **live it** every day. In a world where barriers often define the landscape, we are the pathfinders, breaking down walls and building bridges to financial empowerment.

**BUILD WITH VISION AND EQUITY** Every day at Premia, we strive to create products that are not just innovative but revolutionary. Building with vision means more than crafting solutions; it's about shaping the future. It's about believing in what we're doing so passionately that it becomes a mission, not just a task. We use it, we own it, we **live it**. When we build with equity, we're not just considering the bottom line; we're looking at the bigger picture. We consider how our initiatives and decisions affect our community, participants, and the world. Equity is not an afterthought; it's the foundation of our innovation. Led by the belief that everyone deserves a fair shot at financial success, and we're here to make it happen.

**DON'T BETRAY THE COMMUNITY** Trust is the cornerstone of Premia's relationship with the community. When we make internal decisions, we don't just consider the business implications; we ask ourselves, "How will this affect our community?" If the answer is that it would undermine them or make access more complex, we don't just find another way; we find a better way. A more inclusive way. A way that honors the trust that the community has placed in us. We recognize that trust is not given; it's earned. And we commit to earning it at every dawn, with every decision, and through every action, we **live it**. Our community is not just an audience; they are our partners, collaborators, and inspiration. Betraying them is not an option; empowering them is our promise.

**INNOVATE AS A COLLECTIVE** In the world of Premia, innovation is not a solitary pursuit but a collective endeavor. We want all Premians—contributors, participants, and visionaries—to feel like they are integral parts of the Premia movement, not mere cogs in a machine.

Innovating with your collaborators means embracing diverse perspectives, fostering a culture of creativity, and recognizing that the best ideas often emerge from the synergy of minds. It's about working together, not just alongside each other, to create something greater than the sum of its parts.

Contributing to the Premia collective is more than just a task; it's a calling. It's about believing in democratizing financial access and taking active steps to make it a reality. It's about being part of a community that values openness, equity, and the power of collaboration.

At Premia, we don't just talk about innovation; we **live it**. We encourage every Premian to bring their unique insights, passions, and talents. Together, we are not just building products; we are shaping the future of finance, redefining what's possible, and creating a legacy of positive change.

**EMBRACE THE META-ECONOMY YOU SEEK** The call to redefine economics is not just a distant echo; it's a clarion call that resonates at the core of Premia. It's a path we must walk ourselves, not just preach to others. At Premia, we don't just encourage everyone to create positive change; we live it, breathe it, and embody it.

We're not content with the status quo; we're constantly looking for ways to improve our platform, products, and impact. Innovation is not a one-time achievement; it's an ongoing journey. A journey towards a meta-economy where financial access is not a privilege but a right. Where opportunities are not hoarded but shared. Where success is not exclusive but inclusive.

In a world of closed doors, where barriers often define the boundaries of possibility, we are the open gate. We are the way forward. We are the promise of a new era where economics is not just about numbers and figures but about people, dreams, and empowerment.

Embracing the meta-economy is not just about changing systems; it's about changing lives. It's about building a world where financial freedom is not a distant dream but a tangible reality. It's about creating a space where everyone has a seat at the table, where voices are heard, and where dreams are nurtured.

At Premia, we don't just seek the meta-economy; we are building it. Brick by brick, idea by idea, collaboration by collaboration. And we invite you to join us in this remarkable journey. Because the future is not something we wait for; it's something we create.

**Live it.**

## **A Meta-Economic Manifesto**

**ALWAYS EMBRACE OPENNESS.** You should be pushing boundaries and embracing openness, especially in finance. Big changes. Trying what may not have been tried before. Asking questions that challenge the status quo. Seeing if the doors you open remain unshut.

**BE REVOLUTIONARY.** Some will push traditional economics on you. Others will make you pull what you need from the new era. Challenge both. Question their assumptions. Ask for innovation.

**BREAK THE BARRIERS.** Defying the barriers forces you to stray from the path of conventional finance and ultimately create a platform that is more inclusive, more empowering, and more revolutionary.

**EXPLORE EVERY POSSIBILITY. DISMISS NOTHING.** Every idea has the potential to be groundbreaking and transformative. Not every idea will be, but the more you explore, the better your chances of finding something that will redefine finance.

**BE PASSIONATE.** Passion drives you to explore and discover as much as possible about something that inspires you. In the world of Premia, passion fuels innovation.

**BE UNCONVENTIONAL.** It's easy to follow the beaten path of traditional finance. Truly great, inspiring, and transformative platforms come not from convention but from unconvention.

**BE VISIONARY.** You should have visions about finance and the world around you. Preferably, you should have bold visions. Ideally, you should have bold and informed visions.

**BE A PIONEER.** A Premian is a modern pioneer. When you are part of Premia, you are part of a movement 24/7/365. Constantly innovating, always observing, continuously redefining, even if only of the mind.

**The Decentralized Charter: A Manifesto for Inclusive Finance and Community Empowerment**

**Purpose** • Create a decentralized financial platform that empowers and democratizes access to financial opportunities. • Foster a community-driven ecosystem that is owned and shaped by its participants. • Cultivate long-term, transparent, collaborative relationships with our community, contributors, and partners.

**Principles** • **Inclusive**: The belief that financial opportunities should be accessible to all. This includes equality, non-discrimination, and global access. • **Innovative**: We have a forward-thinking view on our platform. We innovate responsibly, support the community, and drive the future of finance. • **Transparent**: We communicate openly and honestly. Any information or process that can be made public will be made public. • **Collaborative**: Create an ecosystem where people can contribute, innovate, and grow together. • **Adaptive**: Be flexible, receptive, and responsive, especially when dealing with community feedback and evolving financial landscapes.

**Methods** Concrete tools for helping us live according to our principles, including • Community-driven decision-making. • Platform transparency – any information or process that can be made open should be made open. • Licensing that benefits our community, contributors, partners, and the broader financial ecosystem. • Revenue-sharing with community, contributors, and aligned causes. • Don’t try to impose a one-size-fits-all approach. Focus on leveraging the diverse strengths of the community. Develop ways to embrace different perspectives and ideas. • Prefer to collaborate with individuals and entities who share our values. • Advocate for decentralized finance and work against regulations that limit financial freedom and individual empowerment responsibly and ethically.

Premia is your platform, molded by you, constructed with love.


# Quick Start

## <mark style="color:blue;">Connecting to a Chain & Wallet</mark>

Connecting to the UI can be done via the following wallets. If you do not have a wallet yet, you can use [MetaMask](https://metamask.io/download/):

<figure><img src="/files/Z9T3bzN3u4ctsPB9VoE1" alt=""><figcaption></figcaption></figure>

Premia V3 is currently available solely on [Arbitrum Mainnet](https://arbitrum.io/).   If using MetaMask as a wallet,  you can visit [Arbitrum One (42161)](https://chainlist.org/chain/42161)  (or [Arbitrum Goerli (421613)](https://chainlist.org/chain/421613) if using testnet) and add the chain quickly and easily.&#x20;

## <mark style="color:blue;">Selecting an Option</mark>

From the Trade tab, there is the option to view markets in either a **Basic** layout or an **Orderbook** layout. The orderbook layout will provide more details beyond just price. Additionally, the underlying, option type (Call or Put), and trade direction are used to help narrow down the option pools.

<figure><img src="/files/v49ubwVMQ3AjGbC2TRVs" alt=""><figcaption></figcaption></figure>

\
To receive quotes, a Strike, Expiration and Option Size (Trade Size) are required.

<figure><img src="/files/4ewrY7FiRjCCxE6g1JEG" alt=""><figcaption></figcaption></figure>

Quotes will populate for a given market once all market parameters have been selected. Multiple quotes may appear and the source of these quotes may be of different origin (ie. Vault, Orderbook, or Option Pool). Additionally, markets with different oracles (but the same Token Pair), will also appear.

The quotes are arranged in order of best price. By selecting a quote, a confirmation window will pop up to proceed with executing a trade. You can then select your payment token and see potential profit and loss.

<figure><img src="/files/hT6XBEodAVQXnbfr8HBz" alt=""><figcaption></figcaption></figure>

{% hint style="danger" %}
It is prudent to note that trades can only be *closed* using the market the trade was *opened* in. For example, WETH/USDC (Chainlink) and WETH/USDC (Uniswap) are not the same market!. &#x20;
{% endhint %}

## <mark style="color:blue;">Trading</mark>

### **Executing a trade (Basic)**

Prior to execution of a trade, basic information is given about the trade. Trades can be initialized with *any* asset as collateral, but will be converted to the collateral asset of the option prior to executing the trade using a DEX aggregator. Users can set slippage controls for swaps if needed. The default is 0.5% slippage for swaps.

<figure><img src="/files/cdPCvPOXwNkJN2zZFIAf" alt=""><figcaption></figcaption></figure>

### **Executing a trade (Orderbook)**

Using the Orderbook view for execution, we can see and traverse through multiple Expirations horizontally and Strikes vertically. Additionally, each Strike can be expanded to see additional information about the option itself, such as Implied Volatility, Bid/Ask Price & Size, Market Price, and Option Greeks.

<figure><img src="/files/eQbsCGUBse5ySdjrC86I" alt=""><figcaption></figcaption></figure>

### **Submitting a range order**

By selecting the Pools tab, we are able to begin the process of submitting a range order and becoming an LP (Liquidity Provider) for a specific pool. Similar to executing a trade, details of the desired pool must be provided first.

{% hint style="info" %}
💡 It is important to know that a single options market (Pair, Strike, Expiration, Type) makes up a single option pool. Therefore range orders are *option specific*. This is not to be confused with being an LP for a vault, which may trade many different options.
{% endhint %}

<figure><img src="/files/CRE2OoFXH51EKLUtGqVU" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/BM9kZQCL80wLGzShxnsV" alt=""><figcaption></figcaption></figure>

### **What does a Buy or Sell Range Order mean?**

Range orders are *side specific*. When initializing a range order, an LP must define the exposure type they would prefer. For example, if an LP would not mind a short exposure (or is depositing long option contracts they would not mind selling), the order type would be a SELL range order. Conversely, if an LP would not mind a long exposure (or is depositing short option contracts they would not mind closing), the order type would be a BUY range orders.

### **Min & Max Values of a Range Order**

Besides the size of the range order, a min and max price limit must be set. For convenience, an Auto-convert toggle is available to see prices in the quote asset.

For more information regarding Range Orders and how they work please see [LP Range Orders](/the-premia-protocol/concepts/lp-range-orders).

<figure><img src="/files/o9DhK0dh2LjKbPGHQCxx" alt=""><figcaption></figcaption></figure>

## <mark style="color:blue;">Managing Positions</mark>

When a wallet is connected, a user is able to click on the Positions tab to see existing option positions for the given wallet address. If a user would like to close a position, it is best to select the option from your portfolio and close/modify the trade from here. By doing so, the position will be closed, and collateral released (if short).

Alternatively, positions can be closed directly from the Trade page. If the trade size is larger than the existing position, the position will first be closed before creating new exposure in the opposite direction.

{% hint style="info" %}
💡 If using the Trade page to close a position, be sure that the oracle for the underlying market is the same, otherwise they are treated as two separate markets.
{% endhint %}

<figure><img src="/files/aldjSDGzsLPty8Mj52Wl" alt=""><figcaption></figcaption></figure>

## <mark style="color:blue;">Staking Premia Token</mark>

Users may stake the Premia token for many reasons. In order to stake Premia tokens, a lock up period must be selected (zero days can be selected). The longer the lock period, the more influence (votes) the staked premia will have and the more staking rewards that can be earned. Staked Premia also shares in earnings from trading fees. Currently, any tokens not paid directly to LP’s are split 50/50 between stakers and the protocol.

For additional details on Governance and Voting, please see [here](broken://pages/uTRjNgDDxzIhDimjgDs2).

<figure><img src="/files/175Me0NQ4wNhMTQ1tGl2" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/BglDYfB0B5Jx0tVYAlHH" alt=""><figcaption></figcaption></figure>

### **Voting**

Staked Premia allows a user to vote on liquidity mining emissions by Vault or Pool. There is incentive to direct liquidity mining emissions to active markets which generate the highest amount of fees, as it will generate higher USDC returns for stakers. Voting can be done at any time, and weights are updated on each block.

<figure><img src="/files/g03OonfAlYHYGAokftp5" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/c4vCgnzMc0o6jnLkR3Wx" alt=""><figcaption></figcaption></figure>

## <mark style="color:blue;">Vaults</mark>

Vaults can be accessed through the Vault tab. Here you will find various single purpose vaults that allow participants to passively earn a return on their investment, manage risk, or hedge specific positions.

{% hint style="info" %}
💡 Each vault has their own mandates and risk profiles. Please ensure that the risks and investment type are suitable for your needs. Additional information about vaults on this page can be found here.
{% endhint %}

<figure><img src="/files/BdiCSzINksFtam4ethbQ" alt=""><figcaption></figcaption></figure>

After determining the appropriate vault, it is as simple as selecting the token that will be used for depositing (a swap will be performed if the asset is not the Vault asset).

### **Vaults Detailed**

Each vault has a detailed page in which specifications about the vault can be found.

<figure><img src="/files/QEViuvrZGNDeTgLKrU6S" alt=""><figcaption></figcaption></figure>


# Options on Premia

Premia options are [ERC-1155 tokens](https://eips.ethereum.org/EIPS/eip-1155) that offer the holder the right (but not the obligation) to buy or sell the underlying token on a specified date. While traditional stock option contracts usually represent 100 shares of the underlying stock, options on Premia represent the same number of tokens as described.

*For exampl&#x65;**,** a 100 ETH call option represents the right to buy 100 ETH at the option's strike price by the option's maturity date.*

Each *option pool* has a **token pair** (e.g. ETH/USDC), an **option type** (call or put), a **strike price** (the price at which the option can be exercised), and a **maturity date** (the expiration date of the option).

{% hint style="info" %}
Each option *is* a pool and each market (ie. ETH/USDC) has multiple pools. Every option is defined by a token pair (oracle feed), expiration, type, and strike price.
{% endhint %}

Options on Premia v3 are *European* in nature, meaning they can only be exercised at or after expiration. This is an update from Premia v2, in which options were American in nature, and could be exercised any time before or after expiration.

Call options use the Base (Underlying) Asset (ie. ETH for an ETH/USDC call option) for collateral where as puts use the Quote Asset (ie. USDC for an ETH/USDC put option). Each option is priced in the corresponding collateral asset.

The Premia Protocol (AKA the “base” layer) requires FULL collateralization. This means that for each *call option* that is traded, the exchange must hold 1 unit of the Underlying Asset to ensure that there is no counter party risk. For each *put option*, the exchange must hold the Quote Asset equivalent to the strike price (eg. 1,800 USDC for a strike price of 1,800 ETH/USDC).


# Options Primer

This is an optional read

{% hint style="success" %}
If you would like to learn more, you are encouraged to complete the Premia Academy Options 101 Courses, which can be found at <https://academy.premia.blue/>
{% endhint %}

**The largest use case for options is hedging risk** (i.e. buying insurance against) the downside risk of tokens one already holds via put options or on the upside risk of tokens one does not already own (or is short) via call options.

Options are also the most popular financial product to express views on volatility (and directional exposure). They exhibit many traits that allow users to curate their desired risk profiles by combining multiple options or using various expirations/strikes.

### **Call options vs. Put options**

Call options provide the owner of the option the right, not an obligation, to purchase the described amount of underlying tokens at the specified strike price, by the option's maturity date. **Buyers of call options believe the underlying token&#x20;*****could*****&#x20;go up in price over time beyond the cost of the premium paid.**

<figure><img src="/files/BTcapIQmU9cklycNZfaa" alt=""><figcaption></figcaption></figure>

Put options provide the owner of the option the right to sell the described amount of the underlying token at the described strike price, by the option's maturity date. **Buyers of put options believe the underlying token&#x20;*****could*****&#x20;go down in price over time time beyond the cost of the premium paid.**

<figure><img src="/files/Fq3TETLeDOZFVi7M4R5Z" alt=""><figcaption></figcaption></figure>

### **The Greeks**

The specific risk metrics of each option can be measured in terms of 5 common variables, often called *The Greeks*. Traders often use these metrics to compare the risk profiles of different options and make decisions as to which option closer meets their strategy. It is important to keep in mind that The Greeks are dynamic, based on current market prices, and are constantly changing, meaning the variables are instantaneous in nature and should not be considered long-term truth values.

#### **Delta**

The change of option price due to price change of the underlying token. Call options have positive delta, put options have negative delta.

{% hint style="info" %}
*A Delta of 0.5 means the option price changes $0.50 for every $1.00 change in the price of the underlying token pair.*
{% endhint %}

#### **Gamma**

Rate of change of the option Delta given a change in price of the underlying token. Gamma is positive if you are long an option (call or put) and negative is you are short an option (call or put).

{% hint style="info" %}
*A Gamma of .01 means the Delta will go up(down) by .01 for every $1.00 change up(down) in the price of the underlying token pair.*
{% endhint %}

#### **Theta**

The change in option price caused by time value decay. Theta is positive if you are short an option (call or put) and negative is you are long an option (call or put).

{% hint style="info" %}
*A Theta of -5 means the option price will decay at a rate of $5 every day prior to expiration (all else being equal).*
{% endhint %}

#### **Vega**

The change in option price caused by a change in an options implied volatility. Vega is positive if you are long an option (call or put) and negative is you are short an option (call or put).

{% hint style="info" %}
*A Vega of 2 means the option price will increase(decrease) by $2 for every 1% increase(decrease) in the option’s implied volatility.*
{% endhint %}

#### **Rho**

The change in option price caused by a 1% change in an options interest rate (typically the risk free rate). Calls have a positive Rho, Puts have a negative Rho.

{% hint style="info" %}
*A Rho of 0.5 means the option price will increase(decrease) $0.50 for every 1% increase(decrease) in the interest rate.*
{% endhint %}


# Order-book vs. AMM

Most traditional markets and centralized exchanges utilize central-limit order books (CLOBs) to track user orders and match overlapping trades. Traders familiar with traditional option brokers and crypto option exchanges will be familiar with order books, in which a depth of liquidity is maintained for each price level on the bid (buy-side) and ask (sell-side) of the market price by market **makers**, while **takers** can fill trades by accepting existing orders on the book.

In the Premia v3, market makers can deposit liquidity into [**range orders**](/the-premia-protocol/concepts/lp-range-orders) in an on-chain pool within the user’s defined price range (AKA concentrated liquidity). Makers can place range orders on the **buy-side,** **sell-side,** or **both**, to determine how their liquidity can be used within the specified price range. Each market’s automated price is directly determined by the distribution of liquidity on the exchange, and the past trades in the market. As traders (takers) buy options from sell-side orders, the market price will be adjusted upwards, and as traders sell options to buy-side orders, the market price will be adjusted downwards. This enables both traders and market makers to maintain short and / or long positions on the exchange as either makers or takers.

Each time a trade occurs, every overlapping range order will split fees and exposure for the trade pro-rata, determined by the amount of liquidity in each range order vs. the total amount of overlapping liquidity. The price each user pays or receives for an option is the quote price, determined by the AMM, plus a [**taker fee**](/the-premia-protocol/concepts/fees)**.** The taker fee is split between makers and the protocol **stakeholders** ([vePREMIA](broken://pages/uTRjNgDDxzIhDimjgDs2) holders and protocol treasury).

Additionally, market makers can place limit orders on the [v3 order book](/the-premia-protocol/concepts/orderbook-and-request-for-quote-rfq) (which lives on Arbitrum Nova). Users do not need to interact with Arbitrum Nova directly; the Premia Blue UI will relay these orders and cover gas for your convenience. These orders do not earn maker fees; however, they will still be quoted to users on the Premia Interface via resting Limit Order.

This duality enables Premia v3 users to benefit from both earning fees in automated range orders and trade or market-make in traditional order book fashion. Exchange traders will also benefit from increased liquidity and better option pricing.


# Key Protocol Features

## <mark style="color:blue;">**Capital efficiency**</mark>

Liquidity providers are able to create concentrated range orders in an option pool with defined upper and lower price bounds. As traders move the market price through an LP’s price range, the LP will collect trading fees and the LP’s exposure will be updated. If the market price moves back down, the LP will collect more trading fees as the LP’s exposure will be reversed back to its original state.

A price range with more liquidity will require more option trades to be traversed than an equivalent price range with less liquidity, all else equal. This enables active traders with high conviction to benefit from highly capital efficient, concentrated orders, while passive traders with less conviction can still benefit from trading fees in a less capitally efficient range.

This increased capital efficiency can compounded by the use of a sell-side margin vault. The amount of collateral required to sell an option is often much larger than is required to buy the same option, thus causing an imbalance in option markets. A margin system introduced alongside the protocol enables sell-side LPs and option sellers (takers) to open positions on margin, up to an amount determined by an automated value-at-risk system.

## <mark style="color:blue;">**User functionality**</mark>

Traders, market-makers, and traditional LPs all receive additional functionality in this version of the protocol. Traders can buy or sell using market orders any time there is liquidity in the pool, with price impact determined by the size of the trade relative to the amount of liquidity in the effected price range(s).

LPs can place *uni-directional* concentrated orders within a specific price range to express a position that will either get net-long or net-short as the market price traverses through the range.

Users with more passive intentions can utilize automated liquidity pools (vaults), built to manage specific trading, investment, and hedging strategies for the users within the vault’s liquidity pool.. The v3 system has been built as the base liquidity layer, on top of which many different strategies can be composed without liquidity fragmentation.

## <mark style="color:blue;">**Composability**</mark>

Diverse strategies can be created on top of the protocol, all benefiting from the more accurate price discovery, improved execution prices, and increased capital availability in the unified liquidity space. A wide range of vaults, traders, market-makers, and LPs can use the exchange for different reasons, without segregating and fragmenting liquidity for each use case. Due to the permissionless nature of the protocol, anyone can create a new market for an [ERC-20](https://eips.ethereum.org/EIPS/eip-20) pair, so long as each token has an on-chain spot price oracle (data feed). Options on the protocol are represented as [ERC-1155 tokens](https://eips.ethereum.org/EIPS/eip-1155) and LP positions are represented as [ERC-721 tokens](https://eips.ethereum.org/EIPS/eip-721), to preserve maximum composability.

For each trade in a pool, the exposure change and fee growth is distributed pro-rata across all liquidity overlapping the traded price range. Fees are accumulated separately and not compounded back into LP positions, enabling vaults to distribute fees according to their specific strategies. Pool capital can be borrowed for a fee with flash loans, increasing protocol and LP revenue generation. In addition, the historic pricing and volatility of options in each pool can be queried from the pool’s time-weighted average oracle, enabling deep integrations within other protocols.

## <mark style="color:blue;">**Protocol sustainability**</mark>

The Premia v3 protocol requires no maintenance.

Additionally, the governance of liquidity mining emissions is entirely on-chain with the introduction of the vxPREMIA system. This upgrade incentivizes stakers and LPs to more actively participate in reward distribution decisions, ensuring the pools with the highest expected fee returns receive the highest subsidies. Expired option positions can also be settled by any user of the protocol. This feature is self-financed by withholding collateral for the cost of EVM transaction fees (gas), enabling the feature to be permanently supported without external funding.

## <mark style="color:blue;">Incentivization</mark>

The protocol currently incentivizes Vaults to provide liquidity to the Premia Protocol with PREMIA liquidity mining rewards. The result is more trading volume, as takers receive better execution prices and have more liquidity to counter-trade. It follows that higher volumes will result in higher returns from fee distributions for stakeholders of the protocol.

LPs are additionally incentivized to stake the PREMIA they receive from liquidity mining rewards for vxPREMIA, to earn a higher portion of trading fees, pay less fees on any taker trades, and direct more rewards to the pairs in which they receive the highest fee return.

To complete the incentive circle, vxPREMIA stakers are incentivized to direct rewards to the vaults and pools that generate the most volume and highest fee return, as it will result in the highest return from fee distributions. All of these incentivizes work together to increase net volume and available liquidity, improve price efficiency, and enable higher returns for users of the platform.


# Base Layer (Exchange)

The base layer of PREMIA V3 is a complete rework of the protocol, focusing on capital efficiency in the decentralized finance (DeFi) options exchange. Here's a summary of the key components:

1. **Concentrated Liquidity**: Allows liquidity providers (LPs) to create positions in specific option pools with defined price bounds. It enables both active and passive traders to maximize fee collection and capital efficiency.
2. **Partial Collateralization**: Introduces margin architecture, enabling partial collateralization of options for select payoffs like spread strategies. This facilitates greater liquidity and more efficiently-priced assets while maintaining solvency and eliminating counter-party risk. (Enabled at a later date - ETA Oct 23)
3. **Transaction Fees & Liquidity Mining**: Traders pay fees and split between LPs and protocol stakeholders. Users can stake PREMIA tokens to collect fees and direct liquidity mining rewards.
4. **Vaults & OTC Liquidity**: Addresses challenges with granular options markets.
5. **Modular and Layered Protocol**: Designed for maximum composability and upgradability on top of the primitive base exchange layer.
6. **European-style Options Markets**: Enables the creation of European-style options markets for any asset pair with an on-chain spot price oracle.
7. **Range Orders**: Supports different types of range orders, such as Sell-with-collateral, Buy-with-shorts, Buy-with-collateral, and Sell-with-longs, each with specific functionalities.
8. **Margin System**: Using a risk-based model to assess user positions, blends attributes from traditional Reg-T and Portfolio Margin systems. Lending markets are established to provide capital to option underwriters. (Enabled at a later date - ETA Nov 23)


# Depot Layer (Vaults)

The Vault Layer in PREMIA V3 plays a crucial role in enhancing liquidity and capital efficiency within the options market. Here's a brief feature summary:

1. **Vaults for Passive Users**: Vaults enable passive users to participate in options markets automatically, market-making, and utilizing yield capture strategies created by Premia contributors and third parties. They can utilize standard range orders or the quote-based liquidity system to execute strategies, splitting returns across liquidity within the vault.
2. **OTC Liquidity & Market-Makers**: The over-the-counter (OTC) quote system allows vaults and market-makers to provide fillable option quotes to users, minimizing liquidity fragmentation. This system increases liquidity across strikes and maturities and enables professional market makers to optimize for both execution price and transaction fees.
3. **Liquidity Across Volatility Surface**: Specific vaults can provide liquidity across the entire volatility surface, decreasing fragmentation and increasing capital efficiency. Third-party providers can create vaults, enabling anyone to participate in strategy discovery and monetization. This enables a many-to-one relationship between vaults and pools.
4. **Integration with Base Exchange Layer**: The vault layer is built into the base exchange layer, addressing challenges with liquidity fragmentation across strikes and maturities. It provides just-in-time liquidity mechanisms to vaults and market-makers, enabling highly capital-efficient market-making for passive and active users.
5. **Volatility-Based Pricing**: Institutional traders can provide volatility-based quotes without paying EVM gas fees to manage on-chain liquidity positions.

The Vault Layer's design aims to simplify the complexity of pricing and strategy creation within option markets, making it more accessible to passive users while optimizing liquidity and capital efficiency. It's a key component in PREMIA V3's architecture, contributing to a more functional and efficient decentralized token options exchange.


# Messaging Layer (RFQ & OB)

The Messaging Layer or Over-the-Counter (OTC) Quote System in PREMIA V3 is a vital component designed to enhance liquidity and efficiency in the options market. It provides multiple functionalities and opportunities for integrations such as:

1. **Liquidity Provision**: Enables vaults or market-makers to provide fillable option quotes to users, either on-chain or off-chain. This minimizes the fragmentation of liquidity across the exchange.
2. **Just-In-Time Liquidity**: Offers just-in-time liquidity mechanisms to vaults and market-makers, allowing for highly capital-efficient market-making for passive and active users.
3. **Integration with Vaults**: Specific vaults can use the OTC quote system to provide liquidity across the entire volatility surface, further decreasing liquidity fragmentation and increasing capital efficiency.
4. **Volatility-Based Pricing**: Professional traders can provide volatility-based quotes to takers without incurring EVM gas fees for managing on-chain liquidity positions.
5. **Enhanced Liquidity Across Strikes & Maturities**: Increases liquidity across different strikes and maturities, enabling professional market-makers to optimize both execution price and transaction fees.
6. **Flexibility for Off-Chain Quotes**: Market-makers can provide quotes to users or aggregators off-chain, which can then be fulfilled through the exchange, even composable with range orders.
7. **Programmatic Trading**: The Messaging layer is available via the Premia Blue app, Typescript [SDK](/developer-center/sdk), and [API](/developer-center/apis/orderbook-api) (Auth Key & Docker for self-hosting).  This allows developers to integrate Premia V3 into their trading systems and algorithmic strategies.  For more information, see the [Developer Center](/developer-center/apis).

The OTC Quote System in PREMIA V3 bridges on-chain and off-chain activities, facilitating a more seamless and efficient trading experience. It is key in reducing liquidity fragmentation and enabling more sophisticated trading strategies.


# Fee Schedule

## Exchange Layer Fees

{% hint style="info" %}
Maker: A “maker” order is an order that adds liquidity to the order book. A maker order is not executed instantly but is placed on the order book or AMM. \
Taker: A “taker” order is an order that removes liquidity from the order book. A taker order is an order that is executed instantly against other orders upon submission.
{% endhint %}

| Fee Category           | Premia  | Deribit         |
| ---------------------- | ------- | --------------- |
| Maker Fee              | 0.00%   | 0.03%           |
| Taker Fee (AMM)        | 0.30%\* | -               |
| Taker Fee (Orderbook)  | 0.08%   | 0.03%           |
| Settlement Fee (Short) | Free    | Free            |
| Excercise Fee (Long)   | 0.30%\* | 0.015%          |
| Quoting Fee            | Free    | -               |
| Deposit Fee            | -       | Free            |
| Withdrawal Fee         | -       | Variable        |
| Multi-Leg (Combo)      | TBD     | Highest Fee Leg |

For more information on calculations, please see [Concepts>Fees](/the-premia-protocol/concepts/fees)

This is the current fee schedule on Premia V3 (active version) and is subject to change anytime.

\*This fee is capped at 12% of the Option's value.


# Differentiators

<figure><img src="/files/PV2SZofagQ53kQZ3ihq5" alt=""><figcaption></figcaption></figure>


# Concepts

## Overview

The Premia ecosystem is designed to be an open, accessible, and innovative platform for decentralized finance. This overview provides a glimpse into the technical concepts and core functionalities that power the system. Whether you're a developer, trader, liquidity provider, or just curious about how it all works, this section is for you. Where possible, corresponding inputs and function calls are provided.  For a complete list of function calls available, please reference [contracts](broken://pages/Ueo2itwYv9Fk9mVQVrvK).&#x20;

### LP Range Orders

Range orders allow LPs to deposit over specific price ranges defined by lower and upper price bounds. [**More Details**](https://docs.premia.blue/the-premia-protocol/concepts/lp-range-orders)

* **Range Order Basics**: Requires three primary inputs: lower price bound, upper price bound, and size of Collateral or Option Contracts.
* **Depositing Collateral or Options**: Defines the exposure as either buy or sell, with specific ask-side and bid-side liquidity rules.

### Trading

There could be up to 4 sources of liquidity for a given option. [**More Details**](https://docs.premia.blue/the-premia-protocol/concepts/trading)

* **AMM**: Allows traders to receive quotes for buying or selling options.
* **Orderbook/RFQ System**: Enables makers and takers to provide and fill quotes.
* **Vaults**: Unique contracts that follow specific strategies for trading.
* **External Protocols**: Allows other protocols to utilize the pools as a settlement layer.

### Orderbook & Request-for-Quote (RFQ)

The Orderbook architecture in Premia is unique and utilizes two separate chains: Arbitrum One and Arbitrum Nova. [**More Details**](https://docs.premia.blue/the-premia-protocol/concepts/orderbook-and-request-for-quote-rfq)

* **Arbitrum One**: The primary chain where all orders are filled, canceled, and positions settled/exercised. All collateral and approvals must be on Arbitrum One.
* **Arbitrum Nova**: Used to reflect the order book on-chain, ensuring a decentralized token options exchange. It helps prevent front-running or censorship of orders.
* **Providing Quotes**: Quotes are emitted events of order details signed by the maker. They can be emitted:
  1. Directly through the IOrderbookStream interface on Arbitrum Nova.
  2. Using the Premia Orderbook API, Premia will publish the quote on the maker's behalf.
* **Access**: The order book can be accessed via the Premia Blue app, API, or SDK.

### Fees

The Premia V3 protocol has a structured fee system, including trading and pool initialization fees.  [**More Details**](https://docs.premia.blue/the-premia-protocol/concepts/fees)

* **Trading Fees**: Paid by traders taking liquidity (takers), split between LPs (makers) and protocol stakeholders. Calculated as the maximum of 3% of the total premium or 0.3% of the size. These fees can be claimed at any time.
* **Pool Initialization Fee**: Pool creation is permissionless and fee-based. The fee is dynamic and incentivizes users to initialize ATM pools (At The Money) and near-dated. Discounts are provided for specific expirations or strikes that create spread trading opportunities. Example: Initializing a 50 Delta option with 14 days expiration would cost $25.
* **Permissionless Pool Creation Bounds**: To prevent fragmentation, pools can only be created for common strikes and expirations. The maximum expiration is 365 days, with specific rules for expiration timing.
* **Oracle Support**: Premia v3 supports Chainlink oracles, Uniswap v3 pairs, or custom Oracle solutions.

### Exercise & Settlement

The exercise and settlement process within the Premia protocol is designed to be straightforward and flexible. [**More Details and Examples**](https://docs.premia.blue/the-premia-protocol/concepts/exercise-and-settlement)

* **Exercise**: Both call and put options can be exercised at any time after the option's maturity date. The payoff is locked to the intrinsic value if the option is In The Money at maturity.
* **Settlement**: Short option holders can claim the remaining collateral value after expiration. There's no penalty for late exercise or settlement.
* **Auto-Settlement**: Expired options can be exercised or settled by any approved user after expiration, with compensation for gas spent on settlement.
* **Settlement Price**: Determined via spot price oracles.

### Margin (Under Construction)

### Oracles (Under Construction)

### Liquidity Mining

Premia's liquidity mining is significantly changing, replacing traditional token liquidity mining with Premia Call Options. [**More Details**](https://docs.premia.blue/the-premia-protocol/concepts/liquidity-mining)

* **Discounted Call Options**: Liquidity providers will receive PREMIA Call options at a 45% discount to the underlying asset's current market price, replacing the existing liquidity mining scheme.
* **Proceeds Distribution**: If exercised, approximately 90% of the proceeds will circulate to vxPREMIA staking users, with the remaining 10% directed to Blue Descent (DAO).
* **Unexercised Options**: If not exercised, 20% of the option's intrinsic value will be locked for 1 year and then provided to the liquidity provider's wallet.
* **Fees**: Protocol Fees will be collected on exercise, and taker fees will be collected if the option is traded on the secondary market.
* **Modular Design**: Built modularly, allowing any market to be deployed as a physically settled option.  Premia encourages other protocols to reach out if they want to implement call options for their incentive programs.

### Advanced Exchange Concepts (Under Construction)

### Vaults / Depot

Premia Vaults, originally named "Meta-Vaults," are designed as passive liquidity vaults to enable users to use the current meta for options. They are meant to be used by traders and yield seekers to maximize returns and risk-management success in DeFi. [**More Details**](https://docs.premia.blue/the-premia-protocol/concepts/vaults)

**Premia v3 Vaults**

* **Margin Pool**: A Premia Vault created in-house to provide leverage to sell-side options on The Premia Protocol. It enables lenders to earn interest relative to their risk and option sellers to maintain lower capital requirements.
* **Other Vaults**: Includes the well-known C-Level Vault (Premia V2 Sell-Side Pools) and Knox Vaults, implementing option selling strategies for passive income. More composable Vaults, including Market-Making implementations, are planned for the future.

**3rd Party Vaults**

* **Permissionless Creation**: Anyone can create Vaults to deploy strategies utilizing the Premia Protocol.
* **Contributor Program**: A future program to showcase Third-party Vaults on the Premia Interface, benefiting both Premia and vault creators.

Premia Vaults are a key feature of the Premia ecosystem, offering diverse strategies and opportunities for in-house and third-party developers. They reflect financial markets' competitive and strategic nature, providing tools to optimize for specific environments or rulesets.


# LP Range Orders

## <mark style="color:blue;">Overview</mark>

Range orders are at the core of concentrated liquidity, they allow LPs to deposit over a specific price range defined by a *lower price bound* and *upper price bound*. Orders that span the minimum price width can replicate limit orders similar to orders placed on a limit order-book (if only crossed a single time), while orders spanning across multiple price points (called *ticks*) replicate orders placed *linearly* over multiple adjacent prices. There is no commitment period for LP deposits. They can be withdrawn prior to expiration.

Premia v3 uses an accounting method called *Split-User Accounting*. At the core, this accounting process allows LPs to define directional exposure of a range order. This is automatically determined based on the asset that is deposited (Collateral or Option Contracts) along with the orientation of the order relative to the current market price. Simply put, range orders provide *uni-directional* exposure (either buy **or** sell). More information about how *Split-User Accounting* works can be found in Section 4 of the Premia v3 whitepaper [here](https://premia.finance/v3.pdf).

## <mark style="color:blue;">Range Order (Basics)</mark>

In order to define a range order, 3 primary inputs must be provided to the `deposit` function in the `IPool` interface:

* <mark style="color:orange;">Lower Tick</mark> ⇒ lower price bound
* <mark style="color:orange;">Upper Tick</mark> ⇒ upper price bound
* <mark style="color:orange;">Size (liquidity)</mark> ⇒ size of Collateral OR Option Contracts

{% hint style="info" %}
To find the pool address, users can query the `getPoolAddress` function in `IPoolFactory`.
{% endhint %}

When liquidity is deposited above the market price, this order can be initially viewed as *<mark style="color:red;">ask-side liquidity</mark>*. Similarly, deposits below the market price can be initially viewed as *<mark style="color:green;">bid-side liquidity</mark>*. As the market price moves up and down through a range, the liquidity provider collects maker fees, in addition to any exposure changes.

<figure><img src="/files/pJ9Y02HBu92zTO3A3RrD" alt=""><figcaption></figcaption></figure>

### Depositing Collateral

If an LP deposits collateral, they are suggesting that they would like to get *long* option contracts if they are posting a bid-side range order and *short* contracts if they are posting an ask-side range order. These range orders can be thought of as “buy-to-open” or “sell-to-open” order types initially. As the market price traverses through these range orders, they will become “sell-to-close” and “buy-to-close” range orders respectively.

{% hint style="info" %}
An ask-side range order with collateral can never be net *long* options just as a bid-side order with collateral can never be *short* options.
{% endhint %}

### Depositing Option Contracts

If an LP deposits option contracts, they are suggesting that they would like to close their positio&#x6E;*.* Bid-side orders can be made with short option contracts, and Ask-side orders can be made with long option contracts. These order types can be thought of as “buy-to-close” and “sell-to-close” order types initially. As markets traverse back and forth through these range orders, an LP may re-establish the original option exposure they deposited with.

{% hint style="info" %}
An ask-side range order with *long options* can never get net short options. A bid-side order with short options can never get net long options.
{% endhint %}

## <mark style="color:blue;">Range Order (Detailed)</mark>

It is best to illustrate a detailed view of a range order through an example. Here, we will be focusing on a range order with the following details:

* <mark style="color:orange;">Option type</mark> ⇒ Call Option
* <mark style="color:orange;">Current Market Price</mark> ⇒ 0.35
* *<mark style="color:orange;">Initial</mark>* <mark style="color:orange;"></mark><mark style="color:orange;">Range Order Type</mark> ⇒ *bid-side liquidity*
* <mark style="color:orange;">Lower Tick</mark> ⇒ 0.25
* <mark style="color:orange;">Upper Tick</mark> ⇒ 0.30
* <mark style="color:orange;">Deposit</mark> ⇒ 1 Unit of Base (Underlying) Asset as collateral

As the price of the option moves *down* (right to left), the collateral which was initially deposited (1 unit) begins to decrease (transferred to takers) as the market price enters and traverses through the order range. The collateral is used to purchase *long* option contracts from traders.

Once this order is fully traversed (ie. market price is now 0.20), the range order consists of 3.63 options and 0 collateral. Note, any fees collected are not part of the collateral balance and are separately redeemable. At this point, the order is considered sell-side liquidity, which consists of Option Contracts that will be sold to collateral if the price of the option were to go up (left to right).

It is worth noting that pricing is linear, which means the average execution price of a range is simple `(Upper Tick + Lower Tick)/2`. In this example of a sell-side order, the average execution price is 0.275.

<figure><img src="/files/nWBmhTYRDrSReBcsH797" alt=""><figcaption></figcaption></figure>

### Range Order Width

$$
RangeWidth = upperTick -lowerTick
$$

While the minimum tick precision for a market is 0.001, a range order must have a compatible *RangeWidth*.  Since liquidity for a range order is distributed evenly in between the ticks of a range order, it is possible to generate rounding errors using certain range widths.   While this is automatically handled on the front end to prevent bad order ranges, care must be taken for direct interaction with smart contracts to abide by

A valid *RangeWidth* for *any* order type must be one of the following values:

```
ValidRangeWidths = [
  0.001, 0.002, 0.004, 0.005, 0.008, 0.01, 0.016, 0.02, 0.025, 0.032,
  0.04, 0.05, 0.064, 0.08, 0.1, 0.125, 0.128, 0.16, 0.2, 0.25, 0.256, 
  0.32, 0.4, 0.5, 0.512, 0.625, 0.64, 0.8
]
```

#### Example:

A deposit of 1 unit of collateral (ie. WETH) for bid-side liquidity is desired. The lower tick is  .001 and corresponding upper tick is .004 (*RangeWidth* = 0.003). This would mean that 1/3 of the liquidity would be distributed across each of the 3 ticks within the range.   This produces rounding errors that are undesirable even with 18 decimal places of precision for most ERC-20 assets. &#x20;

## <mark style="color:blue;">Range Order (Technical) - Deposits</mark>

### The Position.Key struct

In order to directly process a range order `deposit`, a position `Key` struct must be passed in. This can be found in the `Position` library. Here, a user can specify both an `owner` and `operator` addresses for the position. This is primarily intended for 3rd party integrations, otherwise both will be the user’s address.

Additionally, a user will specify the `lower` and `upper` ticks for their range order and define the order using the `OrderType` enum as follows:

`uint8` <mark style="color:yellow;">0 → CSUP (Collateral ↔ Short, Use Premiums)</mark> - Convert collateral to short exposure or vice versa and use the premiums towards collateral requirements (fully filled spends any premiums collected).

`uint8` <mark style="color:yellow;">1 → CS (Collateral ↔ Short)</mark> - Convert collateral to short exposure or vice versa and collect (pay) premiums separately (fully filled retains all premiums collected).

`uint8` <mark style="color:yellow;">2 → LC (Long ↔ Collateral)</mark> - Convert collateral to long exposure or vice versa and pay (collect) premiums separately (fully filled spends all collateral as premiums).

### Finding belowLower and belowUpper Ticks

Providing the `belowLower` and `belowUpper` tick values can easily be done by first calling `getNearestTicksBelow` view function with the `lower` and `upper` of the Position to be deposited. The pool will verify that the ticks are in the correct location before inserting and confirming the deposit. The following relationship is verified:

$$
belowLower <= lower <= belowLower.right \\
belowUpper <= upper <= belowUpper.right
$$

{% hint style="info" %}
The insert location is not searched for within each `deposit` transaction, because of the gas costs associated with inserting into the [doubly linked list](https://en.wikipedia.org/wiki/Doubly_linked_list) of ticks. By first finding the nearest ticks for the function off-chain (view function) and then verifying correctness on-chain, users can significantly reduce transaction costs per `deposit`.
{% endhint %}

### Determining minimum and maximum market price

In addition to `belowLower`, `belowUpper`, and `size`, users must also supply a `minMarketPrice` and `maxMarketPrice` when directly interacting with the `deposit` function. Market price here refers to the *option’s* price. By specifying a min/max market price for the option, LPs can get granular control of the composition of asset(s) that are used for collateral. It can be thought of as slippage control for asset composition.

These slippage controls are primarily helpful for orders that are intended to be solely *bid-side* or *ask-side* liquidity with a **single** collateral type (option **OR** collateral). When LPs hold a mixture of options and collateral in their wallet, there is risk of using an unintended collateral type if a range order is placed close to the market price.  It is possible for a single sided range order to be an *unintended straddle* (more on straddles below). This risk can be prevented by correcting defining the `minMarketPrice` and `maxMarketPrice` parameters.

{% hint style="info" %}
If no slippage controls are desired, the values can be set to the minimum and maximum tick for a pool.
{% endhint %}

### Range Orders that straddle market price

It is possible to initialize a range order that *straddles* the current market price. This would mean `Lower *Tick < Market Price < Upper Tick*`. In this case, a deposit will need to consist of **both** options **AND** collateral (linearly interpolated based on the core order inputs and market price).

Setting the `minMarketPrice` and `maxMarketPrice` to a narrow range ensures the composition of the order is within a user’s tolerance.

### Unintended Straddle Example

Let’s imagine for example an LP holds ETH and short options in their wallet. Their intention is to create a *bid-side* range order to close the existing short exposure in the price range of 0.4 ↔ 0.5. The range is set just below the current market price of 0.55 (Upper Tick < Market Price). In the process of creating the range order, the market price moves down to 0.45, *into* the LP’s order range (thus creating an unintended straddle).

In this case, the `deposit` function would seek a small portion of the LP’s ETH and leave behind a small portion of the short option contract in the user’s wallet, to correctly open the position.

Setting the `minMarketPrice` to the Upper Tick (0.5) would cause the transaction to revert if price moved below 0.5, allowing the LP to adjust the range order and re-submit. In this example `maxMarketPrice` is trivial, but still requires a value greater than or equal to the market price at time of deposit.

## <mark style="color:blue;">Range Order (Technical) - Withdraws</mark>

Withdrawing a range order is very similar to a `deposit`. The only difference is that `belowLower` and `belowUpper` are NOT required function inputs, as no linked list insertion is required. The `minMarketPrice` and `maxMarketPrice` parameters are still used to manage slippage and collateral control as mentioned in [Range Order (Technical) - Deposits](#range-order-technical-deposits).


# Trading

## <mark style="color:blue;">Overview</mark>

Long (short) options are represented as an [ERC-1155 token](https://eips.ethereum.org/EIPS/eip-1155) in a wallet. It allows any EOA or Contract address to easily transfer, trade, or exercise (settle) the option at a future time. When taking liquidity from any source, a transaction fee will need to be paid. More details on fees can be found [here](/the-premia-protocol/concepts/fees#trading-fees).

While all options settle within their respective pools, it’s possible to interact with *multiple* sources of liquidity for the same option. Users of the [Premia Interface](/#the-premia-interface) or Premia v3 SDK will have easy access to the best quotes from each source. Please see here for more details about receiving a quote.

There could be up to 4 sources of liquidity for a given option:

1. AMM - Range Orders
2. Orderbook / RFQ System
3. Vaults
4. External Protocols / Third Parties

Interacting with the [AMM](#amm) and [Orderbook / RFQ](/the-premia-protocol/options-on-premia/order-book-vs.-amm) System can be done directly via the `IPool` interface while [Vaults](/the-premia-protocol/concepts/vault-depot) and [External Protocols](#external-protocols-third-parties) would involve directly corresponding with their contracts or interfaces if not available on the Premia Interface or Premia v3 SDK.

## <mark style="color:blue;">AMM</mark>

Traders (takers) on the Premia v3 exchange can receive a quote to buy (sell) an option from LPs in an option pool at the given quote price using `getQuoteAMM`. If the taker deems the quote acceptable, they can `trade` the option and pay (receive) a premium in addition to receiving long (short) option contracts in the form of [ERC-1155 tokens](https://eips.ethereum.org/EIPS/eip-1155).

The trade function has 3 inputs: `size`, `isBuy`, and `premiumLimit`. The `size` parameter refers to the order size, `isBuy` is a boolean to signify trade direction, and `premiumLimit` is used for slippage control. If an order trades beyond the `premiumLimit`, ie. the average execution price of a buy (sell) order is above (below) the `premiumLimit`, the transaction will revert.

{% hint style="info" %}
The difference between a pool’s current `marketPrice` and `getQuoteAMM` in the `IPool` interface is the *price impact* of a potential trade. This is a function of market liquidity and order size, where more a higher ratio of order size to existing liquidity will result in a higher price impact and vice versa.
{% endhint %}

It is possible to pay/receive premium/collateral for an option in the token of a user’s choice. This requires the user to define their swap parameters in the form of *calldata*, which will enable the swap to be executed on-chain before or after the necessary action to convert a token. The `swapAndTrade` and `tradeAndSwap` functions on each AMM pool can be used to facilitate this feature. More details can be found in the `IPool` interface within the Contract section.

## <mark style="color:blue;">Orderbook / RFQ System</mark>

### Makers

Market Makers can provide quotes to the Orderbook either via [Orderbook API](/developer-center/apis/orderbook-api) (off-chain) or on-chain via  `add` within the `IOrderbookStream` interface. An on-chain event is emitted with the details of each order. This acts as a transparent/capital efficient database for orders. Off-chain indexers can track the state of the Orderbook through these events.

A quote will have several parameters, among them a `deadline`. The deadline will specify how long a quote will be valid for.  Alternatively, orders can be cancelled using `cancelQuotesOB` in the `IPool` Interface if an order needs to be cancelled before the deadline is reached.  Multiple quotes can be cancelled at once by passing a list of quotes.  Cancelling quotes can only be done on-chain.&#x20;

### Takers

While takers will *fill* their order on-chain, the process of *getting* a quote is done off-chain via the [Orderbook API](/developer-center/apis/orderbook-api).   We index all quotes in our subgraph, which users can get from the [Orderbook API](/developer-center/apis/orderbook-api). &#x20;

Once a taker has a quote they would like to fill, the order details need to be passed on-chain. The [fillQuoteOB](https://docs-solidity.premia.finance/contracts/pool/IPoolTrade.sol/interface.IPoolTrade.html#fillquoteob) function can be used to fill a quote using the `IPool` Interface.

Traders can verify if a quote is still valid in the Orderbook by calling [isQuoteOBValid](https://docs-solidity.premia.finance/contracts/pool/IPoolTrade.sol/interface.IPoolTrade.html#isquoteobvalid) with the same inputs as [fillQuoteRFQ](https://docs-solidity.premia.finance/contracts/pool/IPoolTrade.sol/interface.IPoolTrade.html#fillquoteob). It is also possible to check the fill status of a quote by using [getQuoteOBFilledAmount](https://docs-solidity.premia.finance/contracts/pool/IPoolTrade.sol/interface.IPoolTrade.html#getquoteobfilledamount).

More details on how the orderbook architecture can be found in Advanced Concepts under [Orderbook & Request-for-Quote (RFQ)](/the-premia-protocol/concepts/orderbook-and-request-for-quote-rfq)

## <mark style="color:blue;">Vaults</mark>

Each vault will have its own unique contract and functions, however, each must implement the `IVault` interface to be integrated in the [Premia Interface](/#the-premia-interface) and [Premia V3 ](#user-content-fn-1)[^1]SDK. If a third party vault correctly implements the `IVault` interface, it is eligible to be added to the V3 Vault Registry, which means its quotes will be automatically included in platform-wide quote streams.

Vaults need to implement the `getQuote` function, allowing users to request the vault’s price for a specific option (`strike`, `maturity`, `isCall`), including trade `size` and direction (`isBuy`). The vault should return both the `maxSize` and `price` for the trade, including a `maxSize` of 0 if the option is not offered by the vault. To enable quotes to be filled, vaults should implement the `trade` function with the same parameters as the `getQuote` function.

In addition to implementing the above functions, vaults will additionally need to emit an `UpdateQuotes()` event (with no parameters) any time the vault’s quotes change, in order for the Premia Interface and Premia v3 SDK to track quote changes.

Anyone interested in learning more about developing vaults on top of Premia v3, [Reach out](broken://pages/0CmqAVOe2KapHYrbKaVr#media-kit) to build with us!

## <mark style="color:blue;">External Protocols / Third Parties</mark>

It is entirely possible for other protocols/users/vaults to utilize the pools strictly as a settlement layer and exchange options outside of Premia. To be able to do this, the `writeFrom` function can be used.

`writeFrom` is a method that will mint both the long and short option, and send each to the designated addresses for `underwriter` and `longReceiver`. In order to invoke this function, the collateral for the short position must be provided. Using the `writeFrom` function will incur a transaction fee equal to 0.3% of the notional value:

$$
Minting:Fee = 0.003*Size*Collateral
$$

Collateral is 1 for calls and the strike price for puts. In other words, the minting fee here is denominated in the collateral of the option.

[^1]:


# Orderbook & Request-for-Quote (RFQ)

## <mark style="color:blue;">Arbitrum One vs. Arbitrum Nova</mark>

The Orderbook architecture is unique in that *two* separate chains are utilized. The primary chain is [Arbitrum One](https://arbitrum.io/). Just like the v3 protocol, it's the primary chain where all orders are filled, cancelled, and positions settled/exercised.   This functionality can be accessed using the `IPool` interface, which resides on Arbitrum One, or via the Premia Blue app. Users of the Orderbook must have a valid address on Arbitrum One. All collateral and approvals to transfer collateral must be on Arbitrum One.&#x20;

{% hint style="info" %}
Why Arbitrum Nova? To be a true decentralized tokens options exchange, Premia believes the order book should also be decentralized so that all parties can ensure their orders are not being front ran or censored. A centralized off-chain order book may be subject to unwanted behaviors; thus, Premia decided to use Arbitrum Nova due to its low cost and fast transaction speeds to reflect the order book on-chain.
{% endhint %}

Providing *quotes* for the order book are done through [Arbitrum Nova](https://nova.arbitrum.io/).  Quotes are nothing more than emitted events of order details that are signed by the maker of a transaction that will ultimately process on Arbitrum One.   There are two primary ways to emit quotes to the order book:

1. Directly through the `IOrderbookStream` interface using `add`.  This contract resides on Arbitrum Nova and requires a maker to have an account with an ETH balance to pay for gas fees. &#x20;
2. Using the [Premia Orderbook API](/developer-center/apis/orderbook-api),  Premia will publish the quote on Arbitrum Nova on the maker's behalf.   This is a rate-limited / tiered feature.

{% hint style="info" %}
These orders do **not** earn maker rebates or liquidity mining rewards, ensuring concentrated liquidity and vaults stay competitive long-term.
{% endhint %}

The order book can be accessed directly via the Premia Blue app, [API](/developer-center/apis/orderbook-api), or the [SDK](broken://pages/3n1ds7vUC0e0NZlG3fOk). &#x20;


# Fees

## <mark style="color:blue;">Trading Fees</mark>

Transaction fees are paid by traders taking liquidity (takers) and split between LPs (makers) and protocol stakeholders at a rate determined by governance. To retain higher composability, transaction fees are accumulated separately and not compounded back into LP positions.

The trading fee is calculated as follows:

$$
Trading:Fee = max(0.03*Total:Premium,: 0.003*Size)
$$

$$
Total:Premium = Option:Price \* Size
$$

{% hint style="info" %}
NOTE: Trading Fees are claimable at *any* time by calling the `claim` function on the `IPool` interface.
{% endhint %}

## <mark style="color:blue;">Pool Initialization Fee</mark>

Pool creation is *permissionless\* **and fee based. The fee is dynamic and incentivizes users to initialize pools that are ATM and near-dated, as they are the cheapest to create. Additionally, discounts are provided for specific expirations and/or strikes that have not been initialized that would create spread trading opportunities. The formal math behind how this is determined can be found in Appendix A.2 of the*** [Premia v3 whitepaper](https://premia.finance/v3.pdf)***.***

The fee for a pool initialization can be queried from the `IPoolFactory` interface using the initializationFee method. As a basic example, if a user wanted to initialize a 50 Delta option with 14 days to expiration, the fee to do so would be $25.

**NOTE: Permissionless Pool Creation Bounds**

In order to prevent excessive fragmentation and ensure maximum composability with other option markets, pools can only be created for common strikes and expirations.

<mark style="color:orange;">Strikes</mark> are algorithmically limited to common values (log-rounded). The formal math behind how this is determined can be found in Append A.1 of the [Premia v3 whitepaper](https://premia.finance/v3.pdf).

The maximum <mark style="color:orange;">expiration</mark> an option can be created with is 365 days out. Options will all expire at 8AM UTC, with all options over 7 days to maturity expiring on a Friday. All options past 30 days must expire on the last Friday of the month.

Additionally, a spot market needs a valid <mark style="color:orange;">oracle feed</mark> for the token pair (ie. ETH/USDC). Premia v3 has out-of-the-box support for any Chainlink oracle, Uniswap v3 pair, or custom oracle solution that implements the `IOracleAdapter` interface.


# Exercise & Settlement

When a user is long (or short) an option, they **can `exercise` (or** `settle`**)** their option from the `IPool` interface **at any time after the option’s maturity date**. If at the time of maturity, an option is [*In The Money*](https://www.investopedia.com/ask/answers/042715/what-difference-between-money-and-out-money.asp), **the payoff is locked to the intrinsic value and can be claimed at any time post-maturity by the owner of the long option. Short option holders can also claim the remaining value of collateral any time after expiration.** There is no penalty for late exercising or settlement.

{% hint style="info" %}
**Expired options can be exercised or settled by any approved user after expiration, if enabled by the option holder. The address settling the option will be compensated in return for the gas spent on settlement, up to the maximum fee set by the option holder in advance, in order to maintain self-sustaining auto-settlement.**
{% endhint %}

## <mark style="color:blue;">**Exercise/Settlement of a PUT option**</mark>

If at the time of maturity, the price of the underlying asset is lower than the breakeven price, a put option is considered **In The Money**. In this case, the option owner (long the option) is entitled to the payoff, which is equal to the strike price of the underlying minus the spot price. This difference is calculated automatically and settled **in cash** (the quote token) to the option buyer. The option underwriter (short the option) is charged against their collateral held.

<mark style="color:orange;">**Example:**</mark>

An user buys a 2 ETH/USDC put option, at a strike price of 3,000 USDC. At the time of exercise, the ETH price is 2,700 USDC. The user receives the difference between the strike price and the spot price (3,000 - 2,700), multiplied by the amount of options they own (2). In this case, the user receives 600 USDC on exercise. The counter party who is short the option must settle their position. They will 2,700 USDC for each option they were short (in which they provided 3,000 USDC as collateral).

## <mark style="color:blue;">**Exercise/Settlement of a CALL option**</mark>

If at the time of maturity, the price of the underlying asset is higher than the breakeven price, a call option is considered **In The Money**. In this case, the user is entitled to the payoff, which is equal to the strike price of the underlying minus the spot price. This difference is calculated automatically and settled **in the underlying asset** (the base token) to the option buyer.

<mark style="color:orange;">**Example:**</mark>

A user buys a 2 ETH/USDC call option, at a strike price of 3,500 USDC. At the time of exercise, the ETH price is 4,000 USDC. User receives the difference between the strike price and the spot price (4,000 - 3,500), multiplied by the amount of options they own (2). In this case, the user is entitled to 1,000 USDC, which is settled in ETH. Thus the user receives (1,000 / 4,000 ETH) = 0.25 ETH on exercise.

## <mark style="color:blue;">Settlement Price (Oracle Feed)</mark>

Determining the settlement price is done via spot price oracles. In order to find out how the spot price is determined, please see here.


# Margin

## <mark style="color:blue;">Overview</mark>

Margin in of itself is a type of vault. It is built *on top* of the base layer. This segregation from the base layer insures solvency and ability to guarantee payout as a settlement engine. Users who choose to utilize margin must do so through the margin vault. This experience is simplified for users of the Premia Interface or Premia v3 SDK. One of the major differences between using margin and using the base layer is that positions held by users on the base layer can be withdrawn and freely moved. Conversely, positions that utilize margin can not be withdrawn.

The margin vault contains a blend of attributes from traditional Reg-T and Portfolio Margin systems that provide *sell-side* leverage. A risk-based model is used to assess user positions in an isolated fashion (per-position). In order for the base layer to always remain solvent, margin users must borrow capital from pool lenders, which is then used to *fully collateralize* the exposure on the base layer.

Borrowers are in “first-loss” position relative to the lender. This means all losses incurred on a position are debited from a borrow before the lender takes on any risk. All profit is retained by the user borrowing capital, less capital usage fees (interest).

## <mark style="color:blue;">Providing Liquidity as a Lender</mark>

Lending markets are established exclusively for the purpose of providing capital to option underwriters, where each collateral type (eg. ETH, WBTC, USDC) has its own margin lending pool.

When depositing capital into a margin pool, each lender must select a deadline on which their capital is to be returned. A lender's capital can be borrowed at any time before the deadline (or indefinitely if no deadline is set). For example, if a lender's deadline is 30 days from now, this implies the lender's capital will be available for up to the next 30 days, and will only be used for options that expire between the current time and the deadline.

Any lender capital utilized in an option position is locked for up to the expiration of the position. Upon borrowing, a borrower pays an upfront interest-based commitment fee based on the utilization of the total available capital in the pool, up to the option's expiration. When a borrower successfully closes a position, each lender's capital is unlocked and immediately made available for further lending or withdrawal. At any time, lenders may withdraw any of their capital that is not being utilized in the pool.

A lender's capital may be utilized for multiple options, so long as each expiration date is prior to the lender's deadline. All lenders for a specific expiration share in lending fees pro-rata. Additionally, lenders split principal risk of liquidated option positions, if and only if the Reserve Fund (discussed [below](#reserve-fund)) cannot fully cover losses. When a lender's deadline is passed, their capital will be reserved for withdrawal and will no longer be available to be borrowed for margin.

If a borrower closes a position before maturity, they will be rebated with commitment fee claim tokens, enabling the user to claim any potential commitment fees generated by the returned capital, if borrowed again by another user prior to maturity.

## <mark style="color:blue;">Selling on Margin</mark>

### Lending Fee

In order to sell on margin, a user must borrow funds so that the position is fully collateralized. Borrowing these funds requires paying interest. Interest is payed *up-front when a trade is opened.* Any interest left over (ie. a position is closed before expiration) is credited back to the trader upon closing the trade in the form or rebate claim tokens, which do **not** affect lender returns. The lending fee sits between the prevailing risk-free rate, `R` and `R + .05`. The amount of reserves relative to the amount of margined open interest determines where the interest rate will be. In other words, the more risk the lenders are potentially exposed to, the higher the interest rate charged up to 5% over the risk-free rate.

For example, if there is 100 ETH in the ETH Reserve Fund, the first 100 short option positions opened on margin will borrow at the risk free rate. This is because there is no risk of loss to the lenders as any loss will be covered by the reserve fund. As the risk of loss to lenders becomes non-zero (the reserve fund capital becomes exposed), the interest rate will traverse to 10% to cover the risk of potential loss of their funds (as risk is transferred to lenders).

<figure><img src="/files/wGKWsEgBH8q1eHKL1kp5" alt=""><figcaption></figcaption></figure>

### Min Margin

Minimum Margin is the least amount of collateral a position needs to maintain before it will be liquidated. It is important to know that this is a *dynamic* number and will change over the life of a margined position based of several factors.

### Dynamics of Min Margin

<mark style="color:orange;">Time</mark> → As a function of time (all else equal), the Min Margin will *decrease* as an option gets closer to expiration.

<mark style="color:orange;">IV</mark> → As a function of IV (all else equal), the Min Margin will *increase* when an option’s IV increases.

<mark style="color:orange;">Price</mark> → As a function of price (all else equal), the Min Margin will *increase* when an option’s price increases.

{% hint style="info" %}
Under volatile market conditions, it is possible for margin to become temporarily unavailable for a given market (or option). If this were to happen, all positions that were opened using margin must be fully collateralized by users (or closed); otherwise positions will be liquidated. More technical details on the calculation method can be found in the [whitepaper](https://premia.finance/v3.pdf) under section *6 Margin*.
{% endhint %}

At all times a user can monitor the Minimum Margin requirement for a given position and in the future, users will be able to set alerts directly on the Premia Interface to avoid liquidation.

### Initial Margin

Initial Margin is the minimum amount of collateral that must be provided by a user in order to open a *new* short option position using margin. It is set to 1.5x the Min Margin. This ensures users have a substantial risk buffer before a position can be liquidated, once it is opened.

## <mark style="color:blue;">Liquidation</mark>

Liquidations do not instantly occur automatically on-chain. One of the of the major challenges with on-chain liquidation is price distortion, which is a function of liquidity. The less liquidity there is in a given market, the more it will be impacted by a liquidation event creating negative feedback loops. To solve for this, we’ve implemented a Reserve Fund structure (discussed [next](#reserve-fund)), which will help prevent negative feedback loops and can offset risk exposures for lenders as it grows.

### Liquidation Trigger

Anyone can liquidate an at-risk position on-chain and collect a liquidation fee for doing so. The liquidator does *not* take on position exposure. They merely act as a keeper, monitoring for positions that can be liquidated, and invoking the `liquidate_position` function for LP exposures and `liquidate_trade` for taker positions.

### Liquidation Fee

The fee that is rewarded to a liquidator is 0.3% of the total position value (capped at $10k USDC equivalent).

### Liquidated Positions

Liquidation events merely transfer ownership from the trader to the reserve fund. The position is then held by the reserve fund until expiration. *Traders who are liquidated lose their collateral (Minimum Margin) upon liquidation. Funds forfeited by the trader are then used to offset any potential loss.*

{% hint style="info" %}
&#x20;*Any additional funds left after expiration are allocated to the reserve fund to cover future potential losses.*
{% endhint %}

### Determining Market Value

Liquidations are determined based on an IV oracle which seeks to establish the fair market value of an option at any given point. This means that liquidations are not effected by pool prices. This has the added benefit of not triggering erroneous liquidations due to price wicks on the exchange. For further details on the IV Oracle, please see [here](/the-premia-protocol/concepts/oracles#iv-oracle).

## <mark style="color:blue;">Reserve Fund</mark>

Collateral in the Reserve Fund is meant to absorb the profit-or-loss of liquidated positions. Since lenders only provide capital to option positions that have times to maturity less than their deadline, the margin system is able to settle positions and abstract profit-or-loss variance from lenders before they are able to request a withdraw. *Simply stated, the Reserve Fund is in a first-loss position against lenders' principle.* Additionally, it is capable of distributing excess reserves as supplementary yield to lenders, akin to dividend payouts. If the Reserve Fund were to ever be insolvent, lenders' principle *could* be exposed pro-rata to loss on liquidated positions.

{% hint style="info" %}
&#x20;Keep in mind, as the Reserve Fund’s available capital decreases, the interest rate provided to lenders (required to borrow additional capital) may increase (if not already at the ceiling rate) to compensate for additional potential risk.
{% endhint %}

In the event that reserve funds can not completely cover all (potential) losses, they are utilized in order of option expiration first. For options that have the same expiration, options are settled with reserve assets on a *first-come, first-settle basis*.


# Oracles

## <mark style="color:blue;">Price Feed Oracles</mark>

### Price Feed Overview

In order to create an options market for a given token pair, a valid oracle must be available to determine the value of an option (based on spot price) at expiration. Premia v3 pools can be established out-of-the-box with Chainlink VWAP Price feeds, RedStone Classic TWAP price feeds or Uniswap v3 TWAP Price feeds. Additionally, any Price Oracle implementing the `IOracleAdapter` interface can be used to initialize a new option pool.

By default, options will be automatically settled by an address maintained by the protocol, but Option holders can at any time designate an `autoSettleAddress` and an `autoMaxSettleFee`. Once set, the `autoSettleAddress` can exercise or settle options for the user after expiration, and be given a credit to compensate for the gas fees associated with making the call.

For convenience a keeper bot is then used to hydrate each pool with its corresponding settlement price if the option has expired. However, this value can also be populated within each pool by *any* user who calls the `exercise` or `settle` functions.

### Chainlink

Chainlink has many available feeds which can be found [here](https://docs.chain.link/data-feeds/price-feeds/addresses?network=arbitrum). If a direct pair is not available when a pair is upserted to the `ChainlinkAdapter`, an attempt will be made to combine multiple price paths to create a valid price feed.

To *initialize* a pool, Chainlink is queried with the selected pair, and if a valid market exists, a VWAP price is returned to help determine the `initializationFee`.

### RedStone

RedStone is a Modular Oracle delivering token pricing by fetching price feeds from off-chain sources (CEXes, aggregators) and on-chain sources (DEXes).&#x20;

Its support for all EVM-compatible Layer1s and Layer2s, a lot of customization options (TWAPs, exact pricing at the time of settlement), and multiple available data feeds (long-tail, LP, LST, and Ecosystem-native tokens, as well as custom feeds) offer an advantage to Premia for new markets creation and cross-chain expansion.

For a comprehensive understanding, please refer to the [RedStone Documentation](https://docs.redstone.finance/docs/introduction).

#### Determining Settlement Price

Ideally, the settlement price of *any* option would be determined by the spot price that corresponds exactly to 8AM UTC. If a price is *not available* at this timestamp, there are several actions that are taken to determine the most appropriate price:

1. A valid price *nearest* to 8AM UTC on the expiration date is queried. This may end up being at or *before* 8AM UTC.
2. If the last price update is more than 25 hours before expiration, the pool will go into a holding state until a fresh price update is received. In the event the oracle is unavailable for an extended period, a price override may be applied via governance to release the pool from the holding state

### 3rd Party Oracles

Any price feed that implements the `IOracleAdapter` smart contract interface can be used to initialize a new pool. However, only well-established price feeds will be shown directly to users on the Premia Interface or using the Premia v3 SDK.

## <mark style="color:blue;">IV Oracle</mark>

<mark style="color:red;">\<UNFINISHED SECTION SEE NOTES BELOW></mark>

Pending a change to amberdata instead of Deribit

* ESSVI → model derived from Deribit data (subject to change)
* Used for → Underwriter Vault & Margin Vault
* Updates → every minute


# Liquidity Mining

Under Construction

Replacement of traditional token liquidity mining with Premia Call Options

* The proposed change allows liquidity providers to receive PREMIA Call options at a 45% discount to the underlying asset's current market price, replacing the current liquidity mining scheme.
* The proceeds, if exercised, will circulate \~90% to vxPREMIA staking users and direct the remaining 10% to Blue Descent DAO. If not exercised, 20% of the option's intrinsic value will be locked for 1 year and then provided to the liquidity provider's wallet.
* Protocol Fees will be collected on exercise, and taker fees will be collected if this option is traded on the secondary market. This is built modularly so that any market can be deployed as a physically settled option.


# Referral Programs

## Premia Ecosystem Offers & Programs

On the Premia Platform, many different incentive programs exist; check them out!

#### 1. Advocate Program

* **Learn and Earn**: Educate yourself and earn rewards.
* **Refer Friends**: Receive rewards for referring friends to the platform.
* **Content Creators**: Special incentives for content creators.
* **Combination**: Can be combined with the Affiliate Program for additional benefits.

#### 2. Affiliate Program

* **Monetize Network**: Earn back commissions by leveraging your network.
* **Commission Tiers**: Four commission tiers available (5%, 10%, 20%, ?%).
* **Personalized Referral Links**: Top affiliates receive personalized referral links.
* **Combination**: Can be combined with the Advocate Program for additional benefits.

#### 3. Market Maker Program

* **Competitive Fees**: Offers competitive fee schedules compared to centralized exchanges.
* **Rebates**: Provides rebates based on trading volume.
* **Tight Spreads**: Tight spreads lead to rebates and discounts.
* **OTC Trades**: Over-the-counter trades are KYC enabled.
* **Composability**: All options are composable with AMM.
* **Programmatic Trading**: Allows programmatic quotes/trading via API or SDK.

#### 4. Broker / Institutional Program

* **Best Execution**: Payment for order flow with the best execution.
* **Routing Orders**: Route orders to Premia and receive a percentage of the taker fees collected.
* **Commissions/Spreads**: Commissions and spreads are acceptable.
* **Programmatic Trading**: Allows programmatic quotes/orders via API or SDK.

These programs offer a variety of ways for individuals, content creators, market makers, and institutions to engage with Premia's platform, earn rewards, and benefit from customized services. Whether through direct referrals, monetizing networks, or specialized trading programs, Premia provides diverse opportunities to participate in the ecosystem. To learn more about who to contact, check out [**VIP & Institutional Services**](/resources/vip-and-institutional-services)**.**


# Advanced Exchange Concepts

Overview

Many advanced features will continually be added around the base layer.  These features will be highlighted/introduced in this section. &#x20;


# Token Integration Requirements

<figure><img src="/files/PV2SZofagQ53kQZ3ihq5" alt=""><figcaption></figcaption></figure>


# Flash Swaps and Loans

<figure><img src="/files/PV2SZofagQ53kQZ3ihq5" alt=""><figcaption></figcaption></figure>


# Vault Depot

## <mark style="color:blue;">Overview</mark>

Premia Vaults were originally named “Meta-Vaults”, because they were designed as passive liquidity Vaults that would enable users to take advantage of the current meta for options. In competitive gaming (not too far from the PvP nature of financial markets), meta or “metagame” is a term used to refer to the top tactics and strategies at the time, used by players to optimize for a specific environment or ruleset. Similarly, Premia Vaults are meant to be used by traders and yield seekers alike, to maximize their returns and risk-management success in DeFi.

## <mark style="color:blue;">Premia v3 Vaults</mark>

The Margin Pool is a Premia Vault created in-house, intended to provide leverage to sell-side options on The Premia Protocol. This Vault will go live immediately after the launch of the V3 protocol, enabling lenders to earn interest relative to their risk, and option sellers to maintain lower capital requirements for their positions.

In addition, there are other Vaults planned and being developed to go live in the near future. This includes the well-known C-Level Vault (Premia V2 Sell-Side Pools) and Knox Vaults, brought forward from the previous version of our platform by popular demand. These Vaults implement option selling strategies, to attempt to earn passive income. We look forward to adding additional composable Vaults to the platform, including Market-Making implementations in the future.

## <mark style="color:blue;">3rd Party Vaults</mark>

Vaults can be created permissionlessly by anyone, to deploy strategies utilizing the Premia Protocol. Over time, we will be implementing a Contributor program, for showcasing Third-party Vaults on the Premia Interface, enabling Premia to benefit from increased volume and vault creators to benefit from performance fees. [Reach out ](broken://pages/0CmqAVOe2KapHYrbKaVr#media-kit)to build with us!


# What is a Depot?

What does DEPOT stand for?\
**DEPOT**: **D**ynamic **E**ngine for **P**ermissionless **O**ptions **T**rading\
**DEPOT**: **D**eFi **E**ngine for **P**ermissionless **O**ptimized **T**ransactions\
**DEPOT**: **D**igitally **E**xecuting **P**ermissionless **O**mnibus **T**rust\
**DEPOT**: **D**ecentralized **E**nvironment for **P**eer-to-peer **O**ptions **T**rading\
**DEPOT**: **D**istributed **E**quity **P**ool for **O**nchain **T**rading

Welp, we will keep it a surprise for now, and you can form your own opinions.

## Premia's DEPOT Vaults

Premia's DEPOT is a specialized vault designed to cluster liquidity in battle-tested strategies. It's part of the migration from Premia V2 to Premia V3 and satisfies the ERC4626 vault standard, enabling cross-protocol compatibility. Think of it like a robo-advisor for options strategies.

**Key Features:**

1. **Tracking Option Listings**: DEPOT keeps track of its short option positions, including strike and maturity combinations.
2. **Accounting of Locked Spreads**: The quoted price includes the option's fair value, the spread charged by the vault, and the minting fee paid to the pool.
3. **Fee Collection**: Liquidity Providers (LPs) pay management and performance fees.
4. **Trade**: Users can buy call/put options from the vault, with trades passing filters based on the option's delta and the days to expiry.

## DeFi Options Vaults (DOVs)

DOVs are instruments that simplify option investment strategies by allowing participants to stake their assets in a vault while earning yield simultaneously. They automatically deploy staked assets into specific options strategies, entirely run by smart contracts.

**Key Features:**

1. **Automated Investment**: DOVs invest staked assets in options strategies for users.
2. **One-Button Investment**: Users can invest in selling or buying options through a vault and earn options premiums.
3. **Strategies**: Two main strategies are employed in DOVs: Covered Call and Cash-Secured Put. However, more advanced strategies can and should be deployed.

#### Similarities Between DEPOT and DOV

1. **Options Underwriting**: DEPOT and DOVs are involved in underwriting options, including call and put options.
2. **Automated Execution**: Both systems rely on smart contracts to automate investment.
3. **Liquidity Management**: Both DEPOT and DOVs cluster liquidity to execute options strategies.
4. **User Interaction**: In both cases, users can deposit assets, buy options, and earn premiums or spreads.

#### What are the Risks?

Premia's DEPOT and DOVs are innovative financial instruments in the DeFi space that provide automated options strategies. While DEPOT focuses on underwriting options with specific accounting and fee collection mechanisms, DOVs offer a more simplified approach to options investment. Both represent the evolving landscape of decentralized finance, leveraging blockchain technology to offer unique investment opportunities.\
\
All investing includes risk, and Premia's DEPOT products involve risk. Engaging in options underwriting and trading within decentralized finance, particularly with cryptocurrencies, comes with significant risks. These include but are not limited to, volatile market price fluctuations, flash crashes, potential market manipulation, and cybersecurity threats. Understand the DEPOT strategy before depositing because many strategies may have a directional bias.

Unlike traditional equity, option, futures, or foreign exchange investing, the decentralized nature of cryptocurrency markets means they are not regulated with the same controls or customer protections. Premia's DEPOT's unique structure and functionality may introduce additional complexities and risks, including clustering liquidity for underwriting options.

Trading in Premia's DEPOT can lead to substantial and immediate financial losses. Participation in these products is suitable only for investors who fully understand the associated risks and can bear such potential losses. Prospective investors should consider their risk tolerance carefully and consult financial professionals before trading with Premia's DEPOT products.


# APY Calculation

APY, or Annual Percentage Yield, represents the annualized rate of return that can be anticipated from a deposit into a vault. It considers the impact of compounded profit from the vault strategy and any capital losses, resulting in a more precise estimation of earnings. Assuming no withdrawals occur, APY considers how returns contribute to the initial deposit, leading to a gradual growth in the rate of return.

**Calculated as followed**

APY = 100 \[(1 + Collateral Today/Initial Deposit)(365/Days)−1]

This is a projected APY calculation based on historical data, provided on a good faith basis, and should not be used as a basis for investment decisions. Past performance is no guarantee of future results. Future returns are not guaranteed, and a loss of original capital may occur.


# Underwriter Depot

## *Introduction*

*The purpose of creating the underwriter vault is to migrate users from Premia V2 to Premia V3. The UnderwriterVault satisfies the ERC4626 vault standard and enables cross protocol compatibility.*

## General Overview and Functionality

{% hint style="info" %}
*The vault's purpose is to cluster liquidity that will be used to underwrite options at prices close to Deribit's. The depositor's liquidity will be used to underwrite call and put options for a wide set of strikes and maturities.*
{% endhint %}

### Depot Summary

1. **ERC4626 State Variables**: The vault maintains state variables like total assets and total supply. These are updated based on user interactions like deposits, withdrawals, mints, and redemptions.
2. **Tracking Option Listings**: The vault keeps track of its short option positions, i.e., strike and maturity combinations. This uses variables like maturities, maturityToStrikes, minMaturity, and maxMaturity.
3. **Accounting of Locked Spreads**: The price quoted by the vault includes the fair value of the option, the spread charged by the vault, and the minting fee paid to the pool. Spreads collected from underwriting options are considered profits and are dispersed linearly over the option's lifetime to prevent front-running trades.
4. **Fee Collection**: LPs pay management and performance fees. Management fees are for managing LPs' assets, and performance fees are for generating positive returns. Fees are triggered upon a transfer or redemption and are only paid on the transferred/redeemed amount.
5. **Trade**: Users can buy call/put options from a vault, given that a pool with the corresponding maturity, strike, and option type exists. Trades need to pass filters based on the option's delta and the days to expiry. The vault charges a spread using the c-level function.
6. **Options Pricing**: The Underwriter Vault uses a [SSVI Model](/resources/research/ssvi) for Options Pricing.

*User Stories*

*• As a depositor, I want to deposit collateral into the vault to receive shares that can later be redeemed for the premium and spread that is made by selling options to buyers in addition to my original deposit.*

*• As a depositor, I want to be able to withdraw from a vault when there is capital available so that I can recover my collateral and realize the pro-rata P\&L from the time spent in the vault.*

*• As a buyer, I want to receive a quote for an option purchase so that I can know in advance what the premium will be for purchasing the options and compare the cost with other outlets.*

*• As a buyer, I want to purchase options from the vault by paying a premium for long contracts.*

*• As a vault operator, I want to settle all options until the current time so that I increase the vault's liquidity / available assets, such that it will be available for depositors to withdraw or buyers to purchase new options.*

{% hint style="info" %}
This is just a summary of the Underwriter Options Depot - The full detailed explanation can be found within the [research specification](/resources/research)
{% endhint %}


# Governance

## Premia Governance: Navigating the Cosmos of Innovation

In the infinite expanse of decentralized finance, governance is the star map that guides the way. At Premia, governance is not merely a mechanism; it's a galactic alliance between the platform and its community. It's a democratic journey where every holder of PREMIA or vxPREMIA tokens has a voice, a vote, and a vital role in the odyssey of Premia.

Here's how the governance at Premia is charted:

1. **The Power of Participation:** Any holder of PREMIA or vxPREMIA tokens can actively participate in Premia Governance. Your voice resonates whether you're a cosmic explorer or a seasoned astronaut.
2. **Staking for Influence:** By staking PREMIA tokens for non-transferrable vxPREMIA tokens, users not only share in the fees generated by the protocol but also can vote on interstellar decisions, such as distributing liquidity mining rewards.
3. **On-Chain & Off-Chain Voting:** Governance at Premia is a fusion of on-chain voting for real-time updates, off-chain Snapshot votes, and a brand new hybrid model brought to you by UMA's oSnap. This celestial combination ensures agility, security, and inclusiveness.
4. **Insurance Fund:** A cosmic shield for the ecosystem, the Insurance Fund protects against bad debt and ensures stability. It's a beacon of Premia's commitment to risk management.
5. **Options Liquidity Mining:** A groundbreaking approach that replaces traditional token rewards with Premia Call Options, aligning the orbits of liquidity providers and long-term visionaries.
6. **Transparency & Trust:** From the public broadcasting of all operator addresses and accounting transparency to open participation in governance, transparency is a core value in Premia's universe.
7. **A Path to the Future:** With initiatives like Blue Descent, Premia is continually evolving its governance to meet the needs of a growing and dynamic cosmic community.

Premia's governance is like an ever-expanding star map, where every instrument plays a vital role in exploring the unknown. It's a place where innovation meets collaboration, every token holder is a navigator, and the symphony of decentralized finance is composed of ambition, accuracy, and aspiration.

Join the expedition, be part of the movement, and help navigate the cosmos of innovation at Premia. Your voice, your vote, your vision – that's what makes Premia not just a platform but a community. 🚀

## Quick Resources

SNAPSHOT: <https://gov.premia.blue/#/>\
PARLIAMENT SNAPSHOT: <https://parliament.premia.blue/>\
FORUM: <https://forum.premia.finance/>\
GITHUB: <https://github.com/Premia-Gov>


# Premian Civitas

In the grand tapestry of decentralized finance, a term resonates with the wisdom of ancient Rome: **Civitas**. A united social body of Citizens, Civitas was a concept that transcended mere governance and embodied a collective spirit.

Enter the Premian Civitas, the beating heart of the Premia Collaborative Network. These are not mere users or participants; they are the constituents, the lifeblood, the very soul of the platform. With Direct, Indirect, or Vested Interest, they are the guardians of a new financial frontier.

Represented by the digital sigil of a Public Key (EOA or SC wallet), the members of the Premian Civitas take many forms:

* **Citizen**: A Holder of Influence, a voice in the chorus, a Community Member.
* **Participant**: The Liquidity Providing User, the Staking User, the hands that shape the Platform.
* **Contributor**: A Paid Associate or Contractor, be it a Dev, Writer, Advocate, Researcher, Adviser, and more, the innovation architects.
* **Multi-Stakeholder**: A fusion, a synergy, Any Combination of the above, the multifaceted gem of the ecosystem.

The power they wield, the mark they leave, is known as "Influence" (vxPREMIA \* Boost). It's not merely a metric; it's a testament to their impact on the economics and stewardship of the ecosystem.

The Premian Civitas is more than a community; it's a movement, a philosophy. It's the embodiment of decentralized governance, the formal path etched in the scrolls of our Blue Descent.

Join us, become a Citizen of Premia, and be part of a revolution that redefines, reclaims, and renews the essence of economics.

[**Enter the Forum**](https://forum.premia.finance/)


# Parliament

#### Premia Parliament Formation - [Passed and Implemented by Governance Vote](https://gov.premia.blue/#/proposal/0x011d101a569caeff821d3dce2b7319fdd0db1c560b7e564ec763213620b4914b)

**Abstract**: The Premia Parliament is a visionary assembly of 10 motivated community members united by a vested stakeholder interest in the flourishing of the Premia Ecosystem.

**Motivation**: The need for community involvement grows as the Premia Ecosystem matures. The Parliament is a joint task force of Premia Core and Elected Community members tasked with guiding the Premia Ecosystem into its next chapter.

**Specification**:

* **Purpose**: To formalize the path to a Decentralized Organization, focusing on Premia tokenomics, Commission splits, meta-economy aspects, new initiatives, product reviews, legal collaboration, continuous ratifications, and democratizing the governance process.
* **Expectations & Requirements**: Parliament members must commit 6 to 20 hours per month, with weekly call attendance. The position is paid in Premia Tokens, with privacy solutions future generationsfor those who wish to remain anonymous.
* **Timelines**: Application and Election periods were outlined, with the top 10 candidates ratified as Parliament Members.
* **Candidates**: A diverse list of community members submitted their candidacy.

**Conclusion**: The formation of the Premia Parliament marks a significant milestone in the journey toward decentralized governance. With temporary email addresses, NFT Badges, and a transparent communication process, the Parliament is poised to set the groundwork for future generations.

**Additional Details**: The Parliament's formation includes specific timelines, voting procedures, and candidate information. The process ensures transparency, inclusivity, and a commitment to the long-term success of the Premia community. For more insights, visit the [Parliament Formation Notes](https://notes.premia.community/parliament-formation).


# Blue Descent

**Blue Descent**: A name that resonates with the echoes of the deep blue sea and carries the weight of history and the promise of discovery. It's not just a name; it's a vision, a journey, a descent into the uncharted galaxy of DeFi.

From the azure hues of Premia's Origins to the vast expanse of decentralized finance, Blue Descent is the proposed beacon for the Premia Decentralized Community. It's the first step on a path less traveled, a formalized route to decentralized governance.

But why stop at the familiar "DAO"? As web3 matures, so must our language. Enter "DeSCEnt," a decentralized social collective enterprise. A term that dances with the likes of dORG(BBLLC), DisCO, or DO, yet carves its own identity, reflecting the unique vision of the Premia Ecosystem.

The path to governance is not a sprint but a marathon, an \~18-month odyssey that unfolds in layers, protections, and controls, shaped by the hands of the community.

The Community Forum and Proposal Process, targeted for the end of 2022, is a symphony in four movements, four Eras that define the evolution of Blue Descent:

* **Pre-Foundation (Q1-Q2 2023)**: The genesis, where Code of Conduct & Principles are forged, and Community Legal Liability Protections are set in stone.
* **Foundation (Q3-Q4 2023)**: The building blocks where Tools and Proposal Applications come to life, 10 Community Members rise to the Ratification Council, and the First Small Grant Fellowship is born.
* **Republic (Q1-Q2 2024)**: The blossoming, where the First Elected Magistrate Class takes the helm, Open Organization Creations flourish, and On-Chain Alpha Voting begins to pulse.
* **Empire (Q3-Q4 2024)**: The zenith, where On-Chain Beta Voting thrives, the Second Magistrate Class ascends, and Social Reputation matures into a force of nature.

Blue Descent is more than a name; it's a manifesto, a declaration of intent, and a map to a future where the Premia Ecosystem evolves into something transcendent.

Join us in this descent, this exploration, this adventure into the deep blue of DeFi. Be part of Blue Descent, and let's discover what lies beneath.

{% hint style="danger" %}
The content of this page is subject to change due to experience, new information, changes in process requirements, and the availability of resources.
{% endhint %}


# Premian Assembly

The Premia protocol is community governed and managed.

**The Premian Assembly**: A name that echoes through the digital halls of the Premia Ecosystem, a name that stands as a beacon of governance and embodies the very essence of decentralized decision-making.

In the world of Premia, the Assembly is not just a mechanism; it's a symphony of voices, a confluence of ideas, a dance of proposals and votes that shape the very fabric of the protocol.

**Community Proposals** ("Preliminary Vote"): The whispers of change, the seeds of innovation, the sparks that ignite the flame. Any member holding 100 Premia Tokens or more can submit a community vote, a call to action that may blossom into a Core Implementation Proposal.

**Signal Proposals** ("Signal Vote"): The gentle nudges, the probing questions, the subtle hints. Core members submit these to gauge the heartbeat of the community, to feel the pulse of interest. They are the whispers in the wind, non-binding yet powerful.

**Implementation Proposals** ("Core Vote"): The thunderclaps, the crescendos, the climaxes. These propositions transform, evolve, and become part of the Premia Ecosystem's DNA.

With the advent of the vxPremia model and the majestic path to decentralized governance known as Blue Descent, the Assembly has evolved into the "P3 - Premian Publication Process," a formal improvement proposal voting system that promises to be a new dawn. [**More Details**](https://gov.premia.blue/#/proposal/0xcc8ed29d41cfaf919baed0c84b15b0832972f0c9fd1d8f6cb5d543839991df91)

**What is a P3?** It's a beacon, a guide, a map. Adapted from the EIP (Ethereum Improvement Proposal), the P3 ensures that changes to Premia are as transparent as crystal and as well-governed as a wise old council.

**P3 Roles**: The Author, the Mod, the Sponsor. The dreamers, the guardians, the champions.

**P3 Status Codes**: From DRAFT to PUBLISHED, from inception to realization.

**P3 Type Codes**: Concept, Task, & Reference. The what, the how, the need-to-know.

**P3 Rationale**: The why, the reason, and the soul of the proposal.

**P3 Work Flow**: A dance, a journey, a process that involves the author, the moderator, the sponsor, and the Premia community.

**Mod Status**: From Rejected to Executed, from Deferred to Active. The lifecycle of a proposal.

**What Makes a Successful P3?**: The MetaContent, the Summary, the Abstract, the Motivation, the Specification, the Rationale, the Test Cases, and the Copyright Waiver. The ingredients of success.

**P3 Formats and Templates**: The structure, the form, and the vessel that carries the idea.

The Premian Assembly is not just a governance mechanism; it's a living, breathing entity. It's the heart and soul of the Premia Ecosystem, the place where ideas are born, nurtured, debated, and realized.

Join the Assembly, be part of the dance, add your voice to the symphony, and let's shape the future of Premia together.

{% hint style="info" %}
With the implementation of the [vxPremia](/developer-center/contracts/vxpremia) model and the upcoming path to decentralized governance [Blue Descent](/the-premia-protocol/governance/premian-civitas/blue-descent), this process is now the "[P3 - Premian Publication Process](https://forum.premia.finance/t/p3-purpose-and-guidelines/38)," a formal improvement proposal voting system.
{% endhint %}


# "Influence" Politics

Influence = vxPREMIA \* Boost

**Influence**: A word that resonates with power, echoes with authority and stands as the very currency of the Premia Meta-Economy.

In the grand tapestry of Premia, Influence is not just a unit; it's a force, a tide, a wave that shapes the very contours of the ecosystem. Calculated by **vxPREMIA holdings \* Boost**, Influence is the compass that aligns the long-term vision with economics. [**More Details.**](/the-premia-protocol/governance/voting-vxpremia)

But Influence is more than a mere calculation; it's a symphony, a dance, a convergence. It unites the multi-stakeholders of the platform - the citizens, the contributors, and the participants (LPs & Traders) - into one cohesive standard measure. It's the heartbeat, the pulse, the rhythm of Premia.

Today, Influence is the scepter that can be wielded in Governance via Snapshot vote ([gov.premia.blue](https://gov.premia.blue/)) or the wand that controls valve gauge weights via the [Rewards Manifold control](/the-premia-protocol/governance/voting-vxpremia/vxpremia-manifold). It's the key, the tool, the instrument of change.

But tomorrow, as Premia's decentralized governance blossoms via the majestic path of [Blue Descent](/the-premia-protocol/governance/premian-civitas/blue-descent), Influence will evolve, transform, and ascend. It will become the cornerstone, the pillar, the foundation of policy, parameter control, representatives, funding, organizations, and the Republic.

Influence is not just a unit of account; it's a philosophy, a vision, a way of life. It's the essence of Premia, the soul of the Meta-Economy, the force that drives us forward.

Join us in this dance of Influence, this symphony of power, this journey into the heart of Premia. Be part of Influence Politics, and let's shape the future together.


# Voting (vxPremia)

Synthesis of the xToken, veToken, and xChain native design

### Abstract <a href="#abstract" id="abstract"></a>

vxPREMIA is the voting token of the Premia Meta-Economy. The token represents a weighted balance of PREMIA tokens and utilizes a voting-escrow model popularized by Curve (veCRV) and custom sustainability mechanics. vxPREMIA is minted equal to your deposit of PREMIA tokens. This balance is then modified by your lock period, referred to as your “Boost”.

Your balance of vxPREMIA multiplied by your Boost modifier is your “Influence”. Wallet Influence is the key metric in determining your fee distribution, trading fee discounts, and votes for PREMIA token emission flow.

### Introduction <a href="#introduction" id="introduction"></a>

#### Background <a href="#background" id="background"></a>

The original design [xPREMIA](https://docs.premia.finance/archive/archive-deprecated/depr-premia-staking-earn-protocol-fees-w-xpremia), was elegant yet ever-evolving. It allowed for Premia deposits to receive a pro-rata share of protocol fee distributions, as well as the ability to reduce protocol fees paid by traders. Liquidity Mining (the Liquidity Provider incentive program) was controlled by Snapshot Governance, periodically re-allocating the directional flow of Premia Tokens.

The Premia Protocol has redefined the paradigm known as valve gauge weighting to introduce the vxPremia Reward Manifold.

**Why is it better than traditional ve?**

1. Utilization-based rewards mean that vote farming for low-volume pools is not economic and prevents DAO takeover of emissions (see: Balancer, Convex, etc.).
2. Omni-chain means that users can bridge their locked vxPREMIA to any chain supported by LayerZero and vote on emissions or earn rewards on whichever chain they currently see the most benefit.
3. Non-transferrable (soul-bound until unlocked), means that bribes are disabled by default, enabling healthier emissions governance.
4. Earn rewards in USDC, zap-compoundable into more vePREMIA at any time, means stakers earn highly liquid, stable yield.

#### Definitions <a href="#definitions" id="definitions"></a>

* **vxPREMIA:** Staked PREMIA tokens
* **Boost:** Modifier calculated by lock period length remaining
* **Influence:** Weighted PREMIA Balance
  * \=(vxPREMIA\*Boost)
* **Withdraw Delay:** 10-day delay once withdrawal requested
* **Early Unlock Penalty:** Penalty paid to remove the lock period
  * coefficient scales to lock time remaining - 25% per year left, max is 75%
  * feePercentage % fee to pay for early unstake (1e4 = 100%)
* **Liquidity Mining:** Option Pool Liquidity Provider Incentives in PREMIA Token
* **Reward Manifold:** Valve gauge control for emission flow of liquidity mining rewards
  * **Flowback Throttle:** Synthetic cap on applied influence based on utilization
    * \=(Influence \* max(utilization, 0.25))
    * This ensures each pool's rewards are based on the revenue produced by the pool
* **Universal Social Dividend:** Protocol Fee Distributions to vxPREMIA holders (USD Proceeds)
* **Rewards:** Protocol Fee Distributions (Social Dividend) & Liquidity Mining Incentives (Manifold)
* **Bridge:** Process to move a token from one chain to another (vxPremia currently uses [LayerZero](https://layerzero.network/))

### vxPremia Meta-Economy <a href="#usage" id="usage"></a>

#### Methodology <a href="#methodology" id="methodology"></a>

**Liquid Valves -** By locking Premia Tokens via the vxPremia Interface, users are now empowered to align the long-term platform vision with that of participants and citizens. Liquid Valve Gauge Weight is applied immediately and does not follow an epoch process. Each source chain has its corresponding manifold to distribute liquidity mining incentives.

**Protocol Commissions -** Pro-rata distributions of collected fees based on source chain utilization, collateralization, and settlement fees. Proceeds are applied based on the amount of influence on the source chain.

**Omnichain Gateway -** As now reward controls are at the chain level, there needs to be a fluid method to move vxPREMIA between chains. Utilizing our omnichain approach and LayerZero implementation, this is a quick and effortless transaction. The process is as follows: burn vxPREMIA on the source chain, mint vxPREMIA on the destination chain. In the LayerZero transaction, the boost modifier is automatically carried to the destination chain and combined with local vxPREMIA to update your size-weighted multiplier.

**Omnichain Hub Relay** \[In Development] **-** A method to sync cross-chain vxPREMIA Influence to direct Chain Weight of the Liquidity Mining Incentives from the Liquidity Mining Reservoir Fund (on mainnet) to the destination chains. This will complete the entire process of reward distribution, becoming decentralized, on-chain, and omni-chain.

#### **vxPremia Manifold Control**

Influence holders can direct their vote to any directional pool (call or put) on their vxPREMIA source chain. The total aggregate of the pool's valve gauge as a percentage of total influence directs that chain's share of liquidity mining incentives. Voting is liquid and applied immediately upon the next pool update transaction; there is no epochal update with Reward Manifold Control. To incentivize highly utilized pools and reduce the irrational application of influence, there is a mechanism known as the flow back throttle that creates a synthetic cap on the pressure applied at the valve level.

The **flow back throttle** is calculated as (Influence \* max(utilization, 0.25)); thus a less-utilized pool receives a haircut on votes applied. For example, if 1,000 influence is applied to pool "A" and the if utilization rate of pool "A" is 20%, then the influence applied to that pool is calculated as 250. If 1,000 influence is applied to pool "B" and the utilization rate of pool "B" is 85%, then the influence applied to that pool is calculated as 850.

#### **Premia Universal Social Dividend (USD Proceeds)**

**Distributed Protocol Fees**

\~50% distribution of accrued fees each month (decay function) is given to vxPREMIA holders via their pro-rata share of Influence. For example, if you own 20% of the chain's vxPREMIA influence, you will receive 20% of fee distributions.

#### **Fee Discounts**

* Externally owned accounts (ex: metamask wallet)
  * 60% Max Discount
  * 5,000 vePREMIA Influence = 10% Discount\
    50,000 vePREMIA Influence = 25% Discount\
    500,000 vePREMIA Influence = 35% Discount\
    2,500,000 vePREMIA Influence = 60% Discount
* Smart contract accounts
  * 30% Max Discount
  * Discount scales linearly from 0-30% as the contract's control of Total Influence on the Source Chain scales from 0-50%

#### Contract Functions <a href="#contract-functions" id="contract-functions"></a>

A contract allowing you to use your locked Premia as voting power for mining weights

1. **getPoolVotes -** Get total votes at the pool level
2. **getUserVotes -** Get total votes at the user level
3. **castVotes**
   1. Remove previously applied votes (if any)
   2. Apply new vote distribution


# vxPremia Manifold

Brief visualization of a source chain Reward Manifold

An example of a local instance of the vxPremia Manifold control mechanism.

Further information can be found [here](/the-premia-protocol/governance/voting-vxpremia)

<figure><img src="/files/P59aA6muah6ZBbngebaM" alt=""><figcaption></figcaption></figure>


# vxPremia Rewards

**Welcome to the vxPremia Rewards Odyssey!**

In the bustling bazaar of Premia, we don't just create products; we craft social treasures for our thriving community. Our commissions, those gleaming gems collected from premiums, utilization, and settlement, are not hoarded but generously repaid to our esteemed Premia Citizens (USD Proceeds). Why? Because we believe in harmony, balance, and a dance that unites liquidity providers with the visionaries of our platform.

**Liquidity Mining: The Fountain of Growth** Embark on a journey to the heart of our ecosystem, where liquidity mining springs to life. Introduced to fuel our growth, this wellspring incentivizes liquidity providers beyond mere premiums. We've crafted a harmonious flow across supported chains with a fine-tuned target rate to maintain gentle inflation between 0.75 and 1.00 Premia tokens per block. And with the upcoming Omnichain Hub Relay, prepare for a new chapter in this ever-evolving tale.

**Protocol Commissions: The Treasury of Influence** Step into the grand hall of Protocol Commissions, where taker fees, performance fees, management fees, and more are not mere numbers but the essence of our decentralized governance. These fees are the golden threads woven into the fabric of vxPREMIA holders' influence. And as we transition from Premia v2 to the exciting horizon of Premia v3, the adventure continues to unfold.

**The vxPremia Symphony** Here at Premia, vxPremia Rewards are not static; they are a symphony, a harmonious blend of liquidity mining and protocol commissions. A melody that resonates with the interests of citizens, contributors, and participants (LPs & Traders). A rhythm that echoes through governance, valve gauge weights, policy, and the very soul of our Republic.

Join us in this odyssey, for as Premia's decentralized governance blossoms through the [Blue Descent](/the-premia-protocol/governance/premian-civitas/blue-descent), vxPremia Rewards will be the heartbeat, pulse, and essence of our collective dream.


# Options Liquidity Mining

## Premia's Options Liquidity Mining: A Symphony of Strategy

Premia has orchestrated a novel approach to liquidity mining in the ever-evolving landscape of DeFi Primitives. Instead of the traditional token rewards, liquidity providers are now bestowed with Premia Call Options at a tantalizing 45% discount to the underlying asset's current market price.

Here's how the melody plays out:

1. **The Call of Options:** Liquidity providers receive PREMIA Call Options, granting them the right (but not the obligation) to buy PREMIA at a specific price within a set timeframe.
2. **A Discounted Dance:** These options are offered at a 45% discount, creating an attractive incentive for liquidity providers to participate.
3. **The Exercise Enigma:** If the options are exercised, approximately 90% of the proceeds circulate to vxPREMIA staking users, while the remaining 10% is directed to the Blue Descent DAO.
4. **The Lock of Intrinsic Value:** If the options are not exercised, 20% of the option's intrinsic value is locked for a year, after which it's provided to the liquidity provider's wallet.
5. **Fees and the Secondary Market:** Protocol fees are collected on exercise, and taker fees are levied if the option is traded on the secondary market.
6. **Modular Mastery:** This mechanism is built modularly, allowing any market to be deployed as a physically settled option.
7. **A Harmonious Balance:** This innovative approach aligns the interests of liquidity providers, staking users, and the broader Premia ecosystem.

Premia's Options Liquidity Mining is like a finely composed piece of music; each note and rhythm plays a vital role in creating a harmonious balance. It's a strategic dance that benefits liquidity providers and long-term visionaries of the platform, adding a new layer of complexity and opportunity to the decentralized finance space. It's not just a change; it's a revolution in how liquidity mining is conceived and executed. 🎵

### The below will be decommissioned in September 2023

To bootstrap liquidity during the growth phases of the Premia Ecosystem, liquidity mining was introduced to further incentivize liquidity providers in addition to the premiums generated through underwriting products on the Premia Platform.

The target rate was established to maintain low inflation between 0.75 and 1.00 Premia tokens emitted per block to liquidity providers. As of November 2022, this hovers around 0.905 Premia tokens per block across all supported chains.

* Arbitrum (0.375)
* Ethereum (0.1875)
* Fantom (0.1875)
* Optimism (0.155)

With the coming implementation of the Omnichain Hub Relay, this allocation will be subject for review and amendment.

{% hint style="info" %}
This is for V2 and is subject to change in V3, which can be [found here.](/the-premia-protocol/governance/voting-vxpremia/vxpremia-rewards/protocol-commissions)
{% endhint %}


# Protocol Commissions

Under Construction

## **Premia Blue (V3) Protocol Fees:**

* Three layers of fees: Base, Margin, and Vault.
  * **Base Layer** amasses commissions from the greater of either 3% of premiums paid or 0.3% of the notional value transacted. On Settlement, a fee of 0.3% is collected, not to exceed 12.5% of the option's value. (Rates subject to change by vote)
  * **Margin Layer** is a two-part equation. Firstly, it subtracts 0.4% from the Prime Rate (driven by supply and demand dynamics) charged to providers of margin lending liquidity. Secondly, it levies a 15% fee on users' liquidated positions. (Rates subject to change by vote)
  * **Vault Layer** includes a 2% per annum management fee and a 20% fee on all positive returns for all native vaults (built in-house). (Rates subject to change by vote)
    * For Vaults developed by third parties, fees will be negotiated ad-hoc on a case-by-case basis.
* Distribution of fees to Staking Users (vxPremia), Premian Republic, and the Insurance Fund.
  * **Staking Users** are allotted 80% of Base Layer fees.
  * The **Operator Group** receives 20% of Base Layer fees.
  * The **Insurance Fund** collects 100% of the fees from the Vault and Margin Layers.
* Parliament will reconvene every January to re-access the allocations and amend, any changes will be submitted for a vote before any action is taken. The first meeting will be January 2024.

Premia V2 Protocol Fees: Premia charges a 3% Protocol Fee to option buyers and a 2.5% Utilization Fee to LPs. 80% of fees are paid to $PREMIA staking users.

#### Premia Classic (V2) Fees Below:

Upon creation of a trade on the platform, a taker fee is currently charged:

* Taker Fee - 3% of option premium applied at option creation

Currently, upon settlement of any trade, a utilization fee is captured.

* Utilization Fee - 2.5% annual interest fee applied at settlement based on length & size

These fees are collected on a source chain level (chain independent), and allocated to vxPREMIA holders on a pro-rata basis of their percentage influence on that source chain.


# AirDrip Initiative

Under Construction

## AirDrip Initiative Overview

The AirDrip Initiative is a groundbreaking part of Premia's cosmic strategy, designed to reward the loyal navigators of the Premia universe. Initially, 30mm Premia Tokens were earmarked for Liquidity Mining over a decade, but the new initiative has recharted the course, setting aside 16mm for Liquidity Mining and 10mm for the AirDrip Initiative. The first allocation of 2mm Tokens will be pro-rata distributed to all staking users based on their influence across all chains. A snapshot will record all influence on a specific date, and a new smart contract will lock these tokens for one year, allocated based on the Influence amount. Any gaming of the system will be penalized, ensuring a fair distribution.

The AirDrip Initiative is not just a one-time event but a continuous journey. One year after the Snapshot Date, the Tokens will be dripped daily over the next year, fully vesting by Snapshot Date + 2 years. The remaining 8mm Tokens will be part of a long-term proposal, with the Parliament reconvening in 2024 to decide the allocation. It's a celestial commitment to the community, a way to fuel the exploration, and a testament to Premia's dedication to its users as they traverse the infinite possibilities of decentralized finance.

## AirDrip Background and Motivation

* Initially, 30mm Premia Tokens were reserved for Liquidity Mining over 10 years. The new initiative proposes to set aside 16mm for Liquidity Mining and 10mm for the AirDrip Initiative (4mm have already been allocated)
  * 16mm Liquidity Mining to be split into two buckets of 8mm, one bucket to be allocated over four years (2mm per year). The other bucket will be used for future ecosystem products outside the Options Exchange.
* The AirDrip Initiative of 10mm Tokens will be split over multiple years. The first allocation proposed is to utilize 2mm Tokens and allocate pro-rata to all staking users based on their influence across all chains.
* A snapshot will be communicated (date to be announced shortly \~ETA August 1st), and all influence will be recorded on that date. Over the coming weeks, a new smart contract will be deployed, locking the 2mm Tokens for one year, allocated to individuals based on their Influence amount.
* If, for any reason, a wallet withdraws before its regular staking lockup period and concedes to pay the early withdrawal penalty, the wallet will forfeit any AirDrip allocation, and that will be redistributed to the remaining staked users. If the wallet's natural lockup period expires before Snapshot Date + 1 year, then the allocation shall remain; however, it won't begin to vest until the Snapshot +1 year date as defined below.
  * This is to penalize any user trying to game the influence metric during the snapshot date.
* One year following the Snapshot Date, the Tokens will be dripped out to all eligible wallets monthly (linearly) over the next year. The allocation of 2mm Tokens will then be fully vested and available for claim by Snapshot Date + 2 years.
* For the remaining 8mm Tokens, the Parliament will reconvene in January of 2024 with a long-term proposal for allocation.

[Airdrip 1 Initial Snapshot](https://files.premia.finance/$/IPRQM)\
As the Airdrip smart contracts are being developed, periodic snapshots will be taken to remove wallets that have withdrawn early and paid the withdrawal penalty fee.  At the point, the Airdrip tokens are allocated to the smart contract, and eligible users are added, the smart contract will handle the removal of allocation for any wallet that pays a withdrawal penalty fee and reallocate to the remaining wallets eligible.


# Operator & Facilitator Role

Vision: Public Redux of Economic Market & Investment Access \[PREMIA]

The Premian Ecosystem operated by the Premian Republic is a cooperative effort spanning many contribution groups and individuals across the globe.

The Premian Republic acts as fiduciary for the ecosystem and manages direct and coordination costs to achieve the shared vision. The Premian Republic directs its efforts to contributors focusing on building conscious, open, & contestable smart markets.

The collaborative enterprise only asks that all share a similar cultural outlook and uphold the following virtues: Equality of wealth, Equity of opportunity, and Economic justice. If these hold true to you and you would like to join our contribution network, please don't hesitate to reach out.

As we hold transparency as a core tenet, economic costs associated with fulfilling this doctrine are summarized [here](broken://pages/fbSt3ZAybePsZ9wauuPr).


# Operational Expenditure and Maintenance Costs

The protocol utilizes a number of third party platforms & networks in order to provide the optimal user experience.

While it would be nice if the protocol were a cost-free automaton, there are several user-experience upgrades and protocol features that require continual expenditure & upkeep. These are the main expenses used by the Premia protocol:

* [Chainlink Network](https://chain.link/)
  * Chainlink Price Feeds for accurate Pool pricing
  * Chainlink Automation
    * Auto exercise of expired options
    * Convert protocol fees to PREMIA rewards
* [The Graph Network](https://thegraph.com/en/)
  * On-chain Data Indexing for Premia smart contract events used on the front end
    * Wallet & Protocol analytics
    * Third-party tooling
* <mark style="color:purple;">Cloud Infrastructure</mark>
  * Volatility Surface Oracle
  * Front-end APIs and RPCs
  * E2E Testing and Verification
* Contract Deployment & Servicing
* Contributor Compensation
* Traditional Business Expenses (Legal, Marketing, Recruitment, etc)
* Strategic Service Providers & Partnerships
* Misc. Compute & Infrastructure Costs

Some of these must be maintained on a per-chain basis, causing expenses to scale per additional chain supported.


# Insurance Fund

Under Construction

## Premia's Insurance Fund: The Guardian of Stability

Risk management is a crucial thread in the intricate tapestry of decentralized finance. Premia's Stability Non-Appropriation Assurance Reservoir Fund, commonly known as the "Insurance Fund," is a vigilant guardian, ensuring the ecosystem's resilience and stability.

Here's how this financial safeguard unfolds:

1. **The Shield Against Bad Debt:** The Insurance Fund's primary purpose is to protect the Lending Pools from bad debt accrued due to liquidated positions once margin trading is enabled.
2. **A Correlated Connection:** The amount available for margin trading directly correlates to the size of the Insurance Fund's held assets. More assets in the fund mean more room for margin trading within the ecosystem.
3. **Rehypothecation Rights:** If the Insurance Fund's assets exceed the calculated amount needed for bad-debt payoff, the Operator may rehypothecate these excess assets for other protocol purposes. This flexibility ensures that the fund's resources are utilized optimally.
4. **Transparency Triumphs:** Once established, the Insurance Fund's address will be published publicly, reflecting Premia's commitment to transparency and trust. [Found Here.](/developer-center/contracts/multi-signature-wallets)
5. **A Safety Net for the Future:** By providing a buffer against potential financial turbulence, the Insurance Fund plays a vital role in maintaining the integrity and robustness of the Premia ecosystem.

Premia's Insurance Fund is not just a mechanism; it's a philosophy. It embodies the wisdom of foresight, the prudence of risk management, and the integrity of transparent governance. It's a testament to Premia's dedication to creating a secure, resilient, and thriving decentralized financial landscape. 🛡️


# Meta Economics

Premia Token Economics

Recently overhauled in coordination with Parliament and Community\
<https://blog.premia.blue/p/premia-meta-economics-revamp>\
Revised Tokenomics and Emissions will be available shortly

<figure><img src="/files/PV2SZofagQ53kQZ3ihq5" alt="" width="333"><figcaption></figcaption></figure>

#### Premia's New Dawn: A Tokenomics Odyssey -[Approved by Governance Vote Aug 2023](https://gov.premia.blue/#/proposal/0x04b0ad986eed6eaf2451487af4e23f6ed7b815efa5586eabd9a404e9f2b26869)

**1. Token Allocation Re-Categorizations:**

* **Blue Descent's Rise:** \~22% of the total 100M token allocation has transitioned from Premian Republic to Blue Descent (DAO).
* **Liquidity Mining's Bounty:** \~30% of the total supply is dedicated to Liquidity Mining, including Options Liquidity Mining and the AirDrip Initiative.
* **Re-vesting the Future:** \~20% of total supply re-vested for four more years as of Jan 15, 2023.

**2.** [**Protocol Fees**](/the-premia-protocol/governance/voting-vxpremia/vxpremia-rewards/protocol-commissions)**: A Triumvirate of Power:**

* **Base, Margin, and Vault Layers:** A cascade of fees and commissions that flow into three distinct realms.
* **Staking Users, Premian Republic, and Insurance Fund:** The beneficiaries of these fees, each playing a vital role in the ecosystem.

**3. The** [**Insurance Fund**](/the-premia-protocol/governance/operator-and-facilitator-role/insurance-fund)**:**

* **Guardian of the Protocol:** Ensuring bad-debt payoff and potential rehypothecation for other protocol purposes.

**4.** [**vxPremia**](/developer-center/contracts/vxpremia) **and** [**Voting Influence**](/the-premia-protocol/governance/voting-vxpremia)**:**

* **The Power of Staking:** Wallets staking PREMIA tokens partake in a pro-rata share of fees.
* [**Locked vxPREMIA'**](/the-premia-protocol/governance/voting-vxpremia#fee-discounts)**s Influence:** Fee Discounts up to 60% for EOA’s and 30% for Smart Contracts, with lock-in periods incentivizing long-term commitment.

**5. Hydraulic Solutions Framework &** [**Options Liquidity Mining**](/the-premia-protocol/governance/voting-vxpremia/vxpremia-rewards/options-liquidity-mining)**:**

* **A New Era of Mining:** Replacement of traditional liquidity mining with Premia Call Options at a 45% discount.
* **Harmonic Balance:** A novel mechanism benefiting both liquidity providers and staking users.

**6.** [**AirDrip Initiative**](/the-premia-protocol/governance/voting-vxpremia/vxpremia-rewards/airdrip-initiative) **and Liquidity Mining Emissions Schedule:**

* **The AirDrip Initiative:** 10M tokens allocated, with 2M immediately dropped to vxPREMIA holders.
* **Liquidity Mining's Dual Buckets:** 16M split into two buckets of 8M each, allocated over various periods and purposes.

**7. Public Redux of Economic Market & Investment Access:**

* **A Commitment to Community:** Emphasizing transparency and dedication to decentralized finance's future.

Premia's revamped tokenomics is a symphony of innovation, aligning interests, empowering stakeholders, and pioneering sustainable growth. It's a dance of numbers and strategy, a game of influence and rewards, all woven into the fabric of a decentralized future. The Premia ecosystem is not just evolving; it's metamorphosing into something more profound, resilient, and aligned with the true spirit of decentralization. Welcome to the new age of Premia! 🚀


# APIs

Premia's API Suite

There are several ways to programmatically interact with [The Premia Protocol](/#the-premia-protocol).  In this section we will specifically be talking about access via an API.  Currently we have 3 major APIs set up.  Please take note which ones are more applicable for developers, and which ones are more applicable for traders.

### [Orderbook API](#orderbook-api)

Direct use of the Orderbook API is suggested for *advanced* web3 developers (ie aggregator protocols), not traders.  For a more trader centric API, please have a look at our [Containerized API](#containerized-api) solution.

The orderbook API is useful for *direct* access to the orderbook and its current state.  It will require additional knowledge of web3 functionality and formatting as there are many aspects of the lifecycle of option trading that will require direct interaction with our on-chain smart contracts.  &#x20;

### [Subgraph API](#subgraph-api)

Like the orderbook API, this is for advanced web3 developers.  Advanced data querying can be done via our Subgraph API.  This is useful for data science, dashboards, and other data centric projects. &#x20;

### [Containerized API](#containerized-api)

The containerized API is an "all-in-one" solution for users who would like to programmatically trade (in any coding language) using the orderbook, but do not want to be slowed down with "Defi integration" (aka web3).  This API solution is very similar to using a centralized exchange API, but with all the benefits of interacting with a decentralized exchange.&#x20;


# Orderbook API

### <mark style="color:blue;">Overview</mark>

The Premia Orderbook API can be used to `Publish` and/or `Get` quotes from the orderbook and RFQ system for any deployed/deployable option pool.   The Orderbook API comprises of both a [REST API](/developer-center/apis/orderbook-api/rest-api) and a [WEBSOCKET](/developer-center/apis/orderbook-api/websocket).  There is no centralized dependency to `Publish` or `Get` quotes.  The orderbook API is simply a convenience wrapper around web3 calls so that others do not need to aggregate the data themselves.

{% hint style="success" %}
This API is primarily for the aggregation/display of decentralized orderbook data. Actions such as [*cancelling*](https://docs-solidity.premia.finance/contracts/pool/IPoolTrade.sol/interface.IPoolTrade.html#cancelquotesob), [*filling*](https://docs-solidity.premia.finance/contracts/pool/IPoolTrade.sol/interface.IPoolTrade.html#fillquoteob), or checking a quotes [fillable](https://docs-solidity.premia.finance/contracts/pool/IPoolTrade.sol/interface.IPoolTrade.html#getquoteobfilledamount) status is NOT done through this API. If you are a trader please read through this section and then reference our [Containerized API](/developer-center/apis/containerized-api).&#x20;
{% endhint %}

### <mark style="color:blue;">API KEY</mark>

In order to use the API directly or through the SDK, an api key is required.  Currently, all api key requests must be made to <mark style="color:blue;"><research@premia.finance></mark>.  Please use subject line: 'API KEY REQUEST' and an api key will be returned. &#x20;

### <mark style="color:blue;">Pool vs Orderbook</mark>

Since all trades must make their way on-chain in some way shape or form, the pool contract for a specific market can be viewed as the "gateway" for this. The pool contract currently supports dual functionality for both interacting with the AMM and interacting with the Orderbook. Functions which include `OB` in their name are designated for Orderbook functionality

### <mark style="color:blue;">Orderbook</mark>

As mentioned in the [Orderbook Concepts](/the-premia-protocol/concepts/orderbook-and-request-for-quote-rfq), quotes are published (by emitting events) to Arbitrum Nova and can be accessed by anyone listening to events on-chain. The Orderbook API will publish quotes for market makers *on their behalf* and aggregate public order events to create a limit orderbook for any deployed/deployable pool.&#x20;

When posting an order, a `deadline` is provided in the quote object which specifies the duration a quote is valid for.  When a deadline is surpassed, the quote will expire without the need for action by the quote maker. However, if a user would like to prematurely void a quote before the deadline is hit, they must invoke the cancel function within the pool contract [here](https://docs-solidity.premia.finance/contracts/pool/IPoolTrade.sol/interface.IPoolTrade.html#cancelquotesob).&#x20;

To *fill* an order that was published to the orderbook, a user must call the fill function available on the pool contract [here](https://docs-solidity.premia.finance/contracts/pool/IPoolTrade.sol/interface.IPoolTrade.html#fillquoteob). Filling orders (as a taker) will incur a transaction fee.  Please see [Fees](/the-premia-protocol/concepts/fees) for more details.&#x20;

{% hint style="warning" %}
IMPORTANT: Unlike LP's, makers who utilize the orderbook do NOT collect trading fees.
{% endhint %}

### <mark style="color:blue;">RFQ</mark>

Request-For-Quote is an additional feature available through the orderbook infrastructure in which users can publish *requests* for a specific pool and receive *personalized* quotes from market makers.  Publishing a request can only be done via [WEBSOCKET](/developer-center/apis/orderbook-api/websocket), but receiving requests can be done via [REST API](/developer-center/apis/orderbook-api/rest-api) or [WEBSOCKET](/developer-center/apis/orderbook-api/websocket).

*What is an RFQ request look like? It is simply an object with the following details:*

* <mark style="color:green;">PoolKey</mark> -> the pool identifier object (base token, quote token, oracle address, strike, maturity, call or put)
* <mark style="color:green;">Side</mark> -> either a 'bid' or 'ask'
* <mark style="color:green;">ChainId</mark> -> the chain id (Arbitrum One Mainnet or Goerli Arbitrum Testnet)
* <mark style="color:green;">Size</mark> -> the quantity that is be requested
* <mark style="color:green;">Taker</mark> -> the address of the user requesting the quote

When a market maker receives this request (via WEBSOCKET), they will then generate a personalized quote and publish a quote to the orderbook for this request. *There is no guarantee that a quote will be returned back after publishing an RFQ request.*

### <mark style="color:blue;">Orderbook vs. RFQ Quotes</mark>

The main difference between an RFQ quote and an orderbook quote is that the `takerAddress` is not populated within the quote object for standard quotes.  This mean the quote can be filled by any taker address on Arbitrum One.  This makes the quote "public".  If the `takerAddress` is populated with an address, it can only be filled by this address, making the order "private". Private quotes are created when a Request-For-Quote is made by a user.  See [here](/developer-center/apis/orderbook-api/websocket#publish-rfq-request-s) for more information on how to publish an RFQ.

{% hint style="success" %}
*<mark style="color:orange;">NOTE: It's important for market makers to publish RFQ quotes with the</mark> <mark style="color:orange;"></mark><mark style="color:orange;">`takerAddress`</mark> <mark style="color:orange;"></mark><mark style="color:orange;">in the quote object populated with the</mark> <mark style="color:orange;"></mark><mark style="color:orange;">`taker`</mark> <mark style="color:orange;"></mark><mark style="color:orange;">address from the request (as opposed to Zero Address).</mark>* While the quote is viewable by anyone, the quote can only be filled by the requester.
{% endhint %}


# REST API

Rest API End Points

### <mark style="color:blue;">Overview</mark>

| Chain                    | Base Url                                |
| ------------------------ | --------------------------------------- |
| Arbitrum Goerli (421613) | <https://test.orderbook.premia.finance> |
| Arbitrum One (42161)     | <https://orderbook.premia.finance>      |

### <mark style="color:blue;">Publish Quotes</mark>

To submit a quote to the orderbook, `POST` quotes can be used.  In the background, we will take this quote an submit an event on Arbitrum Nova on the users behalf.  One the quote event is generated on Arbitrum Nova, it will be added to the orderbook.

{% openapi src="/files/5nbQ6z0IDC4AGIP2Jlod" path="/quotes" method="post" %}
[cloud.yaml](https://3519168136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyZYDiwOkAUTz3OWc6dGF%2Fuploads%2FVsz02KIxPrTutilZNTun%2Fcloud.yaml?alt=media\&token=7b3ec2b8-fd44-4fb2-95e1-155c3514059f)
{% endopenapi %}

{% tabs %}
{% tab title="Publish Quote Example" %}

```javascript
// Javascript Sample Code
const { fetch } = require ('cross-fetch')
const { parseEther } = require("ethers");

const url = 'https://test.orderbook.premia.finance/quotes'

// Free or Paid Tier API KEY
const MOCK_API_KEY = '3423ee2bfd89491f82b351404ea8c3b7'

// object array of one or more quotes
const mockQuotes = [{
  poolKey: {
    base: '0x9f5D1212514Ac88E26c523387C60F87B67AD1130',
    quote: '0x53421DB1f41368E028A4239954feB5033C7B3729',
    oracleAdapter: '0xB89756634Bae979d13721d9883e67CF22cc31D6b',
    strike: parseEther('2900').toString(),
    maturity: 1688716800,
    isCallPool: false
  },
  chainId: '421613'
  provider: '0x9E600587b9035a8C1254E8256F4E588CC33B8467',
  taker: '0x0000000000000000000000000000000000000000',
  price: parseEther('.195').toString(),
  size: parseEther('1').toString(),
  isBuy: false,
  deadline: 1686592096,
  salt: 1686584896,
  signature: {
    r: '0x7feff79a77a023fd8e034066c5bdb78e9b9e5e3804dfc02c0d5b3979b5be8324',
    s: '0x58229484d69566752b48c49326e6eaca2b4fba5372ba638870bda5b58b4fb25e',
    v: 28
  }
}]


async publishQuote(quotes) {
  const response = await fetch(url, {
      method: 'POST',
      headers: {
          'Content-Type': 'application/json',
          'x-apikey': MOCK_API_KEY,
      },
      body: JSON.stringify(quotes),
  })
  
  if (!response.ok) {
    console.error('Request failed: ', await response.json())
    throw new Error(`Failed to publish quotes: ${response.statusText}`)
  }
		
  return response.json()
}


publishQuote(mockQuotes)
```

{% endtab %}
{% endtabs %}

### <mark style="color:blue;">Get Quotes</mark>

When using `GET` quotes, orders are returned based on the params details provided.  `quotes` endpoint is ideal for determining which order(s) will satisfy a specific order `size` and `side`. The returned quotes are ordered by price, and only the order(s) that satisfy the `size` (cumulatively) will be returned.&#x20;

Additionally, it is possible to receive RFQ quotes  along with public quotes by specifying a `taker` address.  The allows users to find the best possible public/private quote combination for a particular quote size.

{% openapi src="/files/LncIVoWyVPrjAKzio9hv" path="/quotes" method="get" %}
[openapi3\_0.yaml](https://3519168136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyZYDiwOkAUTz3OWc6dGF%2Fuploads%2FawubrCnuv7akeniV1WCy%2Fopenapi3_0.yaml?alt=media\&token=da6264b0-3268-40a5-a439-ec089f68755f)
{% endopenapi %}

{% tabs %}
{% tab title="Get Quotes Example" %}

<pre class="language-javascript"><code class="lang-javascript">// Javascript Sample Code
<strong>const { fetch } = require ('cross-fetch')
</strong>const { parseEther } = require("ethers");

const baseUrl = 'https://test.orderbook.premia.finance'

// Free or Paid Tier API KEY
const MOCK_API_KEY = '3423ee2bfd89491f82b351404ea8c3b7'

// Params
const poolAddress='0xb9e594644D3BB24cfcBa3FA0289F18dB7cf81573'
const size= parseEther('5').toString()
const side='bid' //Side is 'ask'('bid') if the intention is to buy(sell). 
const chainId='421613'


async getQuotes(_addr, _size, _side, _chainId){
  const url = `${baseUrl}/quotes?poolAddress=${_addr}&#x26;size=${_size}&#x26;side=${_side}&#x26;chainId=${_chainId}`
	
  const response = await fetch(url, {
    headers: {
      'Content-Type': 'application/json',
      'x-apikey': MOCK_API_KEY
    }
  })
	
  if (!response.ok) {
    console.error('Request failed: ', await response.json())
    throw new Error(`Failed to fetch quote: ${response.statusText}`)
  }
	
  const quotes = await response.json()	
  
  return quotes
}

getQuotes(poolAddress, size, side, chainId)
</code></pre>

{% endtab %}
{% endtabs %}

### <mark style="color:blue;">Get rfq\_quotes</mark>

When publishing an RFQ, users can [listen](/developer-center/apis/orderbook-api/websocket#subscribe-to-quotes-orderbook-and-rfq) for quotes via WEBSOCKET or use the rfq\_quotes endpoint to retrieve only RFQ quotes via REST API.&#x20;

{% openapi src="/files/LncIVoWyVPrjAKzio9hv" path="/rfq\_quotes" method="get" %}
[openapi3\_0.yaml](https://3519168136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyZYDiwOkAUTz3OWc6dGF%2Fuploads%2FawubrCnuv7akeniV1WCy%2Fopenapi3_0.yaml?alt=media\&token=da6264b0-3268-40a5-a439-ec089f68755f)
{% endopenapi %}

{% tabs %}
{% tab title="Get RFQ Quote Example " %}

```javascript
// Javascript Sample Code
const { fetch } = require ('cross-fetch')

const baseUrl = 'https://test.orderbook.premia.finance'

// Free or Paid Tier API KEY
const MOCK_API_KEY = '3423ee2bfd89491f82b351404ea8c3b7'

// Params
const poolAddress='0xb9e594644D3BB24cfcBa3FA0289F18dB7cf81573'.toLowerCase()
const side='bid'
const chainId='421613'
const takerAddress = '0xd18EE1c241e7A7e59797763C94d2Bd8C9169c831'


async getRfqQuotes(_addr, _side, _chainId, _taker){
  const url = `${baseUrl}/quotes?poolAddress=${_addr}&side=${_side}&chainId=${_chainId}&taker=${_taker}`
	
  const response = await fetch(url, {
    headers: {
      'Content-Type': 'application/json',
      'x-apikey': MOCK_API_KEY
    }
  })
	
  if (!response.ok) {
    console.error('Request failed: ', await response.json())
    throw new Error(`Failed to fetch quote: ${response.statusText}`)
  }
	
  const rfqQuotes = await response.json()	
  
  return rfqQuotes
}

getRfqQuotes(poolAddress, side, chainId, takerAddress)

```

{% endtab %}
{% endtabs %}

### <mark style="color:blue;">Get Orders</mark>

`GET` orders is a *general purpose* query of orders in the orderbook.  Many of the params are optional to suit the needs of the query.  Orders are returned in descending order based on the *timestamp* in which they were created.

{% openapi src="/files/5nbQ6z0IDC4AGIP2Jlod" path="/orders" method="get" %}
[cloud.yaml](https://3519168136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyZYDiwOkAUTz3OWc6dGF%2Fuploads%2FVsz02KIxPrTutilZNTun%2Fcloud.yaml?alt=media\&token=7b3ec2b8-fd44-4fb2-95e1-155c3514059f)
{% endopenapi %}

{% hint style="warning" %}
Good To Know: `size` param in `GET` orders is not the same as `size` param in `GET` quotes. See param descriptions.
{% endhint %}

{% tabs %}
{% tab title="Get Orders Example" %}

```javascript
// Javascript Sample Code
const { fetch } = require ('cross-fetch')

const baseUrl = 'https://test.orderbook.premia.finance'

// Free or Paid Tier API KEY
const MOCK_API_KEY = '3423ee2bfd89491f82b351404ea8c3b7'

// Params
const poolAddress='0xb9e594644D3BB24cfcBa3FA0289F18dB7cf81573'
const chainId='421613'


async getOrders(_addr, _chainId){
  const url = `${baseUrl}/orders?poolAddress=${_addr}&chainId=${_chainId}`
	
  const response = await fetch(url, {
    headers: {
      'Content-Type': 'application/json',
      'x-apikey': MOCK_API_KEY
    }
  })
	
  if (!response.ok) {
    console.error('Request failed: ', await response.json())
    throw new Error(`Failed to fetch quote: ${response.statusText}`)
  }
	
  const orders = await response.json()	
  
  return orders
}

getOrders(poolAddress, chainId)
```

{% endtab %}
{% endtabs %}


# WEBSOCKET

Websocket Functionality

### <mark style="color:blue;">Overview</mark>

| Chain                    | Websocket Url                     |
| ------------------------ | --------------------------------- |
| Arbitrum Goerli (421613) | wss\://test.quotes.premia.finance |
| Arbitrum One (42161)     | wss\://quotes.premia.finance      |

Using the WEBSOCKET connection, it is possible to:

* [*<mark style="color:blue;">Stream</mark>*](#subscribe-to-quotes-orderbook-and-rfq) public/RFQ quotes from the orderbook in realtime
* [*<mark style="color:green;">Publish</mark>*](#publish-rfq-request-s) an RFQ requests (for market takers) to *receive personalized* quotes
* [*<mark style="color:green;">Stream</mark>*](#subscribe-to-rfq-requests) *RFQ* requests (for market makers) to subsequently provide personalize quotes

### <mark style="color:blue;">Authorize Websocket</mark>

Upon connection with the Websocket server, users must send an `AUTH` message with an api key.  If this step is not done, any requests to *Stream* quotes or *Publish* RFQ requests will be denied.&#x20;

{% tabs %}
{% tab title="Authorization Websocket Example" %}

```javascript
// Javascript Sample Code
const { WebSocket } = require('ws')

const wsUrl = 'test.quotes.premia.finance'
const MOCK_API_KEY = '3423ee2bfd89491f82b351404ea8c3b7'

const authMessage = {
  type: "AUTH",
  apiKey: MOCK_API_KEY,
  body: null
}


const ws = new WebSocket(`wss://${wsUrl}`)
function connectWebsocket() {
  ws.onopen = (event) => {
    console.log("Websocket connection open")
    ws.send(JSON.stringify(authMessage))
    ws.onmessage = (event) => {
      console.log(JSON.parse(event.data).message)
      ws.close()
    }
  }
}

connectWebsocket()
```

{% endtab %}
{% endtabs %}

### <mark style="color:blue;">Subscribe to Quotes (Orderbook & RFQ)</mark>

Subscribing to quotes allows a user to stream real time quotes that are published to the orderbook along with any private quotes that may also be available from an [RFQ request](#publish-rfq-request-s).  By default, ALL public quotes are subscribed to upon authorization of a websocket connection. `FILTER` messages are required.

{% tabs %}
{% tab title="Subscribe to Filtered Quotes Example" %}

```javascript
// Javascript Sample Code
const { WebSocket } = require('ws')
const { parseEther } = require("ethers");

const wsUrl = 'test.quotes.premia.finance'
const MOCK_API_KEY = '3423ee2bfd89491f82b351404ea8c3b7'

const authMessage = {
  type: "AUTH",
  apiKey: MOCK_API_KEY,
  body: null
}

/*
Optional params in body include:
poolAddress -> specific option market
size -> stringified 10^18 value
side -> 'bid' or 'ask'
taker -> taker address (use if publishing RFQ and want to receive personal quotes)
provider -> quote provider address
 */
const filterMessage = {
  type: 'FILTER',
  channel: 'QUOTES',
  body: {
    chainId: '421613',
    poolAddress: '0xeB785e131784ea28b6B64B605CF8aa83D69793b5'
  }
}

const ws = new WebSocket(`wss://${wsUrl}`)
function connectWebsocket() {
  ws.onopen = (event) => {
    console.log("Websocket connection open")
    ws.send(JSON.stringify(authMessage))
    ws.onmessage = (event) => {
      console.log(JSON.parse(event.data).message)
      sendMessage(filterMessage)
    }
  }
}

function sendMessage(_message){
  ws.onmessage = (event) => {
    console.log(JSON.parse(event.data).message)
  }
  ws.send(JSON.stringify(_message))
  setTimeout(() => {
    console.log("Closing connection")
    ws.close()
  }, 1000)
}

connectWebsocket()
		
```

{% endtab %}
{% endtabs %}

### <mark style="color:blue;">Publish RFQ Request(s)</mark>

If the desire is to send an RFQ request to receive personalized quotes, it must be done by sending an `RFQ` message type.  Please note that in order to RECEIVE these personalized quotes via websocket, the `FILTER` message when subscribing to quotes must include the `taker` address.  Alternatively, it is possible to use the get [rfqQuotes](/developer-center/apis/orderbook-api/rest-api#get-rfq_quotes) REST API endpoint.

{% tabs %}
{% tab title="Publish RFQ Example" %}

```javascript
// Javascript Sample Code
const { WebSocket } = require('ws')
const { parseEther } = require("ethers");

const wsUrl = 'test.quotes.premia.finance'
// or quotes.premia.finance for prod environment

const MOCK_API_KEY = '3423ee2bfd89491f82b351404ea8c3b7'

const authMessage = {
  type: "AUTH",
  apiKey: MOCK_API_KEY,
  body: null
}

// All fields are required
const rfqPublishMessage = {
  type: 'RFQ',
  body: {
    poolKey: {
      	base: '0x7F5bc2250ea57d8ca932898297b1FF9aE1a04999'
	quote: '0x53421DB1f41368E028A4239954feB5033C7B3729'
	oracleAdapter: string
	// serialised bigint
	strike: parseEther('1700').toString()
	// make sure maturities either tomorrow, 
	// the day after tomorrow, 
	// each Friday of current month, 
	// last Friday of each next month
	// 8:00 AM UTC
	maturity: 1702022400
	isCallPool: boolean
    },
    side: 'ask',
    chainId: '421613', // or '42161' for prod environment
    size: parseEther('1').toString(),
    taker: '0x3D1dcc44D65C08b39029cA8673D705D7e5c4cFF2'
  }
}

const ws = new WebSocket(`wss://${wsUrl}`)
function connectWebsocket() {
  ws.onopen = (event) => {
    console.log("Websocket connection open")
    ws.send(JSON.stringify(authMessage))
    ws.onmessage = (event) => {
      console.log(JSON.parse(event.data).message)
      sendMessage(rfqPublishMessage)
    }
  }
}

function sendMessage(_message){
  ws.onmessage = (event) => {
    console.log(JSON.parse(event.data).message)
  }
  ws.send(JSON.stringify(_message))
  setTimeout(() => {
    console.log("Closing connection")
    ws.close()
  }, 1000)
}

connectWebsocket()
```

{% endtab %}
{% endtabs %}

### <mark style="color:blue;">Subscribe to RFQ Requests</mark>

As a market maker who would like to provide quotes to users who want to utilize RFQ, it will require subscribing to requests to be alerted when a request is made.  In order to respond to an RFQ, market maker must publish quotes (via rest api), with the `takerAddress` populated with the requesters address, otherwise the quote is fillable by any party and will likely be missed by the requester who is listening for quotes with their address populated in the `takerAddress` field of a quote.

{% tabs %}
{% tab title="Subscribe to RFQ Example" %}

```javascript
// Javascript Sample Code
const { WebSocket } = require('ws')

const wsUrl = 'test.quotes.premia.finance'
const MOCK_API_KEY = '3423ee2bfd89491f82b351404ea8c3b7'

const authMessage = {
  type: "AUTH",
  apiKey: MOCK_API_KEY,
  body: null
}

/*
chainId is required.
Optional params in body include:
poolAddress -> specific option market
side -> 'bid' or 'ask'
 */
const rfqListenMessage = {
  type: 'FILTER',
  channel: 'RFQ',
  body: {
    chainId: '421613',
  },
}

const ws = new WebSocket(`wss://${wsUrl}`)
function connectWebsocket() {
  ws.onopen = (event) => {
    console.log("Websocket connection open")
    ws.send(JSON.stringify(authMessage))
    ws.onmessage = (event) => {
      console.log(JSON.parse(event.data).message)
      sendMessage(rfqListenMessage)
    }
  }
}

function sendMessage(_message){
  ws.onmessage = (event) => {
    console.log(JSON.parse(event.data).message)
  }
  ws.send(JSON.stringify(_message))
  setTimeout(() => {
    console.log("Closing connection")
    ws.close()
  }, 1000)
}

connectWebsocket()
```

{% endtab %}
{% endtabs %}


# Subgraph API

### <mark style="color:blue;">Overview</mark>

The Premia Subgraph is available on every chain the protocol is available on. The subgraph efficiently indexes expensive-to-store data emitted on-chain, to enable applications to query more advanced data much faster and with less computation than querying these values from an Ethereum node provider (such as Infura, Alchemy, Ankr, etc).

These subgraphs are hosted on The Graph hosted service and can be used to query Premia data.

<mark style="color:blue;">**Premia V3 Arbitrum Goerli**</mark>[**​**](https://docs.uniswap.org/api/subgraph/overview#v3)

* [Explorer Page](https://thegraph.com/hosted-service/subgraph/premian-labs/premia-blue)
* [Graphql Endpoint](https://api.thegraph.com/subgraphs/name/premian-labs/premia-blue)
* [Code](https://github.com/Premian-Labs/v3-subgraph)


# Containerized API

### <mark style="color:blue;">Overview</mark>

The containerized API is specifically for traders and institutions who would like to programmatically trade on Premia's orderbook. It includes all the features in the [Orderbook API](/developer-center/apis/orderbook-api) (please read this section for better understanding of how the orderbook works) and abstracts away all other web3 functionality needed for *trading*.  Unlike the Orderbook API, which is hosted by Premia, the Containerized API is *self hosted* by the individual trader or institution either on a local computer (individual) or cloud service (institution) of choice. &#x20;

{% hint style="success" %}
Premia does not manage or maintain any private keys for users of the Containerized API.&#x20;
{% endhint %}

### <mark style="color:blue;">Architecture</mark>

Premia is responsible for the maintenance of the repository for the Containerized API. This  repository can simply be cloned and stored either on a local computer of server.  It acts as the *middle man* between the traders code and protocol interaction.  While the contents of the docker container were written in Typescript, this is not necessarily important to a trader.  Any language can be used to programmatically trade.

Even if a trader is not familiar with Typescript or Docker, the setup process is user friendly and saves considerable amount of development time.  Detailed instructions on the setup of the container can be found in the repository.

<figure><img src="/files/QzrchMYjo3JNnJ15qZyL" alt=""><figcaption><p>Containerized API Architecture</p></figcaption></figure>

### <mark style="color:blue;">Setup Instructions</mark>

Detailed setup instructions for the Containerized API can be found directly in the repository README.  Once setup is complete, please review the [API Reference](/developer-center/apis/containerized-api/api-reference) section which provides a user friendly guide to accessing all the available endpoints.

### <mark style="color:blue;">Note about USDC vs USDCe (Bridged USDC)</mark>

{% hint style="success" %}
IMPORTANT:  The containerized api uses token symbols instead of addresses when interacting with the endpoints.  When using `USDC` as the quote token symbol, it is implied that the token being used is `USDCe` (bridged USDC). Please make sure all approvals are done for USDCe, but when interacting with the container use the symbol USDC.  \
\
The USDCe contract can be found [here](https://arbiscan.io/address/0xFF970A61A04b1cA14834A43f5dE4533eBDDB5CC8).
{% endhint %}


# API Reference

## <mark style="color:blue;">Overview</mark>

Once the containerized API is set up, it's time to get familiar with the endpoints and the specifications required to process requests. There are many languages that can be used to access the endpoints. Its important for users to be comfortable with best practices for using APIs in their language of choice. &#x20;

Some examples of convenience packages used in various languages include:

| Language   | Package  | Reference                                                                                      |
| ---------- | -------- | ---------------------------------------------------------------------------------------------- |
| Javascript | axios    | [Circleci Blog](https://circleci.com/blog/making-http-requests-with-axios/)                    |
| Python     | requests | [Real Python](https://realpython.com/api-integration-in-python/)                               |
| Golang     | http     | [Go Dev](https://pkg.go.dev/net/http)                                                          |
| Java       | spring   | [Spring Docs](https://docs.spring.io/spring-framework/reference/integration/rest-clients.html) |
| Scala      | http4s   | [http4s Github](https://github.com/http4s/http4s)                                              |


# Orderbook

All endpoints that begin with `/orderbook/` are related to actions surrounding *<mark style="color:orange;">quotes</mark>* and *<mark style="color:orange;">trading</mark>* on the orderbook. The core trading logic and the required data needed to trade can be found within this entity.

{% hint style="info" %}
While receiving quotes does not require any additional coding logic other than a rest api call, please be aware that when trading, it is important to make sure that you have approved the movement of your collateral prior to filling an order.  More details on this can be found in [Collateral Approval](/developer-center/apis/containerized-api/api-reference/account/collateral-approval).
{% endhint %}


# Quotes

{% openapi src="/files/TH4OafzoH3YU0bVmWOr1" path="/orderbook/quotes" method="get" %}
[openapi3\_1 (2).yaml](https://3519168136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyZYDiwOkAUTz3OWc6dGF%2Fuploads%2FNqs6vXE4l3qPGJ22sxsQ%2Fopenapi3_1%20\(2\).yaml?alt=media\&token=ee7e5127-9139-4f5c-b01c-78cc95ba2070)
{% endopenapi %}

{% openapi src="/files/mq5w777uBTzGzq4Wz1Pg" path="/orderbook/quotes" method="post" %}
[orderbook-api.yaml](https://3519168136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyZYDiwOkAUTz3OWc6dGF%2Fuploads%2Fpqs6t2fsRy5WHDTvmEV1%2Forderbook-api.yaml?alt=media\&token=734f3f09-b4b2-40ef-8bf6-52c194515774)
{% endopenapi %}

{% openapi src="/files/TH4OafzoH3YU0bVmWOr1" path="/orderbook/quotes" method="delete" %}
[openapi3\_1 (2).yaml](https://3519168136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyZYDiwOkAUTz3OWc6dGF%2Fuploads%2FNqs6vXE4l3qPGJ22sxsQ%2Fopenapi3_1%20\(2\).yaml?alt=media\&token=ee7e5127-9139-4f5c-b01c-78cc95ba2070)
{% endopenapi %}

{% openapi src="/files/TH4OafzoH3YU0bVmWOr1" path="/orderbook/quotes" method="patch" %}
[openapi3\_1 (2).yaml](https://3519168136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyZYDiwOkAUTz3OWc6dGF%2Fuploads%2FNqs6vXE4l3qPGJ22sxsQ%2Fopenapi3_1%20\(2\).yaml?alt=media\&token=ee7e5127-9139-4f5c-b01c-78cc95ba2070)
{% endopenapi %}


# Orders

{% openapi src="/files/mq5w777uBTzGzq4Wz1Pg" path="/orderbook/orders" method="get" %}
[orderbook-api.yaml](https://3519168136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyZYDiwOkAUTz3OWc6dGF%2Fuploads%2Fpqs6t2fsRy5WHDTvmEV1%2Forderbook-api.yaml?alt=media\&token=734f3f09-b4b2-40ef-8bf6-52c194515774)
{% endopenapi %}


# Pool

All endpoints that begin with `/Pool/` are related to actions surrounding *position* (inactive) & *collateral* release.  In order to make sure that collateral is not unnecessarily tied up, these end points will need to be called from time to time to help *<mark style="color:orange;">release</mark>* your collateral in positions that do not represent *<mark style="color:orange;">active</mark>* exposure. &#x20;

{% hint style="success" %}
The [Options Balances](/developer-center/apis/containerized-api/api-reference/account/option-balances) endpoint can be used to determine what *inactive* positions are held.&#x20;
{% endhint %}


# Settle

{% openapi src="/files/TH4OafzoH3YU0bVmWOr1" path="/pool/settle" method="post" %}
[openapi3\_1 (2).yaml](https://3519168136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyZYDiwOkAUTz3OWc6dGF%2Fuploads%2FNqs6vXE4l3qPGJ22sxsQ%2Fopenapi3_1%20\(2\).yaml?alt=media\&token=ee7e5127-9139-4f5c-b01c-78cc95ba2070)
{% endopenapi %}


# Exercise

{% openapi src="/files/TH4OafzoH3YU0bVmWOr1" path="/pool/exercise" method="post" %}
[openapi3\_1 (2).yaml](https://3519168136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyZYDiwOkAUTz3OWc6dGF%2Fuploads%2FNqs6vXE4l3qPGJ22sxsQ%2Fopenapi3_1%20\(2\).yaml?alt=media\&token=ee7e5127-9139-4f5c-b01c-78cc95ba2070)
{% endopenapi %}


# Annihilate

{% openapi src="/files/TH4OafzoH3YU0bVmWOr1" path="/pool/annihilate" method="post" %}
[openapi3\_1 (2).yaml](https://3519168136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyZYDiwOkAUTz3OWc6dGF%2Fuploads%2FNqs6vXE4l3qPGJ22sxsQ%2Fopenapi3_1%20\(2\).yaml?alt=media\&token=ee7e5127-9139-4f5c-b01c-78cc95ba2070)
{% endopenapi %}


# Account

All endpoints that begin with `/Account/` are primarily related to account balances of collateral, native token (ETH), and options . Setting account collateral approvals can also be done through this entity. &#x20;

{% hint style="success" %}
When trying to fill an order, collateral must be used if you are "opening" a position.  This requires that approvals are set to a minimum of the trade size. If existing option positions exist, approvals are not needed since collateral is not used.&#x20;
{% endhint %}


# Collateral Approval

{% openapi src="/files/TH4OafzoH3YU0bVmWOr1" path="/account/collateral\_approval" method="post" %}
[openapi3\_1 (2).yaml](https://3519168136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyZYDiwOkAUTz3OWc6dGF%2Fuploads%2FNqs6vXE4l3qPGJ22sxsQ%2Fopenapi3_1%20\(2\).yaml?alt=media\&token=ee7e5127-9139-4f5c-b01c-78cc95ba2070)
{% endopenapi %}


# Orders

{% openapi src="/files/TH4OafzoH3YU0bVmWOr1" path="/account/orders" method="get" %}
[openapi3\_1 (2).yaml](https://3519168136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyZYDiwOkAUTz3OWc6dGF%2Fuploads%2FNqs6vXE4l3qPGJ22sxsQ%2Fopenapi3_1%20\(2\).yaml?alt=media\&token=ee7e5127-9139-4f5c-b01c-78cc95ba2070)
{% endopenapi %}


# Collateral Balances

{% openapi src="/files/TH4OafzoH3YU0bVmWOr1" path="/account/collateral\_balances" method="get" %}
[openapi3\_1 (2).yaml](https://3519168136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyZYDiwOkAUTz3OWc6dGF%2Fuploads%2FNqs6vXE4l3qPGJ22sxsQ%2Fopenapi3_1%20\(2\).yaml?alt=media\&token=ee7e5127-9139-4f5c-b01c-78cc95ba2070)
{% endopenapi %}


# Native Balance

{% openapi src="/files/TH4OafzoH3YU0bVmWOr1" path="/account/native\_balance" method="get" %}
[openapi3\_1 (2).yaml](https://3519168136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyZYDiwOkAUTz3OWc6dGF%2Fuploads%2FNqs6vXE4l3qPGJ22sxsQ%2Fopenapi3_1%20\(2\).yaml?alt=media\&token=ee7e5127-9139-4f5c-b01c-78cc95ba2070)
{% endopenapi %}


# Option Balances

{% openapi src="/files/TH4OafzoH3YU0bVmWOr1" path="/account/option\_balances" method="get" %}
[openapi3\_1 (2).yaml](https://3519168136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyZYDiwOkAUTz3OWc6dGF%2Fuploads%2FNqs6vXE4l3qPGJ22sxsQ%2Fopenapi3_1%20\(2\).yaml?alt=media\&token=ee7e5127-9139-4f5c-b01c-78cc95ba2070)
{% endopenapi %}


# Pools

Endpoints that begin with `/pools/` path provides user control over option pools lifecycle: use can fetch all available pools (optionally filtered by `base` token, `quote` token, `expiration` date) and deploy a new option pool.

{% hint style="success" %}
If some option pools is *already deployed,* `POST /pools` will handle this case gracefully without an error.
{% endhint %}

{% hint style="warning" %}
`` `GET /pools` ``returns *only* the pools been deployed 90 days ago or later.
{% endhint %}


# Find Pools

{% openapi src="/files/TH4OafzoH3YU0bVmWOr1" path="/pools" method="get" %}
[openapi3\_1 (2).yaml](https://3519168136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyZYDiwOkAUTz3OWc6dGF%2Fuploads%2FNqs6vXE4l3qPGJ22sxsQ%2Fopenapi3_1%20\(2\).yaml?alt=media\&token=ee7e5127-9139-4f5c-b01c-78cc95ba2070)
{% endopenapi %}


# Create Pools

{% openapi src="/files/XEZCMqggbmkDrLDFr2Tt" path="/pools" method="post" %}
[openapi3\_1 (1).yaml](https://3519168136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyZYDiwOkAUTz3OWc6dGF%2Fuploads%2Fe0jcwsYeh3z1eiMXtBEn%2Fopenapi3_1%20\(1\).yaml?alt=media\&token=b2f9e4ff-b40f-4ca9-ad8a-451e62ae9b66)
{% endopenapi %}


# Valid Maturities

{% openapi src="/files/TH4OafzoH3YU0bVmWOr1" path="/pools/maturities" method="get" %}
[openapi3\_1 (2).yaml](https://3519168136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyZYDiwOkAUTz3OWc6dGF%2Fuploads%2FNqs6vXE4l3qPGJ22sxsQ%2Fopenapi3_1%20\(2\).yaml?alt=media\&token=ee7e5127-9139-4f5c-b01c-78cc95ba2070)
{% endopenapi %}


# Valid Strikes

{% openapi src="/files/TH4OafzoH3YU0bVmWOr1" path="/pools/strikes" method="get" %}
[openapi3\_1 (2).yaml](https://3519168136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyZYDiwOkAUTz3OWc6dGF%2Fuploads%2FNqs6vXE4l3qPGJ22sxsQ%2Fopenapi3_1%20\(2\).yaml?alt=media\&token=ee7e5127-9139-4f5c-b01c-78cc95ba2070)
{% endopenapi %}


# Oracles

Endpoints that begin with `/oracles/` path provide users with access to data that is used within premia across various parts of the platform including by not limited to price settlement of options, unrealized PnL calculations, option pricing for vaults, and more. By accessing these endpoints, it is easier for users to know what values are being used for various calculations.&#x20;


# IV

Currently, the following markets are available to query IV from our IV oracles: <mark style="color:blue;">WETH</mark>, <mark style="color:blue;">WBTC</mark>, <mark style="color:blue;">ARB</mark>, <mark style="color:blue;">LINK</mark>, <mark style="color:blue;">WSTETH</mark>, <mark style="color:blue;">GMX</mark>, <mark style="color:blue;">MAGIC</mark>, <mark style="color:blue;">SOL</mark>, <mark style="color:blue;">FXS</mark>.  Please note that each market uses USD as the quote asset.&#x20;

{% openapi src="/files/TH4OafzoH3YU0bVmWOr1" path="/oracles/iv" method="get" %}
[openapi3\_1 (2).yaml](https://3519168136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyZYDiwOkAUTz3OWc6dGF%2Fuploads%2FNqs6vXE4l3qPGJ22sxsQ%2Fopenapi3_1%20\(2\).yaml?alt=media\&token=ee7e5127-9139-4f5c-b01c-78cc95ba2070)
{% endopenapi %}


# Spot

Spot oracles used by the Premia Protocol can be accessed with this endpoint.  Currently, our data is obtained form Chainlink oracles, but more oracle adapters may be available in the future.

{% openapi src="/files/TH4OafzoH3YU0bVmWOr1" path="/oracles/spot" method="get" %}
[openapi3\_1 (2).yaml](https://3519168136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyZYDiwOkAUTz3OWc6dGF%2Fuploads%2FNqs6vXE4l3qPGJ22sxsQ%2Fopenapi3_1%20\(2\).yaml?alt=media\&token=ee7e5127-9139-4f5c-b01c-78cc95ba2070)
{% endopenapi %}


# Vaults

Endpoints that begin with `/vaults/` allow direct access to approved vaults integrated with Premia Protocol to receive quotes and trade.

Currently, the following markets are available for puts and calls: <mark style="color:blue;">WETH</mark>, <mark style="color:blue;">WBTC</mark>, <mark style="color:blue;">ARB</mark>, <mark style="color:blue;">LINK</mark>, <mark style="color:blue;">WSTETH</mark>, <mark style="color:blue;">GMX</mark>, <mark style="color:blue;">MAGIC</mark>, <mark style="color:blue;">SOL</mark>, <mark style="color:blue;">FXS</mark>.&#x20;


# Quote

{% openapi src="/files/TH4OafzoH3YU0bVmWOr1" path="/vaults/quote" method="get" %}
[openapi3\_1 (2).yaml](https://3519168136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyZYDiwOkAUTz3OWc6dGF%2Fuploads%2FNqs6vXE4l3qPGJ22sxsQ%2Fopenapi3_1%20\(2\).yaml?alt=media\&token=ee7e5127-9139-4f5c-b01c-78cc95ba2070)
{% endopenapi %}


# Trade

To trade with a va

{% openapi src="/files/TH4OafzoH3YU0bVmWOr1" path="/vaults/trade" method="post" %}
[openapi3\_1 (2).yaml](https://3519168136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyZYDiwOkAUTz3OWc6dGF%2Fuploads%2FNqs6vXE4l3qPGJ22sxsQ%2Fopenapi3_1%20\(2\).yaml?alt=media\&token=ee7e5127-9139-4f5c-b01c-78cc95ba2070)
{% endopenapi %}


# WebSockets Reference

Overview

Their are *two* major *channels* within the WS connection, they are:

### [Quotes](/developer-center/apis/containerized-api/websockets-reference/quotes-channel)

Receive messages regarding *changes* to the orderbook state along with responses back from an RFQ *requests*&#x20;

[*<mark style="color:green;">Stream</mark>*](#subscribe-to-quotes-orderbook-and-rfq)  *public* orderbook state changes such as:

* <mark style="color:orange;">PostQuoteMessage</mark> -> new orders
* <mark style="color:orange;">FillQuoteMessage</mark> -> trade fills
* <mark style="color:orange;">DeleteQuoteMessage</mark> -> cancelled orders

*<mark style="color:green;">Stream</mark>* *personalized* quotes from market makers after submitting a RFQ

### [RFQ](/developer-center/apis/containerized-api/websockets-reference/rfq-channel)

Participate in the RFQ network&#x20;

[*<mark style="color:green;">Publish</mark>*](#publish-rfq-request-s) RFQ requests to the RFQ network.  This is how requests are broadcasted.

[*<mark style="color:green;">Stream</mark>*](#subscribe-to-rfq-requests)  RFQ requests in order to *provide* personalized quotes.  This is how market makers listen for requests.

{% hint style="info" %}
Participating the in the RFQ network (both as a requester and provider of quotes) can *only* be done via the RFQ channel of our websocket.  There is *no* direct rest endpoints.
{% endhint %}

### <mark style="color:blue;">Dual Channel Support</mark>

It is possible to integrate BOTH channels at the same time under a single websocket connection.  In this case there only needs to be one authorization methods (see [here](/developer-center/apis/containerized-api/websockets-reference/authorization) on how to implement this).  However, two filter messages must be sent (one for each channel).&#x20;

Authorizations and Filter messages are covered in the next section.&#x20;


# Authorization

### <mark style="color:blue;">Authorization Flow</mark>

Upon connection with the Websocket server, users must first send an `AUTH` message with an api key.  If this step is not done, any requests to *<mark style="color:blue;">Stream</mark>* public/RFQ quotes, *<mark style="color:green;">Publish</mark>* RFQ requests, or *<mark style="color:blue;">Stream</mark>* RFQ requests will be denied.&#x20;

### <mark style="color:blue;">API KEY</mark>

In order to use websockets, an api key is required.  Currently, all api key requests must be made to <mark style="color:blue;"><research@premia.finance></mark>.  Please use subject line: 'API KEY REQUEST' and an api key will be returned. &#x20;

{% tabs %}
{% tab title="Authorization " %}

```typescript
/*
TypeScript Sample Code
NOTE: since this is an API,  WS logic can be written in any language. This example
is in typescript, but the overall sequence will be the same for any language.
*/

import { RawData, WebSocket } from 'ws'

// Example if Containerized API runtime is local
const url = `ws://localhost:${process.env.HTTP_PORT}`
const wsConnection = new WebSocket(url)
const MOCK_API_KEY = '3423ee2bfd89491f82b351404'

const authMessage: AuthMessage = {
  type: "AUTH",
  apiKey: MOCK_API_KEY,
  body: null
}

// initialize variable to store authorization response
let infoMessage = ''

// handle message ingestion from ws
const wsCallback = (data: RawData) => {
  const message: InfoMessage | ErrorMessage | RFQMessage = JSON.parse(data.toString())
  
  switch (message.type) {
    case 'INFO': {
        // auth result message will arrive here
	infoMessage = message.message
	break
    }
    default: {
  	throw `Unexpected message type ${message.type}`
    }
  }
}

// subscribe/listen to WS messages
wsConnection.on('message', wsCallback)

// send AuthMessage to authorize connection 
wsConnection.send(JSON.stringify(authMsg))

// unsubscribe/remove message listener
wsConnection.off('message', wsCallback)

// should say `Session authorized. Subscriptions enabled.`
console.log(infoMessage)
```

{% endtab %}

{% tab title="Interface" %}

```typescript
// auth message 
interface AuthMessage {
  type: 'AUTH'
  apiKey: string
  body: null
}

// INFO message from Premia orderbook
interface InfoMessage {
  type: 'INFO'
  body: null
  message: string
}
```

{% endtab %}
{% endtabs %}


# Connection

All WS connections have a 30 minute connection duration. Users must incorporate reconnection logic in order to maintain streaming uptime of channels.  An example of this can be found here:

{% tabs %}
{% tab title="Reconnect Example" %}

```typescript
/*
TypeScript Sample Code
NOTE: since this is an API,  WS logic can be written in any language. This example
is in typescript, but the overall sequence will be the same for any language.
*/

import { WebSocket } from 'ws'

// Example if Containerized API runtime is local
const url = `ws://localhost:${process.env.HTTP_PORT}`
const MOCK_API_KEY = '3423ee2bfd89491f82b351404'

const authMessage: AuthMessage = {
  type: "AUTH",
  apiKey: MOCK_API_KEY,
  body: null
}

const connect = () => {
  const wsConnection = new WebSocket(url)
  
  wsConnection.on('open', function() {
    // send AuthMessage to authorize connection 
    wsConnection.send(JSON.stringify(authMsg))
  });
  
  wsConnection.on('close', function() {
   // reconnect after 500 ms
    setTimeout(connect, 500);
  });
  
}

connect()
```

{% endtab %}
{% endtabs %}


# Quotes Channel

The Quote channel is where ALL quotes (limit orders) and state changes to the orderbook can be found. *Additionally, quotes from an RFQ request can also be retrieved here.*

### <mark style="color:blue;">Filter Message (Quotes)</mark>

All channels require a filter message prior to streaming.  Filter messages will define what data is streamed along with activating the stream itself. There are several parameters that can be used to refine the stream.

#### <mark style="color:green;">chainId (Required) :</mark> Designate whether the stream is for a production chain or testnet chain

<mark style="color:green;">poolAddress (Optional):</mark> filter by specific option market

<mark style="color:green;">side (Optional):</mark> filter by either bid only or ask only

<mark style="color:green;">size (Optional):</mark> filter by minimum size

{% hint style="warning" %}
The size parameter must be represented in a string that is in 10^18 format.  For example, if the filter for size is mean to be 2, then value here must be '2000000000000000000'.&#x20;
{% endhint %}

<mark style="color:green;">provider (Optional)</mark>: filter by quote providers

<mark style="color:green;">taker (Optional):</mark> *filter by taker address is IMPORTANT for RFQ network users.*  There are 3 ways to configure this:

1. <mark style="color:orange;">omit:</mark> if this filter param is omitted, then only public quotes will stream.  If there is no intention of using the RFQ network, omit this filter.
2. <mark style="color:orange;">address:</mark>  if the intention is to use the RFQ network to *request* quotes, populate this field with the wallet address of the requester to see all relevant `PostQuote` messages from quote providers
3. <mark style="color:orange;">`*`</mark> -> if the intention is to use the RFQ network to *provide/request* quotes, populate this field with a star to see all relevant `FillQuote` messages.

{% tabs %}
{% tab title="Subscribe/Unsubscribe Quotes" %}

<pre class="language-typescript"><code class="lang-typescript">/*
TypeScript Sample Code
NOTE: since this is an API,  WS logic can be written in any language. This example
is in typescript, but the overall sequence will be the same for any language.
*/

import { RawData, WebSocket } from 'ws'

// Example if Containerized API runtime is local
const url = `ws://localhost:${process.env.HTTP_PORT}`
const wsConnection = new WebSocket(url)
const MOCK_API_KEY = '3423ee2bfd89491f82b351404'


const authMessage: AuthMessage = {
  type: 'AUTH',
  apiKey: MOCK_API_KEY,
  body: null
}

// send AuthMessage
wsConnection.send(JSON.stringify(authMsg))

/*
This filter message will listen to all PUBLIC quote and will additionally
receive PRIVATE quotes from the RFQ network.
*/

const webSocketFilter: FilterMessage = {
  type: 'FILTER',
<strong>  channel: 'QUOTES',
</strong><strong>  body: {
</strong>    chainId: '42161',
    taker: '0x170f9e3eb81ed29491a2efdcfa2edd34fdd24a71' // mock address
  }
}

// handle message ingestion from ws
const wsCallback = (data: RawData) => {
  const message: InfoMessage | PostQuoteMessage | FillQuoteMessage | DeleteQuoteMessage = JSON.parse(data.toString())
    switch (message.type) {
        case 'INFO': {
            // auth result message will arrive here
            break
        }
        case 'POST_QUOTE': {
            // new quotes will arrive here
    	    break
        }
        case 'FILL_QUOTE': {
            // filled quotes will arrive here
    	    break
        }
        case 'DELETE_QUOTE': {
            // cancelled quotes will arrive here
    	    break
        }
        case 'ERROR': {
            // any error message will arrive here
    	    break
        }
        // throw error if case not covered
        default: {
      	    throw `Unexpected message type ${message.type}`
        }
    }
}

// subscribe to WS messages
wsConnection.on('message', wsCallback)

// send FilterMessage to start getting quotes stream
wsConnection.send(JSON.stringify(webSocketFilter))


// unsubscribe to WS messages
// NOTE: unsubscribing does NOT close the ws connection
const unsubscribeMsg: WSUnsubscribeMessage = {
    type: 'UNSUBSCRIBE',
    channel: 'QUOTES',
    body: null,
}

wsConnection.send(JSON.stringify(unsubscribeMsg))
</code></pre>

{% endtab %}

{% tab title="Interface" %}

```typescript
// auth message 
interface AuthMessage {
  type: 'AUTH'
  apiKey: string
  body: null
}

// filter message
interface FilterMessage {
  type: 'FILTER'
  channel: 'QUOTES' | 'RFQ' // which channel to subscribe to
  body: {
    chainId: '42161' | '421613'
    poolAddress?: string
    side?: 'bid' | 'ask'
    size?: string
    provider?: string
    taker?: string
  }
}

// INFO message from Premia orderbook
interface InfoMessage {
  type: 'INFO'
  body: null
  message: string
}

// Quote messages
interface PostQuoteMessage {
  type: 'POST_QUOTE'
  body: ReturnedOrderbookQuote
}

interface FillQuoteMessage {
  type: 'FILL_QUOTE'
  body: ReturnedOrderbookQuote
  size: string
}

interface DeleteQuoteMessage {
  type: 'DELETE_QUOTE'
  body: ReturnedOrderbookQuote
}

// ERROR message from Premia orderbook
interface ErrorMessage {
  type: 'ERROR'
  body: null
  message: string
}

// Quote object
interface ReturnedOrderbookQuote {
  base: string // token name
  quote: string // token name
  expiration: string
  strike: number
  type: 'C' | 'P'
  side: 'bid' | 'ask'
  size: number
  price: number
  deadline: number
  quoteId: string
  ts: number
}

// Unsubscribe message
interface WSUnsubscribeMessage {
    type: 'UNSUBSCRIBE'
    channel: 'QUOTES' | 'RFQ'
    body: null
}
```

{% endtab %}
{% endtabs %}


# RFQ Channel

The RFQ channel is where a user will either *<mark style="color:green;">publish/stream</mark>* a RFQ.  The user who is *<mark style="color:green;">publishing</mark>* a RFQ is the requester for a quote.  They are considered the "taker" in the transaction request.  The user who is *<mark style="color:green;">streaming</mark>* for RFQ's is the provider of the quote. They are considered the "maker" of the quote.&#x20;

{% hint style="success" %}
&#x20;It is important to note that the RFQ channel is <mark style="color:red;">not</mark> where RFQ quotes are actually generated or filled. It is only used to broadcast & listen to requests.

\
When an actual quote is generated by the quote provider, it can only be seen on the Quote channel.  So if you intend to *<mark style="color:green;">publish</mark>* on the RFQ Channel, you will need to *<mark style="color:green;">stream</mark>* on the [Quote Channel](/developer-center/apis/containerized-api/websockets-reference/quotes-channel) to see quotes that are returned to you.\
\
The quote provider who is *<mark style="color:green;">streaming</mark>* on the RFQ Channel will respond to request by [posting](/developer-center/apis/containerized-api/api-reference/orderbook/quotes#orderbook-quotes-1) the quotes via rest api.&#x20;
{% endhint %}

### <mark style="color:blue;">Responding to RFQ (RFQ Streamers Only)</mark>

If you are a *<mark style="color:green;">streamer</mark>* of RFQ's you will need to produce quote objects and post them via REST API.  When doing so, the quotes must have the `takerAddress` populated with the requesters address.  This is an optional param when posting quotes via REST API.  If it is intentionally omitted when posting a quote, the order is considered PUBLIC and can be filled by anyone. &#x20;

{% tabs %}
{% tab title="Publish RFQ " %}

```javascript
/*
TypeScript Sample Code
NOTE: since this is an API,  WS logic can be written in any language. This example
is in typescript, but the overall sequence will be the same for any language.
*/

import { RawData, WebSocket } from 'ws'

// Example for for local container runtime
const url = `ws://localhost:${process.env.HTTP_PORT}`
const wsConnection = new WebSocket(url)
const MOCK_API_KEY = '3423ee2bfd89491f82b351404'


const authMessage: AuthMessage = {
  type: 'AUTH',
  apiKey: MOCK_API_KEY,
  body: null
}

// send AuthMessage
wsConnection.send(JSON.stringify(authMsg))

// IMPORTANT!!! published RFQ messages must be in web3 format
const rfqRequest = {
  type: 'RFQ',
  body: {
    poolKey: {
      	base: '0x7F5bc2250ea57d8ca932898297b1FF9aE1a04999'
	quote: '0x53421DB1f41368E028A4239954feB5033C7B3729'
	oracleAdapter: string
	strike: parseEther('1700').toString()
	maturity: 1702022400
	isCallPool: boolean
    },
    side: 'ask',
    chainId: '421613', // or '42161' for prod environment
    size: parseEther('1').toString(),
    taker: '0x3D1dcc44D65C08b39029cA8673D705D7e5c4cFF2'
  }
}

const wsCallback = (data: RawData) => {
  const message: InfoMessage | ErrorMessage | RFQMessage | PostQuoteMessage | FillQuoteMessage | DeleteQuoteMessage = JSON.parse(data.toString())
    switch (message.type) {
      case 'INFO': {
        // auth result message will arrive here
        break
      }  
      case 'ERROR': {
        // any error message will arrive here
        break
      }
      default: {
        throw `Unexpected message type ${message.type}`
      }
}

// subscribe to WS messages
wsConnection.on('message', wsCallback)

// publish RFQMessage to start getting quotes streamed on QUOTES channel
wsConnection.send(JSON.stringify(rfqRequest))


// unsubscribe to WS messages
// NOTE: unsubscribing does NOT close the ws connection
const unsubscribeMsg: WSUnsubscribeMessage = {
    type: 'UNSUBSCRIBE',
    channel: channel,
    body: null,
}

wsConnection.send(JSON.stringify(unsubscribeMsg))
```

{% endtab %}

{% tab title="Stream RFQ" %}

```typescript
/*
TypeScript Sample Code
NOTE: since this is an API,  WS logic can be written in any language. This example
is in typescript, but the overall sequence will be the same for any language.
*/

import { RawData, WebSocket } from 'ws'

// Example for for local container runtime
const url = `ws://localhost:${process.env.HTTP_PORT}`
const wsConnection = new WebSocket(url)
const MOCK_API_KEY = '3423ee2bfd89491f82b351404'


const authMessage: AuthMessage = {
  type: 'AUTH',
  apiKey: MOCK_API_KEY,
  body: null
}

// send AuthMessage
wsConnection.send(JSON.stringify(authMsg))


const webSocketFilter: FilterMessage = {
  type: 'FILTER',
  channel: 'RFQ',
  body: {
    chainId: '42161',
    taker: '0x170f9e3eb81ed29491a2efdcfa2edd34fdd24a71' // fake address
  }
}

const wsCallback = (data: RawData) => {
  const message: InfoMessage | ErrorMessage | RFQMessage | PostQuoteMessage | FillQuoteMessage | DeleteQuoteMessage = JSON.parse(data.toString())
    switch (message.type) {
      case 'INFO': {
        // auth result message will arrive here
        break
      }
      case 'RFQ': {
        // streamed requests will arrive here
        // business logic to POST quote via REST API HERE
      }  
      case 'ERROR': {
        // any error message will arrive here
        break
      }
      default: {
        throw `Unexpected message type ${message.type}`
      }
}

// subscribe to WS messages
wsConnection.on('message', wsCallback)

// send FilterMessage to start listening to RFQ stream
wsConnection.send(JSON.stringify(webSocketFilter))
```

{% endtab %}

{% tab title="Interface" %}

```typescript
interface AuthMessage {
  type: 'AUTH'
  apiKey: string
  body: null
}

// INFO message from Premia orderbook
interface InfoMessage {
  type: 'INFO'
  body: null
  message: string
}

// ERROR message from Premia orderbook
interface ErrorMessage {
  type: 'ERROR'
  body: null
  message: string
}

// human-readable format of a RFQ request
interface RFQMessage {
  type: 'RFQ'
  body: {
    base: string // base token name i.e. WETH
    quote: string // base token name i.e. USDC
    expiration: string // i.e. 23NOV2023
    strike: number
    type: 'C' | 'P'
    side: 'bid' | 'ask'
    size: number
    taker: string
  }
}

// Unsubscribe message
interface WSUnsubscribeMessage {
    type: 'UNSUBSCRIBE'
    channel: 'QUOTES' | 'RFQ'
    body: null
}
```

{% endtab %}
{% endtabs %}


# SDK

### <mark style="color:blue;">Overview</mark>

The Premia SDK is available in Typescript and is the codebase can be used to query data stored in smart contracts or to modify data on-chain by signing and executing transactions on-chain.

The SDK is separated into three main groups, for simple understanding:

* **Types & Entities**
* **Queries (Reads)**

  Queries only read state from contracts on-chain or subgraphs, never update state.
* **Mutations (Writes)**

  Mutations update the state of a contract on-chain.


# Guides

### <mark style="color:blue;">Quick Start</mark>

The **full SDK** is free to use and open-source, currently available in the following languages:

* **Typescript / Javascript**

> 💡 The full SDK can be used trustlessly to execute any action or query any data from the protocol.

To get started just install the latest stable version of the package with,

```bash
yarn install "@premia/v3-sdk-public"
```

Then use the following code to get started with the minimal setup,

```typescript
API_KEY = '<infura-api-key>'
PRIVATE_KEY = '<private-key>'

premia = await Premia.initialize({
    provider: `https://arbitrum-mainnet.infura.io/v3/${API_KEY}`,
    chainId: SupportedChainId.ARBITRUM,
    privateKey: PRIVATE_KEY
})
```

The Premia v3 SDK is meant to be an all-in-one solution, just instantiate the `Premia` object and you will have access to the following:

* [analytics](https://docs-sdk.premia.finance/classes/AnalyticsAPI.html), query analytics information from the subgraph
* [contracts](https://docs-sdk.premia.finance/classes/ContractAPI.html), find access to the `Contract` types for each of Premia's main contracts.
* [options](https://docs-sdk.premia.finance/classes/OptionAPI.html), an aggregator for different sources of liquidity.
* [orders](https://docs-sdk.premia.finance/classes/OrdersAPI.html), provide and fill quotes through the orderbook (requires an API key).
* [pools](https://docs-sdk.premia.finance/classes/PoolAPI.html), interact with all functionalities related to the option pools.
* [pricing](https://docs-sdk.premia.finance/classes/PricingAPI.html), compare prices of different quotes
* [tokens](https://docs-sdk.premia.finance/classes/TokenAPI.html), query information about tokens in relation to the pools from the subgraph
* [pairs](https://docs-sdk.premia.finance/classes/TokenPairAPI.html), query information about token pairs in relation to the pools from the subgraph
* [transactions](https://docs-sdk.premia.finance/classes/TransactionAPI.html), query information about generic/vault transactions made on the protocol via the subgraph
* [users](https://docs-sdk.premia.finance/classes/UserAPI.html), query user information via the subgraph
* [vaults](https://docs-sdk.premia.finance/classes/VaultAPI.html), interact with all functionalities related to the vaults.
* [vxPremia](https://docs-sdk.premia.finance/classes/VxPremiaAPI.html), interact with all functionalities related to the vxPremia such as vault votes, user stakes, stake histories, and voting histories.

### <mark style="color:blue;">Walkthrough</mark>

#### Making Trades

First, we want to initialize the SDK with the proper configuration

```typescript
API_KEY = '<infura-api-key>'
PREMIA_API_KEY = '<premia-api-key' // Needed for utilizing the orderbook
PRIVATE_KEY = '<private-key>'

premia = await Premia.initialize({
    provider: `https://arbitrum-mainnet.infura.io/v3/${API_KEY}`,
    chainId: SupportedChainId.ARBITRUM,
    privateKey: PRIVATE_KEY,
    apiKey: PREMIA_API_KEY
})
```

Then we need to query the subgraph to see what pools are deployed because this will dictate which listings we end up selecting to get a quote for.

```typescript
const WETH = Addresses[SupportedChainId.ARBITRUM].WETH

const pools = await premia.pools.getPools(WETH)
```

Now that we have a list of available pools, we can filter and sort through them to find out in particular which pools are closest to the strike, maturity, and option type we are aiming for. For the sake of the example, however, we are just going to pick the first pool to demonstrate how to obtain a quote.

```typescript
// Get token contract
const tokenAddress = pools[0].isCall ? pools[0].base.address : pools[0].quote.address
const token = await premia.contracts.getTokenContract(tokenAddress)

// Get quote
const poolAddress = pools[0].address
const quote = await premia.pools.quote(poolAddress, parseEther('1'), true)
```

Now that we have our quote and it seems like it fits our target price range, let's send the transaction and make the trade.

```typescript
// Approve ERC20 token for the premium
await token.approve(quote.approvalTarget, quote.approvalAmount)

// Perform trade on the pool
const tx_response = await premia.pools.trade(poolAddress, {
    size: quote.size,
    isBuy: quote.isBuy,
    premiumLimit: quote.approvalAmount,
    referrer: ZeroAddress
})
```

There you have it, we've made our first trade on Premia!

### <mark style="color:blue;">API Reference</mark>

Detailed API documentation is available [here](https://docs-sdk.premia.finance/).


# SDK Technical Docs

The documentation at [docs-sdk.premia.finance](https://docs-sdk.premia.finance/) provides detailed information about the Premia V3 SDK, an Alpha software used in the Premia Interface. Here's a summary of the key sections:

1. **Alpha Software Warning**: The SDK is considered Alpha software and may contain bugs or significant changes between patch versions.
2. **Development Setup**: Instructions for setting up the development environment, including setting NPM auth tokens, API keys, and running necessary commands.
3. **Anvil Setup**: Guidelines for using Anvil as a local blockchain for development purposes, including installation instructions.
4. **Forking Arbitrum Goerli**: Steps to fork Georli for development, including specific terminal commands.
5. **Contract Deployments**: A list of contract deployment dates on Goerli and Arbitrum Goerli networks.
6. **SDK Documentation**: In-depth documentation on the SDK, including details about various factory functions, structures, queries, and more related to ERC20, IERC1155, IPool, IVault, and other blockchain components.
7. **Utilities and Helpers**: Information about various utilities, formatting functions, and helpers used within the SDK.


# Contracts

*Contracts github repo*: <https://github.com/Premian-Labs/premia-contracts>

| Network          |                                                                                                 |
| ---------------- | ----------------------------------------------------------------------------------------------- |
| Ethereum Mainnet | [📜](https://github.com/Premian-Labs/premia-contracts/blob/master/docs/deployments/ETHEREUM.md) |
| Arbitrum Mainnet | [📜](https://github.com/Premian-Labs/premia-contracts/blob/master/docs/deployments/ARBITRUM.md) |
| Fantom           | [📜](https://github.com/Premian-Labs/premia-contracts/blob/master/docs/deployments/FANTOM.md)   |
| Optimism         | [📜](https://github.com/Premian-Labs/premia-contracts/blob/master/docs/deployments/OPTIMISM.md) |


# Multi-Signature Wallets

### **Operator Treasury & Contract Owner Multi-Signature Wallets (4/5)**

**Ethereum**: [0xc22FAe86443aEed038A4ED887bbA8F5035FD12F0](https://debank.com/profile/0xc22FAe86443aEed038A4ED887bbA8F5035FD12F0)

**Ethereum Finance Delegates**: [0x074F46d86149A7bA0687BBd48aa4F6381A6B364A](https://app.safe.global/home?safe=eth:0x074F46d86149A7bA0687BBd48aa4F6381A6B364A)

**Arbitrum**: [0xa079C6B032133b95Cf8b3d273D27eeb6B110a469](https://debank.com/profile/0xa079c6b032133b95cf8b3d273d27eeb6b110a469)

**Arbitrum Insurance Fund**: [0xa0C49ae8C749A53e9881B226fC0Fa5E570754393](https://app.safe.global/home?safe=arb1:0xa0C49ae8C749A53e9881B226fC0Fa5E570754393)

**Fantom**: [0x0b95674d635c4Cf3E73DD0E4B28b4dcfdccD2Ec2](https://debank.com/profile/0x0b95674d635c4cf3e73dd0e4b28b4dcfdccd2ec2)

**Optimism**: [0xfc5538E1E9814eD6487b407FaD7b5710739A1cC2](https://debank.com/profile/0xfc5538e1e9814ed6487b407fad7b5710739a1cc2)\ <br>

### **Parliament / Blue Descent Treasury Multi-Signature Wallet (11/15)**

**Arbitrum**: [0x8Fb7A635164fb693350AaB6dF8f53d82Df7AABA0](< https://app.safe.global/home?safe=arb1:0x8Fb7A635164fb693350AaB6dF8f53d82Df7AABA0>)


# V3 Protocol

The smart contracts for Premia combine The Premia Protocol, an exchange and settlement engine for crypto options on Arbitrum, and Premia Vaults, a set of automated return and risk-management strategies built on The Premia Protocol. The protocol was developed in-house, while the vault contracts are a joint effort of in-house development and third-party open-source additions.


# Overview

<figure><img src="/files/oPvHQx9Aa2MgJgBKY6RT" alt=""><figcaption><p>Premia Ecosystem</p></figcaption></figure>


# Guides

<figure><img src="/files/PV2SZofagQ53kQZ3ihq5" alt=""><figcaption></figcaption></figure>


# Margin

<figure><img src="/files/PV2SZofagQ53kQZ3ihq5" alt=""><figcaption></figcaption></figure>


# Orderbook

Introduction

<figure><img src="/files/PV2SZofagQ53kQZ3ihq5" alt=""><figcaption></figcaption></figure>


# vxPremia

<figure><img src="/files/PV2SZofagQ53kQZ3ihq5" alt=""><figcaption></figcaption></figure>


# Universal Router

<figure><img src="/files/PV2SZofagQ53kQZ3ihq5" alt=""><figcaption></figcaption></figure>


# Vaults

<figure><img src="/files/PV2SZofagQ53kQZ3ihq5" alt=""><figcaption></figcaption></figure>


# Integrations

<figure><img src="/files/tOzmlXowif1FCko2o3jf" alt=""><figcaption></figcaption></figure>


# Use Cases

<figure><img src="/files/PV2SZofagQ53kQZ3ihq5" alt=""><figcaption></figcaption></figure>


# Code Snippets

<figure><img src="/files/PV2SZofagQ53kQZ3ihq5" alt=""><figcaption></figcaption></figure>




---

[Next Page](/llms-full.txt/1)

