# Swivel Finance Documentation

Documentation for all things Swivel Finance.


# Litepaper

A Basic Description and Visualization of the Swivel Protocol's mechanics.

## Introduction

Concerns surrounding protocols like Compound and Aave have become acceptable for all but the most risk-averse market participants. However, the volatility of DeFi rates still precludes many from effective portfolio/risk management, and others from market participation entirely. \
\
Swivel enables this wider market participation by providing the capital efficient infrastructure and professional trading interface necessary for tokenized cash-flows.

### Tokenizing Cash-Flows (Yield Tokenization)

At it's core, Swivel is built around the concept of cash flow-tokenization (Yield Tokenization).&#x20;

Swivel provides lenders the ability to split an interest generating token into two separate cash-flow tokens until a future date. One token representing the future yield generated (nTokens), and another representing ownership of an underlying token, redeemable at that future date (zcTokens).

In Swivel's design these two are referred to as *nTokens* (yield-generating tokens), and *zcTokens* (tokens redeemable at maturity).

This flexible architecture facilitates a number of interesting use-cases, namely fixed-yield lending and yield boosting (rate-trading), and provides the core infrastructure necessary for fixed-maturity rehypothecation (options markets, futures markets, etc.,).

![Splitting USDC into zcUSDC and nUSDC](/files/-Mc6H50wYjfDYtZ3XzSG)


# zcTokens

ERC-20 Tokens that represent a 1-1 claim for underlying upon maturity.

### Overview

Zero-coupon tokens, ***zcTokens***, are ERC-20's which are redeemable 1:1 at maturity for an underlying token.&#x20;

As users lock-in fixed yields, their deposit is split into zcTokens and nTokens and the the nTokens minted are sold to fuel a fixed-yield.&#x20;

This leaves the lender with an immediate fixed-yield and their minted zcTokens.

**Fixed-Yield Lending:**

**Alice has 1000 USDC.**\
**Alice fills Bob's order, splitting 1000 USDC into 1000 zcUSDC and 1000 nUSDC.**\
**Alice sells 1000 nUSDC to Bob for 50 USDC.**\
**Alice then has 1000 zcUSDC. At maturity Alice redeems her 1000zcUSDC for 1000 USDC.**\
**This leaves Alice with 1050 USDC.**

![Lending 1000 USDC at 5% for 1 Year](/files/-McMBa9H_9LjbQBOA7Gv)

### Pricing

Given zcTokens represent a 1-1 redemption only upon maturity, they are discounted at a rate based on the predicted amount of interest that may have otherwise been generated until the maturity/redemption date (the nToken price).

Accepting that this potential yield decreases as time passes, ZcTokens appreciate towards par and reach par as maturity is reached.

Further, because an nToken represents the predicted future yield, the discount on a zcToken is inversely proportional to the cost of an nToken.

At maturity, zcTokens begin to appreciate above par, accruing the yield generated on a given money-market (e.g. Compound) until redeemed.


# Exiting/Selling zcTokens

An example of common market interactions

As rates fluctuate, active market participants may require the ability to fluidly move in and out of positions.

To facilitate this market participation, Swivel provides the ability to frictionlessly exit or sell a zcToken position.

Exiting zcTokens early by purchasing nTokens and then redeeming for underlying:

**Alice has 1000 zcUSDC.**\
**Alice fills Bob's order, purchasing 1000 nTokens.**\
**Alice redeems 1000 zcUSDC and 1000 nUSDC for 1000 USDC and then pays Bob 50 USDC.**\
**This leaves Alice with 950 USDC.**

![](/files/-McumIYiNN9vcOFXwnAn)

zcTokens can also be sold to counterparties looking to take fixed-yield positions through the orderbook:

**Alice has 1000 zcUSDC.**\
**Alice fills Diane's order, in the process Alice splitting Diane's 1000 USDC into zcUSDC and nUSDC.**\
**Alice purchases 1000 nUSDC from Diane and redeems her 1000 zcUSDC + 1000 nUSDC for 1000 USDC.**\
**Alice then pays Diane a 50 USDC premium for the purchased nUSDC.**\
**This leaves Alice with 950 USDC.**\
*(Simplified to 1000 zcUSDC <-> 950 USDC)*

![Selling zcTokens to initiating fixed-yield counterparties.](/files/-Md01i1kvSDys3PmhpSM)

<br>


# Secondary AMM's

A discussion of potential secondary markets and cross-chain access to fixed-yields.

zcTokens can also be traded on a secondary AMM in order to enter or exit lending positions, or alternatively attempt to amplify yield by providing liquidity.\
(see: Risks of LPing in derivative marketplaces)

Entering:

**Alice has 1000 USDC and wants a fixed yield.**\
**Alice purchases 1050 zcTokens for 1000 USDC, maturing in one year for a 5% yield.**

Exiting:

**Alice has 1050 zcTokens and wants to exit.**\
**Alice sells 1050 zcTokens for 1000 USDC.**

![](/files/-McQjZu5zViYOJoybjsD)


# nTokens

Notional Tokens contained in Swivel's Vaults which represent the claim to underlying yields.

### Overview

When a user buys nTokens, they create a vault that tracks their balances within a given market.

Each vault contains two balances, *Notional* and *Redeemable.*

#### **Notional (nTokens)**

Notional Tokens ***(nTokens)*** represent a 1-1 deposit, currently generating interest in an underlying protocol. Once maturity has been reached, interest-generation ceases and nTokens become worthless.

As such, nTokens are deprecating assets that experience time-decay. As time passes, nTokens decrease in value, and as they approach maturity, an their value approaches 0.

#### Redeemable

The ***Redeemable*** represents the amount of accrued interest currently available to redeem.&#x20;

As users interact with their vault, interest is accumulated to the redeemable balance, and this balance can be redeemed at any time.

\
**Buying nTokens:**
-------------------

**Bob has 50 USDC.**\
**Bob fills Alice's order selling 1000 nUSDC at .05/ea (5%), paying Alice an immediate $50 premium.**\
**Once filled, Alice mints 1000 zcUSDC and 1000 nUSDC, transferring 1000 nUSDC to Bob.**\
**Bob then owns 1000 nUSDC (the right to the yield generated by 1000 USDC).**

![](/files/-McupSKrZw9mqxAT27XZ)

### Pricing

Given nTokens represent a 1-1 deposit into an underlying money-market, and the claim to the deposit's future yield, they are priced based on the expected yield generated until maturity.

This potential future yield decreases as time passes and as such, nTokens depreciate and experience theta-decay.

Of note, because a zcToken represents an underlying token stripped of nToken yields, the cost of a nToken is inversely proportional to the discount on a zcToken.


# Exiting/Selling nTokens

An example of common market interactions

As with zcTokens, as rates fluctuate, active market participants require the ability to fluidly move in and out of nToken positions. To facilitate this market participation, Swivel provides the ability to exit/sell nTokens on our orderbook.&#x20;

Selling nTokens to an initiating counterparty:

**Bob has 1000 nUSDC.**\
**Bob fills Charlie's order for 1000 nUSDC, and in return receives 50 USDC.**\
**This leaves Bob with 50 USDC + any accrued interest.**

![Selling nTokens to an initiating nToken counterparty](/files/-Md-yoLF4rNrvEgkzKYs)

nTokens can also be sold to counterparties redeeming their zcTokens early:

**Bob has 1000 nUSDC.**\
**Bob fills Alice's order, selling Alice 1000 nTokens.**\
**Alice redeems 1000 zcUSDC + 1000 nUSDC for 1000 USDC and then pays Bob 50 USDC.**\
**This leaves Bob with 50 USDC + any accrued interest.**

![Selling nTokens to an exiting zcToken counterparty](/files/-McumIYiNN9vcOFXwnAn)


# AMM vs. Orderbook

An overview of capital efficiency within Interest-Rate Derivative and Cash-Flow Markets

AMM's have insofar proven to be *the* effective mechanism for bootstrapping liquidity, however the efficacy and capital efficiency of AMM's within derivative markets has proven to be questionable at best.

Without the ability to adjust quoted prices with regard to standard derivative pricing variables, liquidity providers are exposed to significant risk and constantly give up an edge to the market. (As seen in LP returns)

![-25% APY for HEGIC LP's ](https://cdn.substack.com/image/fetch/w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fbucketeer-e05bbc84-baa3-437e-9518-adb32be77984.s3.amazonaws.com%2Fpublic%2Fimages%2F198e2c1b-e12c-4c41-879b-f2d5716f44f2_2276x646.jpeg)

Swivel instead attempts to bootstrap liquidity by providing the same token incentives present on most AMM's, but with the enhanced capital efficiency and flexibility that an orderbook can provide for all market participants.

In my previous article, “[So… Why an Orderbook?](https://swivel.substack.com/p/so-why-an-orderbook)” I walked through the reasoning behind our decision to implement an orderbook for interest-rates and cash-flow tokens.

![](/files/aajoFFbB8IW3fhJbPIsV)

As a quick TL;DR, the primary benefits are:

* Increased general capital efficiency (similar to spot markets)
* The ability for LPs to manage inventory with respect to:
  * Underlying rates
  * Time-decay (Theta)
  * Sensitivity to rate variance (Delta)
  * Underlying rate volatility (Vega)
* Combined Principal Token and Yield Token liquidity pools (+100% capital efficiency)
* Free limit orders + order cancellation

## Instrument-Specific Optimizations

If then attempting to address Swivel's market with an AMM, one would need both a time-appreciating AMM for zero-coupon tokens (similar to Element), and a time-depreciating AMM for interest-coupons (similar to Pendle).&#x20;

With Swivel's flexible orderbook, these separate AMM's are not necessary as a user can enter the marketplace with an underlying currency (USDC, ETC, BTC, etc.,), or alternatively with either zero-coupon tokens or money-market notional (interest-coupons) when exiting positions.&#x20;

As a result Swivel's users benefit from the generalized efficiencies provided by an orderbook, and the further **\~2x** enhanced capital efficiency when compared to two separate AMM's.

## **Minting nTokens (Interest-Coupons)**

Swivel’s issuance of interest-coupon&#x73;*,* termed *Notional Tokens* (nTokens)*,* is optimized in two ways:

1. nTokens include interest-generation and tracking functionality within their transfer function which:

   * Reduces the deposit overhead present in designs which require increasing deposits over time&#x20;
   * Reduces complexity in nToken pricing
   * Allows interest to be redeemed at any time&#x20;

2. Swivel atomically mints tokens as orders are filled which reduces the number of transactions necessary for most use cases.


# Swivel Exchange

An overview of the mechanisms and market dynamics of the Swivel Exchange.


# Testnet Setup

Choosing a market and fauceting tokens on the Swivel Exchange Rinkeby Testnet.

After navigating to <https://swivel.exchange>, the first step is to select the currency you want to trade/lend, and a given maturity. (The market)

![](/files/-Mio1PQVRl3pD736JsHA)

After you have selected a currency / maturity, faucet yourself tokens in the balances dropdown.

![](/files/-Mio2YPojNLU8t02VQ1s)

Next, select the balance that you want to spend or sell. This is done from the balances dropdown.&#x20;

![](/files/-Mio3BEMiv-TPixLU0k2)

Users can chose to spend one of three balances:

1. An underlying token:
   * Selecting an underlying token allows a user to lend at a fixed yield, or spend their tokens on nTokens.&#x20;
2. nTokens:
   * Selecting "nTokens" allows a user to sell their nTokens / exit their position.
3. zcTokens:
   * Selecting "zcTokens" allows a user to sell their zcTokens / exit their position.


# Exchange Functions

An overview of all exchange functions


# Fixed-Yield Lending

How to enter fixed-yield positions on the Swivel Exchange.

## Market Orders:

![Entering a Fixed-Yield Position (Market-Order)](/files/-MinSeCofJYwDAYJlFnA)

In order to immediately lend at the best best available price (rate), place a market-order for the amount of principal you would like to lend, and receive a fixed-yield.

1. Select Fixed-Yield.
2. Enter the amount of principal you would like to lend.
3. Review the order's details.
4. Place the order, confirming in your web3 wallet when prompted.

## Limit Orders:

![Entering a Fixed-Yield Position (Limit-Order)](/files/-MioeP85KEU0nrtwwbyS)

In order to place a fixed-yield order at a specific price, select limit order and then input your desired price and amount you would like to lend.

***Importantly, limit orders can be placed for free, without an on-chain transaction.***

1. Select Fixed-Yield.
2. Select Limit.
3. Enter the amount of principal you would like to lend.
4. Enter the price (amount of premium to earn per token).
5. Review the order's details.
6. Place the order, confirming in your web3 wallet when prompted.


# Purchasing nTokens

How to enter into floating-yield position by purchasing Notional.

## Market Orders:

![Purchasing nTokens (Market-Order)](/files/-Minvs8Y8eSsexXmxVeF)

In order to immediately purchase nTokens best price available, place a market-order for the amount of premium you would like to spend.

1. Select Floating-Yield.
2. Enter the amount of DAI you would like to spend.
3. Review the order's details.
4. Place the order, confirming in your web3 wallet when prompted.

## Limit Orders:

![Purchasing nTokens (Limit-Order)](/files/-MinwNjXsw393Wry9yoE)

In order to place an order for nTokens at a specific price, select limit order and then input your desired price and the amount of premium you would like to spend.

***Importantly***, ***limit orders can be placed for free, without an on-chain transaction.***

1. Select Floating-Yield.
2. Toggle a Limit-Order.
3. Enter the amount of premium you would like to spend.
4. Enter the price you are willing to pay. (amount paid per nToken purchased).
5. Review the order's details.
6. Place the order, signing the order in your web3 wallet when prompted.


# Selling zcTokens

How to exit fixed-yield positions on the Swivel Exchange.

## Balance Selection:

![](/files/-MinyxHNYbkaqxyGaQRi)

In order to sell your zcTokens, select a zcToken from the balances dropdown.

## Market Orders:

![Selling zcTokens (Market-Order)](/files/-MinsCVkF5SRnp9LJRK_)

In order to immediately sell your zcTokens for best price available, place a market-order for the amount of zcTokens you would like to sell.

1. Enter the amount of zcDAI you would like to sell.
2. Review the order's details.
3. Place the order, confirming in your web3 wallet when prompted.

## Limit Orders:

![Selling zcTokens (Limit-Order)](/files/-MinsIoqIAsyla0HP4ck)

In order to place an order to sell your zcTokens at a specific price, select limit order and then input your desired price and the amount of zcTokens you would like to sell.

***Importantly***, ***limit orders can be placed for free, without an on-chain transaction.***

1. Toggle a Limit-Order.
2. Enter the amount of zcDAI you would like to sell.
3. Enter the price you want to sell zcDAI for. (DAI received per zcDAI sold)
4. Review the order's details.
5. Place the order, signing the order in your web3 wallet when prompted.


# Selling nTokens

How to exit floating-yield position by selling Notional.

## Balance Selection:

![](/files/-MinzCkTxQpf6ZKdJqjV)

In order to sell your nTokens, select an nToken from the balances dropdown.

## Market Orders:

![Selling nTokens (Market-Order)](/files/-MinsQ4CRw2Ohtg1GguE)

In order to immediately sell nTokens for best price available, place a market-order for the amount of nTokens you would like to sell.

1. Enter the amount of nDAI you would like to sell.
2. Review the order's details.
3. Place the order, confirming in your web3 wallet when prompted.

## Limit Orders:

![Selling nTokens (Limit-Order)](/files/-MinsVsjsk2gETOF-iId)

In order to place an order to sell nTokens at a specific price, select limit order and then input your desired price and the amount of nTokens you would like to sell.

***Importantly***, ***limit orders can be placed for free, without an on-chain transaction.***

1. Toggle a Limit-Order.
2. Enter the amount of nDAI you would like to sell.
3. Enter the price you want to sell nDAI for. (DAI received per nDAI)
4. Review the order's details.
5. Place the order, signing the order in your web3 wallet when prompted.


# Splitting/Combining Tokens

How to split an underlying token into nTokens & zcTokens, or combine nTokens and zcTokens into an underlying token.

## Splitting Underlying:

If a user wants to split their underlying into nTokens and zcTokens, they can do so by navigating to the `Positions` page.

From there a user can chose a market to participate in, and can split their underlying into tokens within that market.

![](/files/-MioGOhO5-YtMwcycTUl)

![](/files/-MioHfqqnu68Bzry-fQe)

1. Select `Split`.
2. Approve your underlying balance.
3. Enter the amount of underlying you would like to split.
4. Confirm the amount and then confirm the transaction in your web3 wallet when prompted.

## Combining nTokens/zcTokens:

A user can also combine their zcTokens & nTokens on the `Positions` page.

From there a user can chose a market, and can combine their zcTokens & nTokens within that market.

![](/files/-MioJL_dN7oRzd6To1q6)

![](/files/-MioJqJMwgOzqN8GFVaz)

1. Select `Combine` .
2. Enter the amount of zcTokens & nTokens you would like to combine.
3. Confirm the amount and then confirm the transaction in your web3 wallet when prompted.


# Redeeming Tokens/Interest

How to redeem zcTokens and redeemable nToken interest

## Redeeming zcTokens

zcTokens can only be redeemed once a market has matured.

Once a market has matured, users can redeem their zcTokens 1:1 for their underlying deposit (e.g. 1 zcUSDC = 1 USDC).

**Redeeming zcTokens:**

1. Navigate to your [Positions ](https://swivel.exchange/positions)page
2. Select "Matured" to view the recently matured markets
3. Find the market and zcToken balance you would like to redeem.
4. Assuming you have zcTokens to redeem, click "redeem".
5. Confirm the transaction and receive a 1:1 amount of tokens !

## Redeeming nToken Interest

nTokens generate interest continuously until maturity.

The interest that nTokens generate can be redeemed at any time.

**Redeeming "redeemable":**

1. Navigate to your [Positions ](https://swivel.exchange/positions)page
2. Identify whether the market has matured or not, and select the correct category.
3. Find the market and "redeemable" balance you would like to redeem.
4. Click "redeem".
5. Confirm the transaction and receive a 1:1 amount of "redeemable" balance in your underlying token.


# Maturity

A description of what happens to markets once they are close to maturity, and after they mature.

## Before Maturity (-4 days)

Once a market is close to maturity, rates tend to be extremely volatile, and the general exchange UX surrounding trades degrades for both lenders and active rate traders.

**In order to ensure our users orders can only place orders that execute as expected, we ensure all orders expire 4 days before maturity. At that point all markets are halted, and a countdown until maturity will begin.**

This means that no more trades can be made in that market, and that users will need to wait to redeem their positions at maturity.

## After Maturity

As is implied by the name, once a market hits its maturity, it can be considered "Matured".

Once a market has matured, users can redeem their zcTokens 1:1 for their underlying deposit (e.g. 1 zcUSDC = 1 USDC).

**Redeeming zcTokens:**

1. Navigate to your [Positions ](https://swivel.exchange/positions)page
2. Select "Matured" to view the recently matured markets
3. Assuming you have zcTokens to redeem, click "redeem".
4. Confirm the transaction and receive a 1:1 amount of tokens !

## Archived Markets

After a market has matured for a significant amount of time (2+ weeks), it may be "archived".

An "archived" market is no different than a "matured" market, and users can still redeem balances in an archived market.

We separate out these markets in order to ensure users can easily identify which markets may be most relevant regardless of our exchange's scale.


# Liquidity Incentives

A description of Swivel's liquidity and market-making incentivization.

Swivel is the first orderbook-based protocol with liquidity incentives built baseline into token distribution and protocol design.

In the context of an AMM, liquidity incentives are straightforward. Any user who provides pooled liquidity across the constant x\*y=k curve is rewarded at a proportional rate for their liquidity provided.

When applying this concept to an orderbook, liquidity rewards are not pools but binary orders. Either an order gets filled, or it does not.

With this accepted, how does one reward those providing liquidity to an orderbook? \
***By providing token rewards only to those liquidity providers (makers) who's orders are filled.***

Swivel sets aside 50% of our token supply for these orderbook liquidity incentives.

![](/files/k697UaVxism9R5M5PHtO)

There are other alternative liquidity incentive implementations using orderbook snapshots as described in [Hummingbot's paper](https://hummingbot.io/liquidity-mining-whitepaper/) on liquidity mining, and as most popularly implemented by dYdX.

While none seem to properly democratize access to rewards across any market participant, we expect that governance will vote to quickly transition to such a design.

### Current Liquidity Incentive Distributions

Each market currently has 5,000 SWIV tokens allocated to it on a daily basis and calculated at 23:55 UTC.

Once a day, cumulative volume is calculated, and users are rewarded proportionally based on the amount of nToken liquidity they provided to trades.

These rewards are earned on a daily basis and then distributed every 4 week liquidity incentive epoch, starting 2-10-2022.&#x20;

![](/files/nAFtTo0zdbX2tFMHF52M)

As shown in the example above, for each market, there are 5,000 SWIV tokens allocated per day.

These tokens are then split proportionally based on the limit orders that have been filled in a given day.

In the example above, 0xmons traded 200,000 of 1,000,000 total nTokens that day.&#x20;

Given they committed 20% of the daily liquidity, 0xmons receives 1,000 SWIV tokens, 20% of the daily allocation.

### Effectiveness of Liquidity Incentives: AMM vs CLOB

While liquidity provider token incentives have historically related to providing liquidity on an AMM, it appears that their positive effect on slippage/spread is enhanced within the context of an orderbook.

Effectively, within an orderbook users have individualized capital allocation, and with our liquidity rewards, more efficient competitive capital allocation results in more reward generation. &#x20;

This then gives market-makers the incentive to not only optimize their capital efficiency, but in doing so undercut one another as they attempt to take on a competitive position within the orderbook.


# Minimums, Rate Limits & Fees

An overview of key exchange parameters, all are subject to change but will be kept up to date here.

## API Rate Limit

The Swivel Exchange API has a API limit of 2000 requests per 5 minutes on a rolling basis. If you may need to exceed this limit, contact @JulianT to make a whitelist or feature request.

**Rate Limit**: 2000 requests / 5 min

We do not currently have a burst limit, which may introduce latency to requests that exceed expected burst rates.

## Minimums

### Minimum Order Size

In order to reduce the gas costs necessary for takers, and prevent potential DDOS through the submission of extremely small orders, we have implemented a minimum order size in terms of `Principal` (nTokens).

Each order must be placed with at or above this value in principal.

**Minimum Order Size:** 2500 nTokens (for stablecoin markets)

### Order Threshold Size

Similarly, in order to ensure orders with small amounts of dust dont fill our orderbook and bloat gas costs, we have also implemented a minimum order threshold in terms of `Principal` (nTokens).&#x20;

Once an order placed is majority filled, if its remaining `Pricipal` amount is less than this value, it will be removed from the orderbook.

**Order Threshold:** 1250 nTokens (for stablecoin markets)

## Fees

As one of the primary parameters for governance modulation alongside incentives, fees are likely to change over time.

Fees solely apply to takers and currently accrue to the swivel.sol contract. All fees other than nToken purchases are paid in USDC, while nToken purchases are paid in nTokens.

#### **Current Fees:**

**nToken Purchases:** .66%

**zcToken Sale (nToken Purchase):** 1%

**Fixed-Rate (nToken Sale):** .5%

**nToken Sale:** .5%


# Retroactive Distribution

## Retroactive Distribution: Does My Address Qualify? <a href="#id-6d28" id="id-6d28"></a>

The launch of our protocol would not have been possible without the cumulative effort of thousands of community members that have continued to contribute to our growth.

Starting with our genesis during Gitcoin Kernel, continuing through a year of iteration and community feedback, and bringing us to our current launch alongside early adopters and liquidity providers, we owe an enormous debt to the community that has gotten us to where we are today.

As a way to ensure these community members are represented in our governance, SWIV tokens have been retroactively allocated to these community members based on their proportional contribution.

\~4.5% of our token supply will be distributed across:

* 0.5% Guarded Mainnet Lenders
* 1% Verified Community Contributors (Verified Feedback & Content)
* 1% Gitcoin Kernel Alumni & Mentors
* 2% Compound, Aave, FEIRari (Fei + Rari) & Gitcoin On-Chain Governance Participants

A full list of all currently recorded addresses is available here:

[SWIV Retroactive Distribution](https://gist.github.com/JTraversa/f97665ba60f5bdd65c2b7ac1c018313f)

If your address was not included, and you believe this is a mistake, please fill out this form: [Request Link](https://6bw0fidkvd9.typeform.com/to/gNPs4PSb)

## Earning Your Allocation <a href="#id-408e" id="id-408e"></a>

**SWIV** has been allocated to historical users of our guarded mainnet based on a snapshot ending 2–08, 2022, at 08:00:00 UTC. Additional allocation tiers depend on a number of qualifying contributions (described above) since our inception.

To claim **SWIV**, historical users and contributors must first meet progressive milestones to unlock their rewards.

**For every $2,500 traded (in notional value), 100 SWIV tokens are unlocked for distribution. Rewards will be distributed with the completion of our first liquidity incentive epoch on 3–10.**

![](https://miro.medium.com/max/1400/0*q2fAEjifq_lwpQpI.png)

For more information, stay tuned for a follow up post as mainnet launches!

*In line with restrictions on the availability of SWIV in the United States, retroactive mining may not be available to users located in, or incorporated or otherwise established in, or a resident of, the United States or any other prohibited jurisdiction. Any accounts that were clearly associated with bot activity speculating on a future airdrop are also excluded from retroactive rewards. Any displayed rewards on a testnet or before 2–10 are not representative of claimable tokens.*


# How to Claim SWIV Tokens

A quick step-by-step walkthrough to claim your SWIV token rewards.

#### Step 1: Click Rewards

If available in your region, you will notice the "Rewards" button in the Swivel\
Exchange header:

*Notice: US Residents may not be eligible to claim rewards and any IP addresses located in the US may not have their rewards button rendered.*

![](/files/bkdc4e0fDYfrrhEzw5UQ)

### Step 2: Read your reward balances

Your "Earned" reflects how many SWIV tokens you have earned for providing liquidity to the Swivel Exchange within the current epoch. These rewards are not yet claimable.

Instead, rewards are released in regularly recurring epochs, which is when your “earned” SWIV will become "Redeemable" SWIV that you are able to claim.

Rewards earned during our Retroactive Airdrop period will be seen on the bottom row. These rewards are also included in your “Redeemable” balance after 3.10.22.

![](/files/8qiSlUBk22zMZ13PjKNz)

### Step 3:

If you have a Redeemable balance to claim, click the claim button and sign the transaction to claim your SWIV tokens!

If you do not see the SWIV tokens in your wallet immediately, click "Add SWIV Token To Wallet" to automatically add it to your token list.

![](/files/17LiK8mOpcQd0mzfJ14J)

### Step 4:

GO VOTE!


# Developers

A collection of developer resources relating to Swivel Finance and the Swivel Exchange.


# Exchange API

The endpoints under the Exchange API section all share the same base URL <https://api.swivel.exchange> no matter on the environment that is being used.

There are two active, live environments so base URL should be changed accordingly:

* Testnet base URL **<https://api-dev.swivel.exchange>**
* Mainnet base URL **<https://api-main.swivel.exchange>.**

## &#x20;<a href="#update-variant" id="update-variant"></a>


# GET

All GET endpoints are documented here. Base URLs should be changed in relation to the environment that is used: Testnet or Mainnet.

## Get Markets

<mark style="color:blue;">`GET`</mark> `https://api.swivel.exchange/v2/markets?status=s&depth=d`

This endpoint allows you to request a list of markets.

#### Query Parameters

| Name   | Type    | Description                      |
| ------ | ------- | -------------------------------- |
| status | string  | **active** or **matured**        |
| depth  | integer | The number of markets to return. |

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

```
[
  {
    "underlying": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
    "maturity": "1648177200"
  }
]
```

{% endtab %}
{% endtabs %}

## Get Orderbook

<mark style="color:blue;">`GET`</mark> `https://api.swivel.exchange/v2/orderbook?underlying=u&maturity=m`

This endpoint allows you to request an orderbook of a given depth for a specified market.\
\
Returns receiving premium and paying premium orders in descending/ascending order including *availableVolume* translated into both *premiumAvailable* and *principalAvailable*.

#### Query Parameters

| Name                                         | Type    | Description                                                   |
| -------------------------------------------- | ------- | ------------------------------------------------------------- |
| underlying<mark style="color:red;">\*</mark> | string  | The underlying token being transacted. E.g. USDC, DAI, etc.,  |
| maturity<mark style="color:red;">\*</mark>   | string  | The maturity of market in unix seconds.                       |
| depth                                        | integer | The number of orders on each side of the orderbook to return. |

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

```
{
    "receivingPremium": [
        {
            "order": {
                "key": "0xae3f59eabffcf1f15f384d5e582985d31a9aef4b181ecf56a0a37bab85013f1f",
                "maker": "0x335c0552eb130f3Dfbe6efcB4D2895aED1E9938b",
                "underlying": "0x5592EC0cfb4dbc12D3aB100b257153436a1f0FEa",
                "vault": false,
                "exit": false,
                "principal": "10000000000000000000000",
                "premium": "799000000000000000000",
                "maturity": "1669957199",
                "expiry": "1641386982"
            },
            "meta": {
                "price": "0.0799",
                "signature": "0x94836bc0b91695430e738f53e08cfef34ee1c048c42f9d846732cd867bf5376233ed86fb6b324dd9fac98c3e53c8e7f00b9c5c80fbd2d00bf8c5a177fbe8d38f1b",
                "premiumAvailable": "799000000000000000000",
                "principalAvailable": "10000000000000000000000",
                "sequence": 69218
            }
        }
    ],
    "payingPremium": [
        {
            "order": {
                "key": "0xa8181ff6e0bfa16130944d5add7220eed46f44796de7d4216728dde40376ac5e",
                "maker": "0x096Da21Ac79ae1EDbC69A07CE5c705E6c77Fec90",
                "underlying": "0x5592EC0cfb4dbc12D3aB100b257153436a1f0FEa",
                "vault": true,
                "exit": false,
                "principal": "107758620689655172413793",
                "premium": "10000000000000000000000",
                "maturity": "1669957199",
                "expiry": "1641371984"
            },
            "meta": {
                "price": "0.0928",
                "signature": "0xa4e8958193cf2cb9c70e4c4a7df9c3c7b68f89fd2f250d80e6bc9dbd9cba8c54415fb2f4d8da33c1d81d5a028233255b52adbf36bee3a2a929fb3ea3e735ff7a1c",
                "premiumAvailable": "10000000000000000000000",
                "principalAvailable": "107758620689655172413793",
                "sequence": 63593
            }
        }
    ],
    "timestamp": 1640178800,
    "nonce": 69218
}
```

{% endtab %}
{% endtabs %}

## Get Order

<mark style="color:blue;">`GET`</mark> `https://api.swivel.exchange/v2/orders/key`

This endpoint allows you to request the detailed state and parameters for a given order.

Returns the orders parameters as well as order price, volume available and initial timestamp.

#### Path Parameters

| Name                                  | Type   | Description |
| ------------------------------------- | ------ | ----------- |
| key<mark style="color:red;">\*</mark> | String | Order key   |

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

```
{
    "order": {
        "key": "0xae3f59eabffcf1f15f384d5e582985d31a9aef4b181ecf56a0a37bab85013f1f",
        "maker": "0x335c0552eb130f3Dfbe6efcB4D2895aED1E9938b",
        "underlying": "0x5592EC0cfb4dbc12D3aB100b257153436a1f0FEa",
        "vault": false,
        "exit": false,
        "principal": "10000000000000000000000",
        "premium": "799000000000000000000",
        "maturity": "1669957199",
        "expiry": "1641386982"
    },
    "meta": {
        "price": "0.0799",
        "signature": "0x94836bc0b91695430e738f53e08cfef34ee1c048c42f9d846732cd867bf5376233ed86fb6b324dd9fac98c3e53c8e7f00b9c5c80fbd2d00bf8c5a177fbe8d38f1b",
        "premiumAvailable": "799000000000000000000",
        "principalAvailable": "10000000000000000000000",
        "sequence": 69218
    }
}
```

{% endtab %}
{% endtabs %}

## Get Effective Price (Preview Market Order)

<mark style="color:blue;">`GET`</mark> `https://api.swivel.exchange/v2/fillpreview?underlying=u&maturity=m&volume=v&vault=w&exit=e`

This endpoint allows you to request a limit order payload that matches a given market order.\
\
Returns the effective price as well as orders for consumption.

#### Query Parameters

| Name                                         | Type    | Description                                                                       |
| -------------------------------------------- | ------- | --------------------------------------------------------------------------------- |
| underlying<mark style="color:red;">\*</mark> | string  | The underlying token being transacted. E.g. USDC, DAI, etc.,                      |
| maturity<mark style="color:red;">\*</mark>   | string  | The duration of the rolling-maturity market in seconds. E.g. 31536000 (12 months) |
| volume<mark style="color:red;">\*</mark>     | string  | The amount of currency to use.                                                    |
| vault<mark style="color:red;">\*</mark>      | boolean | Indicates if an order is in relation to a initiating/exiting a vault or zcToken   |
| exit<mark style="color:red;">\*</mark>       | boolean | Indicated if an order is an exit or an initiate                                   |

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

```
{
    "orders": [
        {
            "order": {
                "key": "0xa8181ff6e0bfa16130944d5add7220eed46f44796de7d4216728dde40376ac5e",
                "maker": "0x096Da21Ac79ae1EDbC69A07CE5c705E6c77Fec90",
                "underlying": "0x5592EC0cfb4dbc12D3aB100b257153436a1f0FEa",
                "vault": true,
                "exit": false,
                "principal": "107758620689655172413793",
                "premium": "10000000000000000000000",
                "maturity": "1669957199",
                "expiry": "1641371984"
            },
            "meta": {
                "price": "0.0928",
                "signature": "0xa4e8958193cf2cb9c70e4c4a7df9c3c7b68f89fd2f250d80e6bc9dbd9cba8c54415fb2f4d8da33c1d81d5a028233255b52adbf36bee3a2a929fb3ea3e735ff7a1c",
                "premiumAvailable": "10000000000000000000000",
                "principalAvailable": "107758620689655172413793",
                "previewFill": "1000",
                "sequence": 63593
            }
        }
    ],
    "effectivePrice": "0.092799999999999997156",
    "timestamp": 1640178873
}
```

{% endtab %}

{% tab title="400 Passed volume exceeds available" %}

```
{
     "message": "passed volume exceeds available" 
}
```

{% endtab %}

{% tab title="400: Bad Request Passed volume exceeds the maximum number of orders allowed" %}

```javascript
{
    "error" {
        "message": "passed volume exceeds the maximum number of orders allowed"
    }
}
```

{% endtab %}
{% endtabs %}

## Get Order History

<mark style="color:blue;">`GET`</mark> `https://api.swivel.exchange/v2/users/:address/orders?underlying=u&maturity=m&status=s`

This endpoint allows you to request the order history for a given address, and allows filtering by **active**, **cancelled**, **full** and **expired** statuses.\
\
Returns chronologically sorted orders for a given address.

#### Query Parameters

| Name                                         | Type         | Description                                                             |
| -------------------------------------------- | ------------ | ----------------------------------------------------------------------- |
| address<mark style="color:red;">\*</mark>    | string       | Public key of an order's creator                                        |
| underlying<mark style="color:red;">\*</mark> | string       | The underlying token being transacted. E.g. USDC, DAI, etc.,            |
| maturity<mark style="color:red;">\*</mark>   | string       | The maturity of market in unix seconds.                                 |
| status                                       | list(string) | List of statuses **expired**, **cancelled**, **full** or **insolvent**. |

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

```
{
    "orders": [
        {
            "order": {
                "key": "0x279eb2584cb32ccc7a512d3d46e3dbb83ecde4b0c231c3f4838cae0ea70223e8",
                "maker": "0x096Da21Ac79ae1EDbC69A07CE5c705E6c77Fec90",
                "underlying": "0x5592EC0cfb4dbc12D3aB100b257153436a1f0FEa",
                "vault": false,
                "exit": false,
                "principal": "30000000000000000000000",
                "premium": "3333000000000000000000",
                "maturity": "1669957199",
                "expiry": "1641372040"
            },
            "meta": {
                "price": "0.1111",
                "signature": "0x75d626fdf62c67cf1de04f077fd7447f1164976f7f60826a63eece886923c11b59f061bd7b6d81fa96cdc3208ff53d4926ad8ba66d06a9101cc81d0e23792aaa1c",
                "premiumAvailable": "3333000000000000000000",
                "principalAvailable": "30000000000000000000000",
                "sequence": 63604
            }
        },
        {
            "order": {
                "key": "0xa8181ff6e0bfa16130944d5add7220eed46f44796de7d4216728dde40376ac5e",
                "maker": "0x096Da21Ac79ae1EDbC69A07CE5c705E6c77Fec90",
                "underlying": "0x5592EC0cfb4dbc12D3aB100b257153436a1f0FEa",
                "vault": true,
                "exit": false,
                "principal": "107758620689655172413793",
                "premium": "10000000000000000000000",
                "maturity": "1669957199",
                "expiry": "1641371984"
            },
            "meta": {
                "price": "0.0928",
                "signature": "0xa4e8958193cf2cb9c70e4c4a7df9c3c7b68f89fd2f250d80e6bc9dbd9cba8c54415fb2f4d8da33c1d81d5a028233255b52adbf36bee3a2a929fb3ea3e735ff7a1c",
                "premiumAvailable": "10000000000000000000000",
                "principalAvailable": "107758620689655172413793",
                "sequence": 63593
            }
        },
    ...
    ]
}
```

{% endtab %}

{% tab title="400: Bad Request E.g. Invalid maturity" %}

```javascript
{
    "error": {
        "message": "invalid maturity"
    }
}
```

{% endtab %}
{% endtabs %}

## Get Last Trade Info

<mark style="color:blue;">`GET`</mark> `https://api.swivel.exchange/v2/fills?underlying=u&maturity=m&depth=d`

This endpoint allows you to request the agreement most recently initiated in a given market. (The trade last made in a given market)\
\
Returns the parameters of the most recent agreement for the specified market.

#### Query Parameters

| Name                                         | Type   | Description                                                                                                           |
| -------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------- |
| underlying<mark style="color:red;">\*</mark> | string | The underlying token being transacted. E.g. USDC, DAI, etc.,                                                          |
| maturity<mark style="color:red;">\*</mark>   | string | The maturity of market in unix seconds.                                                                               |
| depth<mark style="color:red;">\*</mark>      | string | Should always be **1** to return one last trade. If more specified, the result will be a sorted  list of last trades. |

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

```
[
    {
        "key": "0xae3f59eabffcf1f15f384d5e582985d31a9aef4b181ecf56a0a37bab85013f1f",
        "price": "0.0799",
        "exit": false,
        "vault": false,
        "volume": "1.251564456e+20"
    }
]
```

{% endtab %}

{% tab title="400: Bad Request E.g. Invalid maturity" %}

```javascript
{
    "error": {
        "message": "invalid maturity"
    }
}
```

{% endtab %}
{% endtabs %}

## Get OHCLV

<mark style="color:blue;">`GET`</mark> `https://api.swivel.exchange/v2/samples?underlying=x&maturity=y&start=z&end=e&interval=f&type=g`

This endpoint allows you to request OHLCV points for the given period.\
\
Returns OHLCV points with each containing its OHLCV data at the given timestamp.

#### Query Parameters

| Name                                         | Type   | Description                                                                    |
| -------------------------------------------- | ------ | ------------------------------------------------------------------------------ |
| interval<mark style="color:red;">\*</mark>   | string | The time between datapoints in minutes dividable by 5. E.g. 5, 15, 30, 60, ... |
| maturity<mark style="color:red;">\*</mark>   | string | The maturity of market in unix seconds.                                        |
| underlying<mark style="color:red;">\*</mark> | string | The underlying token contract being transacted. E.g. USDC, DAI, etc.,          |
| start<mark style="color:red;">\*</mark>      | number | Start of of the period in seconds                                              |
| end<mark style="color:red;">\*</mark>        | number | End of the period in seconds                                                   |
| type<mark style="color:red;">\*</mark>       | string | Sampling type e.g. OHLCV                                                       |

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

```
[
    {
        "timestamp": 1638472500,
        "data": {
            "open": "0.0499",
            "high": "0.0499",
            "low": "0.0499",
            "close": "0.0499",
            "volume": "252275019238957087498"
        }
    },
    {
        "timestamp": 1638473400,
        "data": {
            "open": "0.0499",
            "high": "0.05",
            "low": "0.0499",
            "close": "0.05",
            "volume": "170000000000000000000"
        }
    },
...
]
```

{% endtab %}

{% tab title="400: Bad Request E.g. Invalid maturity" %}

```javascript
{
    "error": {
        "message": "invalid maturity"
    }
}
```

{% endtab %}
{% endtabs %}


# Orderbook

## Get Orderbook

<mark style="color:blue;">`GET`</mark> `https://api.swivel.exchange/v2/orderbook?underlying=x&maturity=y&depth=z`

This endpoint allows you to request an orderbook of a given depth for a specified market.\
\
Returns receiving premium and paying premium orders in descending/ascending order including *availableVolume* translated into both *premiumAvailable* and *principalAvailable*.

#### Query Parameters

| Name                                         | Type    | Description                                                   |
| -------------------------------------------- | ------- | ------------------------------------------------------------- |
| underlying<mark style="color:red;">\*</mark> | string  | The underlying token being transacted. E.g. USDC, DAI, etc.,  |
| maturity<mark style="color:red;">\*</mark>   | string  | The maturity of market in unix seconds.                       |
| depth<mark style="color:red;">\*</mark>      | integer | The number of orders on each side of the orderbook to return. |

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

```
{
    "receivingPremium": [
        {
            "order": {
                "key": "0xae3f59eabffcf1f15f384d5e582985d31a9aef4b181ecf56a0a37bab85013f1f",
                "maker": "0x335c0552eb130f3Dfbe6efcB4D2895aED1E9938b",
                "underlying": "0x5592EC0cfb4dbc12D3aB100b257153436a1f0FEa",
                "vault": false,
                "exit": false,
                "principal": "10000000000000000000000",
                "premium": "799000000000000000000",
                "maturity": "1669957199",
                "expiry": "1641386982"
            },
            "meta": {
                "price": "0.0799",
                "signature": "0x94836bc0b91695430e738f53e08cfef34ee1c048c42f9d846732cd867bf5376233ed86fb6b324dd9fac98c3e53c8e7f00b9c5c80fbd2d00bf8c5a177fbe8d38f1b",
                "premiumAvailable": "799000000000000000000",
                "principalAvailable": "10000000000000000000000",
                "sequence": 69218
            }
        }
    ],
    "payingPremium": [
        {
            "order": {
                "key": "0xa8181ff6e0bfa16130944d5add7220eed46f44796de7d4216728dde40376ac5e",
                "maker": "0x096Da21Ac79ae1EDbC69A07CE5c705E6c77Fec90",
                "underlying": "0x5592EC0cfb4dbc12D3aB100b257153436a1f0FEa",
                "vault": true,
                "exit": false,
                "principal": "107758620689655172413793",
                "premium": "10000000000000000000000",
                "maturity": "1669957199",
                "expiry": "1641371984"
            },
            "meta": {
                "price": "0.0928",
                "signature": "0xa4e8958193cf2cb9c70e4c4a7df9c3c7b68f89fd2f250d80e6bc9dbd9cba8c54415fb2f4d8da33c1d81d5a028233255b52adbf36bee3a2a929fb3ea3e735ff7a1c",
                "premiumAvailable": "10000000000000000000000",
                "principalAvailable": "107758620689655172413793",
                "sequence": 63593
            }
        }
    ],
    "timestamp": 1640178800,
    "nonce": 69218
}
```

{% endtab %}
{% endtabs %}


# Get Order

## Get Order

<mark style="color:blue;">`GET`</mark> `https://api.swivel.exchange/v2/orders/key`

This endpoint allows you to request the detailed state and parameters for a given order.&#x20;

Returns the orders parameters as well as order price, volume available and initial timestamp.

#### Path Parameters

| Name                                  | Type   | Description |
| ------------------------------------- | ------ | ----------- |
| key<mark style="color:red;">\*</mark> | String | Order key   |

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

```
{
    "order": {
        "key": "0xae3f59eabffcf1f15f384d5e582985d31a9aef4b181ecf56a0a37bab85013f1f",
        "maker": "0x335c0552eb130f3Dfbe6efcB4D2895aED1E9938b",
        "underlying": "0x5592EC0cfb4dbc12D3aB100b257153436a1f0FEa",
        "vault": false,
        "exit": false,
        "principal": "10000000000000000000000",
        "premium": "799000000000000000000",
        "maturity": "1669957199",
        "expiry": "1641386982"
    },
    "meta": {
        "price": "0.0799",
        "signature": "0x94836bc0b91695430e738f53e08cfef34ee1c048c42f9d846732cd867bf5376233ed86fb6b324dd9fac98c3e53c8e7f00b9c5c80fbd2d00bf8c5a177fbe8d38f1b",
        "premiumAvailable": "799000000000000000000",
        "principalAvailable": "10000000000000000000000",
        "sequence": 69218
    }
}
```

{% endtab %}
{% endtabs %}


# OHCLV (Candles)

## Get OHCLV

<mark style="color:blue;">`GET`</mark> `https://api.swivel.exchange/v2/samples?underlying=x&maturity=y&start=z&end=e&interval=f&type=g`

This endpoint allows you to request OHLCV points for the given period.\
\
Returns OHLCV points with each containing its OHLCV data at the given timestamp.

#### Query Parameters

| Name                                         | Type   | Description                                                                    |
| -------------------------------------------- | ------ | ------------------------------------------------------------------------------ |
| interval<mark style="color:red;">\*</mark>   | string | The time between datapoints in minutes dividable by 5. E.g. 5, 15, 30, 60, ... |
| maturity<mark style="color:red;">\*</mark>   | string | The maturity of market in unix seconds.                                        |
| underlying<mark style="color:red;">\*</mark> | string | The underlying token contract being transacted. E.g. USDC, DAI, etc.,          |
| start<mark style="color:red;">\*</mark>      | number | Start of of the period in seconds                                              |
| end<mark style="color:red;">\*</mark>        | number | End of the period in seconds                                                   |
| type<mark style="color:red;">\*</mark>       | string | Sampling type e.g. OHLCV                                                       |

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

```
[
    {
        "timestamp": 1638472500,
        "data": {
            "open": "0.0499",
            "high": "0.0499",
            "low": "0.0499",
            "close": "0.0499",
            "volume": "252275019238957087498"
        }
    },
    {
        "timestamp": 1638473400,
        "data": {
            "open": "0.0499",
            "high": "0.05",
            "low": "0.0499",
            "close": "0.05",
            "volume": "170000000000000000000"
        }
    },
...
]
```

{% endtab %}

{% tab title="400: Bad Request E.g. Invalid maturity" %}

```javascript
{
    "error": {
        "message": "invalid maturity"
    }
}
```

{% endtab %}
{% endtabs %}


# Get Effective Price (Preview Market Order)

## Get Effective Price (Preview Market Order)

<mark style="color:blue;">`GET`</mark> `https://api.swivel.exchange/v2/fillpreview?underlying=u&maturity=m&volume=v&vault=w&exit=e`

This endpoint allows you to request a limit order payload that matches a given market order.\
\
Returns the effective price as well as orders for consumption.

#### Query Parameters

| Name                                         | Type    | Description                                                                     |
| -------------------------------------------- | ------- | ------------------------------------------------------------------------------- |
| underlying<mark style="color:red;">\*</mark> | string  | The underlying token being transacted. E.g. USDC, DAI, etc.,                    |
| maturity<mark style="color:red;">\*</mark>   | string  | The maturity of market in unix seconds.                                         |
| volume<mark style="color:red;">\*</mark>     | string  | The amount of currency to use.                                                  |
| vault<mark style="color:red;">\*</mark>      | boolean | Indicates if an order is in relation to a initiating/exiting a vault or zcToken |
| exit<mark style="color:red;">\*</mark>       | boolean | Indicated if an order is an exit or an initiate                                 |

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

```
{
    "orders": [
        {
            "order": {
                "key": "0xa8181ff6e0bfa16130944d5add7220eed46f44796de7d4216728dde40376ac5e",
                "maker": "0x096Da21Ac79ae1EDbC69A07CE5c705E6c77Fec90",
                "underlying": "0x5592EC0cfb4dbc12D3aB100b257153436a1f0FEa",
                "vault": true,
                "exit": false,
                "principal": "107758620689655172413793",
                "premium": "10000000000000000000000",
                "maturity": "1669957199",
                "expiry": "1641371984"
            },
            "meta": {
                "price": "0.0928",
                "signature": "0xa4e8958193cf2cb9c70e4c4a7df9c3c7b68f89fd2f250d80e6bc9dbd9cba8c54415fb2f4d8da33c1d81d5a028233255b52adbf36bee3a2a929fb3ea3e735ff7a1c",
                "premiumAvailable": "10000000000000000000000",
                "principalAvailable": "107758620689655172413793",
                "previewFill": "1000",
                "sequence": 63593
            }
        }
    ],
    "effectivePrice": "0.092799999999999997156",
    "timestamp": 1640178873
}
```

{% endtab %}

{% tab title="400 Passed volume exceeds available" %}

```
{
     "message": "passed volume exceeds available" 
}
```

{% endtab %}

{% tab title="400: Bad Request Passed volume exceeds the maximum number of orders allowed" %}

```javascript
{
    "message": "passed volume exceeds the maximum number of orders allowed"
}
```

{% endtab %}
{% endtabs %}


# Get Order History

## Get Order History

<mark style="color:blue;">`GET`</mark> `https://api.swivel.exchange/v2/users/:address/orders?underlying=u&maturity=m&status=s`

This endpoint allows you to request the order history for a given address, and allows filtering by **active**, **cancelled**, **full** and **expired** statuses.\
\
Returns chronologically sorted orders for a given address.

#### Query Parameters

| Name                                         | Type         | Description                                                             |
| -------------------------------------------- | ------------ | ----------------------------------------------------------------------- |
| address<mark style="color:red;">\*</mark>    | string       | Public key of an order's creator                                        |
| underlying<mark style="color:red;">\*</mark> | string       | The underlying token being transacted. E.g. USDC, DAI, etc.,            |
| maturity<mark style="color:red;">\*</mark>   | string       | The maturity of market in unix seconds.                                 |
| status                                       | list(string) | List of statuses **expired**, **cancelled**, **full** or **insolvent**. |

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

```
{
    "orders": [
        {
            "order": {
                "key": "0x279eb2584cb32ccc7a512d3d46e3dbb83ecde4b0c231c3f4838cae0ea70223e8",
                "maker": "0x096Da21Ac79ae1EDbC69A07CE5c705E6c77Fec90",
                "underlying": "0x5592EC0cfb4dbc12D3aB100b257153436a1f0FEa",
                "vault": false,
                "exit": false,
                "principal": "30000000000000000000000",
                "premium": "3333000000000000000000",
                "maturity": "1669957199",
                "expiry": "1641372040"
            },
            "meta": {
                "price": "0.1111",
                "signature": "0x75d626fdf62c67cf1de04f077fd7447f1164976f7f60826a63eece886923c11b59f061bd7b6d81fa96cdc3208ff53d4926ad8ba66d06a9101cc81d0e23792aaa1c",
                "premiumAvailable": "3333000000000000000000",
                "principalAvailable": "30000000000000000000000",
                "sequence": 63604
            }
        },
        {
            "order": {
                "key": "0xa8181ff6e0bfa16130944d5add7220eed46f44796de7d4216728dde40376ac5e",
                "maker": "0x096Da21Ac79ae1EDbC69A07CE5c705E6c77Fec90",
                "underlying": "0x5592EC0cfb4dbc12D3aB100b257153436a1f0FEa",
                "vault": true,
                "exit": false,
                "principal": "107758620689655172413793",
                "premium": "10000000000000000000000",
                "maturity": "1669957199",
                "expiry": "1641371984"
            },
            "meta": {
                "price": "0.0928",
                "signature": "0xa4e8958193cf2cb9c70e4c4a7df9c3c7b68f89fd2f250d80e6bc9dbd9cba8c54415fb2f4d8da33c1d81d5a028233255b52adbf36bee3a2a929fb3ea3e735ff7a1c",
                "premiumAvailable": "10000000000000000000000",
                "principalAvailable": "107758620689655172413793",
                "sequence": 63593
            }
        },
    ...
    ]
}
```

{% endtab %}

{% tab title="400: Bad Request E.g. Invalid maturity" %}

```javascript
{
    "error": {
        "message": "invalid maturity"
    }
}
```

{% endtab %}
{% endtabs %}


# Get Last Trade Info

## Get Last Trade Info

<mark style="color:blue;">`GET`</mark> `https://api.swivel.exchange/v2/fills?underlying=u&maturity=m&depth=d`

This endpoint allows you to request the agreement most recently initiated in a given market. (The trade last made in a given market)\
\
Returns the parameters of the most recent agreement for the specified market.

#### Query Parameters

| Name                                         | Type   | Description                                                                                                            |
| -------------------------------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------- |
| underlying<mark style="color:red;">\*</mark> | string | The underlying token being transacted. E.g. USDC, DAI, etc.,                                                           |
| maturity<mark style="color:red;">\*</mark>   | string | The maturity of market in unix seconds.                                                                                |
| depth<mark style="color:red;">\*</mark>      | string | Specify **1** for getting the last trade. If more depth is specified, the result will be a sorted list of last trades. |

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

```
[
    {
        "key": "0xae3f59eabffcf1f15f384d5e582985d31a9aef4b181ecf56a0a37bab85013f1f",
        "price": "0.0799",
        "exit": false,
        "vault": false,
        "volume": "1.251564456e+20"
    }
]
```

{% endtab %}

{% tab title="400: Bad Request E.g. Invalid maturity" %}

```javascript
{
    "error": {
        "message": "invalid maturity"
    }
}
```

{% endtab %}
{% endtabs %}


# Get Markets

## Get Markets

<mark style="color:blue;">`GET`</mark> `https://api.swivel.exchange/v2/markets?status=s&depth=d`

This endpoint allows you to request a list of markets.

#### Query Parameters

| Name   | Type    | Description                      |
| ------ | ------- | -------------------------------- |
| status | string  | **active** or **matured**        |
| depth  | integer | The number of markets to return. |

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

```
[
  {
    "underlying": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
    "maturity": "1648177200"
  }
]
```

{% endtab %}
{% endtabs %}


# POST

All post endpoints are documented here.

## Post Order

<mark style="color:green;">`POST`</mark> `https://api.swivel.exchange/orders`

This endpoint allows you to request the detailed state and parameters for a given order.\
\
Returns the order's parameters as well as current order state and initial timestamp.

#### Request Body

| Name                                    | Type   | Description                                                                                                                                                                                                                     |
| --------------------------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Order<mark style="color:red;">\*</mark> | object | <p>Order object containing:<br>signature: string<br>key: string<br>maker: string<br>underlying: string<br>vault: boolean</p><p>exit: boolean <br>principal: string<br>premium: string<br>maturity: string<br>expiry: string</p> |

{% tabs %}
{% tab title="200 Order successfully posted." %}

{% endtab %}

{% tab title="400 E.g. Invalid order principal" %}

```
{
    "error": {
        "message": "order principal"
    }
}
```

{% endtab %}

{% tab title="404 Unable to place order in the provided market." %}

```
{    "message": "Unable to place order in specified market."}
```

{% endtab %}
{% endtabs %}


# Order

## Post Order

<mark style="color:green;">`POST`</mark> `https://api.swivel.exchange/v2/orders`

This endpoint allows you to request the detailed state and parameters for a given order.\
\
Returns the order's parameters as well as current order state and initial timestamp.

#### Request Body

| Name  | Type   | Description                                                                                                                                                                                                     |
| ----- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Order | object | <p>Order object containing:<br>signature: string<br>key: string<br>maker: string<br>underlying: string<br>floating: boolean <br>principal: string<br>interest: string<br>duration: string<br>expiry: string</p> |

{% tabs %}
{% tab title="200 Order successfully posted." %}

{% endtab %}

{% tab title="400 Incorrect order size." %}

```
{    "message": "Check order size limits: https://swivel.exchange/limits"}
```

{% endtab %}

{% tab title="404 Unable to place order in the provided market." %}

```
{    "message": "Unable to place order in specified market."}
```

{% endtab %}
{% endtabs %}


# Swivel.js

Javascript library for working with the Swivel Finance Protocol

## Installation

### Installing ethers.js

To use Swivel.js you'll need to install ethers.js (`^5.2.0`).

```bash
npm install --save ethers
```

> If demand for web3.js support is high, we'll consider supporting it in future releases.

### Installing swivel-js

```bash
npm install --save @swivel-finance/swivel-js
```

## Quickstart

Swivel.js provides implementations for the 3 main contracts of the Swivel protocol:

* [Swivel](/swivel-v2.0.0/developers/swivel.js/api/swivel) (sign orders, initiate/exit/cancel orders, split/combine/redeem tokens)
* [MarketPlace](/swivel-v2.0.0/developers/swivel.js/api/marketplace) (retrieve token/vault information for a market)
* [VaultTracker](/swivel-v2.0.0/developers/swivel.js/api/vaulttracker) (retrieve vault information for a market and owner)

In most cases you'll want to use the Swivel contract implementation to work with orders and tokens.

### Usage

#### Swivel

* [Create a Swivel instance](/swivel-v2.0.0/developers/swivel.js/api/swivel#creating-a-swivel-instance)
* [Sign an order](/swivel-v2.0.0/developers/swivel.js/api/swivel#signorder)
* [Fill an order](/swivel-v2.0.0/developers/swivel.js/api/swivel#initiate)

#### MarketPlace

* [Create a MarketPlace instance](/swivel-v2.0.0/developers/swivel.js/api/marketplace#creating-a-marketplace-instance)
* [Retrieve market information](/swivel-v2.0.0/developers/swivel.js/api/marketplace#markets)

#### VaultTracker

* [Create a VaultTracker instance](/swivel-v2.0.0/developers/swivel.js/api/vaulttracker#creating-a-vaulttracker-instance)

### Deployed Contract Addresses

To connect a Swivel or MarketPlace instance to the deployed contract on the Ethereum network, you'll need to know the contract address. You can find the currently deployed addresses here: <https://github.com/Swivel-Finance/swivel#current-deployments>

### Other Providers

You can use ethers.js to connect to the Ethereum network in different ways, not only using MetaMask. Please refer to the ethers.js documentation for different ways to connect: <https://docs.ethers.io/v5/getting-started/#getting-started--connecting>.

Once you have created a provider and a signer, creating a Swivel, MarketPlace or VaultTracker instance is identical to the steps illustrated above.


# API

This section describes the API of Swivel.js' smart contract wrappers.

Swivel.js provides implementations for the 3 main contracts of the Swivel protocol:

* [Swivel](/swivel-v2.0.0/developers/swivel.js/api/swivel) (sign orders, initiate/exit/cancel orders, split/combine/redeem tokens)
* [MarketPlace](/swivel-v2.0.0/developers/swivel.js/api/marketplace) (retrieve token/vault information for a market)
* [VaultTracker](/swivel-v2.0.0/developers/swivel.js/api/vaulttracker) (retrieve vault information for a market and owner)

In most cases you'll want to use the Swivel contract implementation to work with orders and tokens.


# Swivel

A TypeScript wrapper for the Swivel smart contract.

## Overview

The Swivel contract wrapper allows a user to sign orders; initiate, exit, and cancel orders; as well as split, combine, and redeem their tokens.

An order is a struct of the following shape:

### Order

```typescript
interface Order {
    key: string;
    maker: string;
    underlying: string;
    vault: boolean;
    exit: boolean;
    principal: string;
    premium: string;
    maturity: string;
    expiry: string;
}
```

### Creating a Swivel instance

The snippet below illustrates how you can create a Swivel instance and what information you need to do so.

```typescript
import { EthersVendor, Swivel } from '@swivel-finance/swivel-js';
import { ethers } from 'ethers';

// you need the chain id of the network you want to use
// this is necessary for signing offline orders
const chainId = 1;
// you need the address of the deployed swivel contract on that network
const swivelAddress = '0x3b983B701406010866bD68331aAed374fb9f50C9';

// create an ethers provider and signer,...
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();

// ...create a Vendor for the Swivel contract,
const vendor = new EthersVendor(provider, signer);

// ...and use the vendor to instantiate the Swivel contract
const swivel = new Swivel(vendor, chainId, swivelAddress).at(swivelAddress);
```

## Properties

### address

Holds the current contract address used by the Swivel instance.

#### Signature

```typescript
address?: string;
```

## Getters

### NAME

Allows a user to get the Swivel domain name for EIP-712 signing.

#### Signature

```typescript
NAME (): Promise<string>;
```

#### Returns

A promise that resolves with the domain name if the contract call succeeds and rejects otherwise.

### VERSION

Allows a user to get the Swivel domain version for EIP-712 signing.

#### Signature

```typescript
VERSION (): Promise<string>;
```

#### Returns

A promise that resolves with the domain version if the contract call succeeds and rejects otherwise.

### domain

Allows a user to get the Swivel domain for EIP-712 signing.

#### Signature

```typescript
domain (): Promise<string>;
```

#### Returns

A promise that resolves with the domain if the contract call succeeds and rejects otherwise.

### marketPlace

Allows a user to get the associated MarketPlace contract address.

#### Signature

```typescript
marketPlace (): Promise<string>;
```

#### Returns

A promise that resolves with the MarketPlace contract's address if the contract call succeeds and rejects otherwise.

## Methods

### constructor

Creates an instance of the Swivel smart contract wrapper.

> After creating an instance of the Swivel contract it can be used to sign offline orders, however it cannot yet interact with the deployed Swivel smart contract on chain. You need to additionally invoke the `at()` method of the Swivel instance to connect the instance with the contract on chain.

> Even though chain-id and contract address are optional parameters for the Swivel constructor, `signOrder()` requires these parameters to be set. If you want to use the Swivel instance to sign offline orders, you **must** provide the paramaters.

#### Signature

```typescript
constructor (v: Vendor, i?: number, c?: string): Swivel;
```

#### Parameters

| Paramater | Type     | Description                                             |
| --------- | -------- | ------------------------------------------------------- |
| v         | `Vendor` | A vendor instance (ethers.js or web3.js vendor) to use. |
| i         | `number` | The chain-id for the deployed Swivel smart contract.    |
| c         | `string` | The address of the deployed Swivel smart contract.      |

#### Example

```typescript
import { EthersVendor, Swivel } from '@swivel-finance/swivel-js';
import { ethers } from 'ethers';

// you need the chain id of the network you want to use
const chainId = 1;
// you need the address of the deployed swivel contract on that network
const swivelAddress = '0x3b983B701406010866bD68331aAed374fb9f50C9';

// create an ethers provider and signer,...
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();

// ...create a Vendor for the Swivel contract,
const vendor = new EthersVendor(provider, signer);

// ...and use the vendor to instantiate the Swivel contract
const swivel = new Swivel(vendor, chainId, swivelAddress);
```

### at

Connects a Swivel instance to a deployed Swivel smart contract on chain.

#### Signature

```typescript
at (a: string, o?: TxOptions): Swivel;
```

#### Parameters

| Paramater | Type        | Description                                                                      |
| --------- | ----------- | -------------------------------------------------------------------------------- |
| a         | `string`    | The address of the deployed Swivel smart contract.                               |
| o         | `TxOptions` | Optional transaction options to override ethers.js' default transaction options. |

#### Returns

The connected Swivel instance.

#### Example

```typescript
import { EthersVendor, Swivel } from '@swivel-finance/swivel-js';
import { ethers } from 'ethers';

// you need the chain id of the network you want to use
const chainId = 1;
// you need the address of the deployed swivel contract on that network
const swivelAddress = '0x3b983B701406010866bD68331aAed374fb9f50C9';

// create an ethers provider and signer,...
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();

// ...create a Vendor for the Swivel contract,
const vendor = new EthersVendor(provider, signer);

// ...and use the vendor to instantiate the Swivel contract
// you can chain the `.at()` call directly to the constructor
const swivel = new Swivel(vendor, chainId, swivelAddress).at(swivelAddress);
```

### signOrder

Allows a user to sign an offline order using EIP-712.

#### Signature

```typescript
signOrder (o: Order): Promise<string>;
```

#### Parameters

| Paramater | Type    | Description              |
| --------- | ------- | ------------------------ |
| o         | `Order` | An order object to sign. |

#### Returns

A promise that resolves with the 132 byte ECDSA signature of the order.

#### Example

```typescript
import { EthersVendor, Swivel } from '@swivel-finance/swivel-js';
import { ethers, utils } from 'ethers';

// you need the chain id of the network you want to use
const chainId = 1;
// you need the address of the deployed swivel contract on that network
const swivelAddress = '0x3b983B701406010866bD68331aAed374fb9f50C9';

// create an ethers provider and signer,...
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();

// ...create a Vendor for the Swivel contract,
const vendor = new EthersVendor(provider, signer);
// ...and use the vendor to instantiate the Swivel contract
const swivel = new Swivel(vendor, chainId, swivelAddress);

// the order maker is your account address
const maker = await signer.getAddress();
// the order key should be a hash of your account address and a timestamp
const key = utils.keccak256(utils.toUtf8Bytes(`${ maker }${ Date.now() }`));
// you will also need the underlying token address and maturity of a market
// you can get them from the Swivel Exchange API
const underlying = '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48';
const maturity = '1648177200';

// create an order
const order: Order = {
    key: key,
    maker: maker,
    underlying: underlying,
    maturity: maturity,
    vault: false,
    exit: false,
    principal: '1000',
    premium: '50',
    expiry: '123456789',
};

// you can now sign the order
const signature = await swivel.signOrder(order);
```

### cancelled

Allows a user to check if an order was cancelled.

#### Signature

```typescript
cancelled (k: string): Promise<boolean>;
```

#### Parameters

| Paramater | Type     | Description                    |
| --------- | -------- | ------------------------------ |
| k         | `string` | The key of the order to check. |

#### Returns

A promise that resolves with `true` or `false` if the contract call succeeds and rejects otherwise.

### filled

Allows a user to retrieve an order's filled volume.

#### Signature

```typescript
filled (k: string): Promise<string>;
```

#### Parameters

| Paramater | Type     | Description                    |
| --------- | -------- | ------------------------------ |
| k         | `string` | The key of the order to check. |

#### Returns

A promise that resolves with the orders filled volume if the contract call succeeds and rejects otherwise.

### initiate

Allows a user to fill part or all of any number of orders by initiating a fixed-yield (zcToken) or amplified-yield (nToken) position.

Splits an array of `bytes32` signatures into R,S,V, and calls the initiate method on the Swivel.sol contract.

#### Signature

```typescript
initiate (o: Order[], a: uint256[], s: string[]): Promise<TxResponse>;
```

#### Parameters

| Paramater | Type        | Description                                                                       |
| --------- | ----------- | --------------------------------------------------------------------------------- |
| o         | `Order[]`   | An array of order objects to be filled.                                           |
| a         | `uint256[]` | An array of `uint256` amounts. The amount filled with each o\[i] order submitted. |
| s         | `string[]`  | An array of 132 byte ECDSA signatures associated with each o\[i] order submitted. |

#### Returns

A promise that resolves with a `TxResponse` if the contract call succeeds and rejects otherwise.

#### Example

```typescript
import { EthersVendor, Swivel } from '@swivel-finance/swivel-js';
import { ethers } from 'ethers';

// you need a subset of the ERC-20 ABI for token allowance and approval
const ERC_20_ABI = [
    'function allowance(address owner, address spender) public view returns (uint256)',
    'function approve(address spender, uint256 value) public returns (bool)',
];

/**
 * Fill an order.
 * 
 * @param amount - the amount of volume to fill
 */
export async function marketOrderFixed (amount: number): Promise<void> {

    // convert the amount to a BigNumber with the appropriate amount of decimals (e.g. 18 for DAI)
    const fillAmount = ethers.utils.parseUnits(amount.toString(), 18);

    // create an ethers provider and signer
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    const signer = provider.getSigner();

    // create an EthersVender for the Swivel wrapper
    const vendor = new EthersVendor(provider, signer);

    // constants for Swivel on rinkeby (this might be outdated)
    const chainId = 4;
    const swivelAddress = '0xDe9a819630094dF6dA6FF7CCc77E04Fd3ad0ACFE';
    const underlyingAddress = '0x5592EC0cfb4dbc12D3aB100b257153436a1f0FEa';

    // create the Swivel wrapper
    const swivel = new Swivel(vendor, chainId, swivelAddress).at(swivelAddress);

    // to fill an order with Swivel, we need to approve Swivel to transfer our tokens
    // in order to do this, we need to:
    //   1. create an ERC20 contract instance
    //   2. check if the Swivel contract has sufficient allowance for the fill amount
    //   3. approve the Swivel contract for at least the fill amount

    // create the ERC-20 token contract for the underlying (e.g. DAI)
    const token = new ethers.Contract(underlyingAddress, ERC_20_ABI, provider);

    // check approval
    const approvalAmount = await token.allowance(window.ethereum.selectedAddress, swivelAddress) as ethers.BigNumber;

    // if not approved approve max uint 
    // (this frees you from having to approve each single fill)
    if (approvalAmount.lt(fillAmount)) {
    
        const approve = await token.approve(swivelAddress, ethers.constants.MaxUint256) as ethers.providers.TransactionResponse;
        await approve.wait();
    }

    // hardcoded nToken purchase order (the order being filled) + signature valid on rinkeby
    // in a real-world scenario you would fetch orders from the Preview Market Order API call
    const order = {
        key: '0x3449db081da0329d51b6757809ce4c1042ea0c110b8980628e46cb4d4b8297fb',
        maker: '0x3f60008Dfd0EfC03F476D9B489D6C5B13B3eBF2C',
        underlying: '0x5592EC0cfb4dbc12D3aB100b257153436a1f0FEa',
        vault: true,
        exit: false,
        principal: '40000000000000000000000',
        premium: '2000000000000000000000',
        maturity: '1662089767',
        expiry: '1633324220',
    };
    const signature = '0x2ab021d3577a940b6d2b2f47288dc240fb003c24d0af93751bd3b9354e1df0d03e6d2c47a7bf566d6ec887b6884edb80c80f0890d247a363eb31b1e99d5636ae1c';

    // fill the hardcoded order by initiating your position
    // each parameter is an array, as multiple orders can be filled at once
    const tx = await swivel.initiate([order], [fillAmount.toString()], [signature]) as ethers.providers.TransactionResponse;
    
    // wait for the transaction to confirm
    const receipt = await tx.wait();

    console.log(receipt);
}
```

### exit

Allows a user to fill part or all of any number of orders by exiting/selling off a zcToken or nToken position.

Splits an array of `bytes32` signatures into R,S,V, and calls the exit method on the Swivel.sol contract.

#### Signature

```typescript
exit (o: Order[], a: uint256[], s: string[]): Promise<TxResponse>;
```

#### Parameters

| Paramater | Type        | Description                                                                       |
| --------- | ----------- | --------------------------------------------------------------------------------- |
| o         | `Order[]`   | An array of order objects to be filled.                                           |
| a         | `uint256[]` | An array of `uint256` amounts. The amount filled with each o\[i] order submitted. |
| s         | `string[]`  | An array of 132 byte ECDSA signatures associated with each o\[i] order submitted. |

#### Returns

A promise that resolves with a `TxResponse` if the contract call succeeds and rejects otherwise.

### cancel

Allows a user to cancel their order.

Splits a `bytes32` signature into R,S,V, and calls the cancel method on the Swivel Brokerage contract. Can only be called by the order's maker.

#### Signature

```typescript
cancel (o: Order, s: string): Promise<TxResponse>;
```

#### Parameters

| Paramater | Type     | Description                                                  |
| --------- | -------- | ------------------------------------------------------------ |
| o         | `Order`  | An order object to be cancelled.                             |
| s         | `string` | The full 132 byte ECDSA signature associated with the order. |

#### Returns

A promise that resolves with a `TxResponse` if the contract call succeeds and rejects otherwise.

### splitUnderlying

Allows a user to split their underlying tokens into zcTokens and nTokens.

#### Signature

```typescript
splitUnderlying (u: string, m: uint256, a: uint256): Promise<TxResponse>;
```

#### Parameters

| Paramater | Type      | Description                                   |
| --------- | --------- | --------------------------------------------- |
| u         | `string`  | The address of the underlying token contract. |
| m         | `uint256` | The market's maturity.                        |
| a         | `uint256` | The amount of underlying to split.            |

#### Returns

A promise that resolves with a `TxResponse` if the contract call succeeds and rejects otherwise.

### splitUnderlying

Allows a user to combine an equal amount of their zcTokens and nTokens into underlying.

#### Signature

```typescript
combineTokens (u: string, m: uint256, a: uint256): Promise<TxResponse>;
```

#### Parameters

| Paramater | Type      | Description                                   |
| --------- | --------- | --------------------------------------------- |
| u         | `string`  | The address of the underlying token contract. |
| m         | `uint256` | The market's maturity.                        |
| a         | `uint256` | The amount of zcTokens/nTokens to combine.    |

#### Returns

A promise that resolves with a `TxResponse` if the contract call succeeds and rejects otherwise.

### redeemZcToken

Allows a user to redeem their zcTokens at maturity.

#### Signature

```typescript
redeemZcToken (u: string, m: uint256, a: uint256): Promise<TxResponse>;
```

#### Parameters

| Paramater | Type      | Description                                   |
| --------- | --------- | --------------------------------------------- |
| u         | `string`  | The address of the underlying token contract. |
| m         | `uint256` | The market's maturity.                        |
| a         | `uint256` | The amount of zcTokens to redeem.             |

#### Returns

A promise that resolves with a `TxResponse` if the contract call succeeds and rejects otherwise.

### redeemZcToken

Allows a user to redeem the interest generated by their nTokens.

#### Signature

```typescript
redeemVaultInterest (u: string, m: uint256): Promise<TxResponse>;
```

#### Parameters

| Paramater | Type      | Description                                   |
| --------- | --------- | --------------------------------------------- |
| u         | `string`  | The address of the underlying token contract. |
| m         | `uint256` | The market's maturity.                        |

#### Returns

A promise that resolves with a `TxResponse` if the contract call succeeds and rejects otherwise.


# MarketPlace

A TypeScript wrapper for the MarketPlace smart contract.

## Overview

The MarketPlace contract wrapper allows a user to fetch market information from the MarketPlace smart contract, mature a market or transfer their vault notional.

Market information is returned in a struct of the following shape:

### Market

```typescript
interface Market {
    cTokenAddr: string;
    zcTokenAddr: string;
    vaultAddr: string;
    maturityRate: string;
}
```

### Creating a MarketPlace instance

The snippet below illustrates how you can create a MarketPlace instance and what information you need to do so.

```typescript
import { EthersVendor, MarketPlace } from '@swivel-finance/swivel-js';
import { ethers } from 'ethers';

// you need the address of the deployed MarketPlace contract
const marketPlaceAddress = '0x998689650D4d55822b4bDd4B7DB5F596bf6b3570';

// create an ethers provider and signer,...
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();

// ...create a Vendor for the MarketPlace contract,
const vendor = new EthersVendor(provider, signer);

// ...and use the vendor to instantiate the MarketPlace contract
const marketPlace = new MarketPlace(vendor).at(marketPlaceAddress);
```

## Properties

### address

Holds the current contract address used by the MarketPlace instance.

#### Signature

```typescript
address?: string;
```

## Getters

### admin

Allows a user to get the admin address of this MarketPlace.

#### Signature

```typescript
admin (): Promise<string>;
```

#### Returns

A promise that resolves with the admin address if the contract call succeeds and rejects otherwise.

### swivel

Allows a user to get the Swivel contract address associated with this MarketPlace.

#### Signature

```typescript
swivel (): Promise<string>;
```

#### Returns

A promise that resolves with the Swivel contract's address if the contract call succeeds and rejects otherwise.

### paused

Allows a user to check if this MarketPlace has been paused.

#### Signature

```typescript
paused (): Promise<boolean>;
```

#### Returns

A promise that resolves with `true` or `false` if the contract call succeeds and rejects otherwise.

## Methods

### constructor

Creates an instance of the MarketPlace smart contract wrapper.

#### Signature

```typescript
constructor (v: Vendor): MarketPlace;
```

#### Parameters

| Paramater | Type     | Description                                             |
| --------- | -------- | ------------------------------------------------------- |
| v         | `Vendor` | A vendor instance (ethers.js or web3.js vendor) to use. |

### at

Connects a MarketPlace instance to a deployed MarketPlace smart contract on chain.

#### Signature

```typescript
at (a: string, o?: TxOptions): MarketPlace;
```

#### Parameters

| Paramater | Type        | Description                                                                      |
| --------- | ----------- | -------------------------------------------------------------------------------- |
| a         | `string`    | The address of the deployed MarketPlace smart contract.                          |
| o         | `TxOptions` | Optional transaction options to override ethers.js' default transaction options. |

#### Returns

The connected MarketPlace instance.

### markets

Allows a user to retrieve market information from the MarketPlace.

#### Signature

```typescript
markets (u: string, m: uint256): Promise<Market>;
```

#### Parameters

| Paramater | Type      | Description                                   |
| --------- | --------- | --------------------------------------------- |
| u         | `string`  | The address of the market's underlying token. |
| m         | `uint256` | The market's maturity.                        |

#### Returns

A promise that resolves with a `Market` if the contract call succeeds and rejects otherwise.

#### Example

Fetch the market information from one of Swivel's markets from the MarketPlace contract.

A market is identified my its underlying token address and its maturity. You can use the [Swivel Exchange API](/swivel-v2.0.0/developers/exchange/get/get-markets) to fetch the available markets (underlying/maturity pairs).

```typescript
// you will need the underlying token address and maturity of a market
const underlying = '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48';
const maturity = '1648177200';

// assuming you already created a MarketPlace instance (as shown above)
// use the underlying and maturity to retrieve the market information
const market = await marketPlace.markets(underlying, maturity);

// you now have access to the market's cTokenAddress, zcTokenAdress, 
// vaultAddress and maturityRate, e.g.:
const cTokenAddress = market.cTokenAddress;
const maturityRate = market.maturityRate;
```

### matureMarket

Allows a user to mature a market in the MarketPlace.

#### Signature

```typescript
matureMarket (u: string, m: uint256): Promise<TxResponse>;
```

#### Parameters

| Paramater | Type      | Description                                   |
| --------- | --------- | --------------------------------------------- |
| u         | `string`  | The address of the market's underlying token. |
| m         | `uint256` | The market's maturity.                        |

#### Returns

A promise that resolves with a `TxResonse` if the contract call succeeds and rejects otherwise.

### transferVaultNotional

Allows a user to transfer the their notional from a market in the MarketPlace.

#### Signature

```typescript
transferVaultNotional (u: string, m: uint256, t: string, a: uint256): Promise<TxResponse>;
```

#### Parameters

| Paramater | Type      | Description                                           |
| --------- | --------- | ----------------------------------------------------- |
| u         | `string`  | The address of the market's underlying token.         |
| m         | `uint256` | The market's maturity.                                |
| t         | `string`  | The target address to which to transfer the notional. |
| a         | `uint256` | The amount of notional to transfer.                   |

#### Returns

A promise that resolves with a `TxResonse` if the contract call succeeds and rejects otherwise.


# VaultTracker

A TypeScript wrapper for the VaultTracker smart contract.

## Overview

The VaultTracker contract wrapper allows a user to fetch vault information for a particular market and owner.

Vault information is returned in a struct of the following shape:

### Vault

```typescript
interface Vault {
    notional: string;
    redeemable: string;
    exchangeRate: string;
}
```

### Creating a VaultTracker instance

The snippet below illustrates how you can create a VaultTracker instance and what information you need to do so.

```typescript
import { EthersVendor, VaultTracker } from '@swivel-finance/swivel-js';
import { ethers } from 'ethers';

// create an ethers provider and signer,...
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();

// ...create a Vendor for the VaultTracker contract,
const vendor = new EthersVendor(provider, signer);

// to create a VaultTracker instance you'll need the address of its
// deployed contract - each market has it's own VaultTracker contract
// you can retrieve the address of a VaultTracker by calling the 
// `markets` method of the MarketPlace wrapper

// you will need the underlying token address and maturity of a market
// you can get them from the Swivel Exchange API
const underlying = '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48';
const maturity = '1648177200';

// assuming you already created a MarketPlace instance, 
// retrieve the desired market information...
const market = await marketPlace.markets(underlying, maturity);
// ...and extract the `vaultAddress` of the market
const vaultAddress = market.vaultAddr;

// use the `vendor` and `vaultAdrress` to instantiate the VaultTracker
const vaultTracker = new VaultTracker(vendor).at(vaultAddress);
```

## Properties

### address

Holds the current contract address used by the VaultTracker instance.

#### Signature

```typescript
address?: string;
```

## Getters

### admin

Allows a user to get the admin address of this VaultTracker. This is the address of the MarketPlace smart contract that owns this VaultTracker.

#### Signature

```typescript
admin (): Promise<string>;
```

#### Returns

A promise that resolves with the admin address if the contract call succeeds and rejects otherwise.

### swivel

Allows a user to get the Swivel contract address associated with this VaultTracker.

#### Signature

```typescript
swivel (): Promise<string>;
```

#### Returns

A promise that resolves with the Swivel contract's address if the contract call succeeds and rejects otherwise.

### maturity

Allows a user to retrieve the vault's maturity. This is a Unix timestamp in seconds.

#### Signature

```typescript
maturity (): Promise<string>;
```

#### Returns

A promise that resolves with the vault's maturity if the contract call succeeds and rejects otherwise.

### maturityRate

Allows a user to retrieve the vault's maturity rate. This is the cToken's exchange rate at the time of maturity.

#### Signature

```typescript
maturityRate (): Promise<string>;
```

#### Returns

A promise that resolves with the vault's maturity rate if the contract call succeeds and rejects otherwise.

### cTokenAddr

Allows a user to retrieve the vault's cToken address.

#### Signature

```typescript
cTokenAddr (): Promise<string>;
```

#### Returns

A promise that resolves with the vault's cToken address if the contract call succeeds and rejects otherwise.

## Methods

### constructor

Creates an instance of the VaultTracker smart contract wrapper.

#### Signature

```typescript
constructor (v: Vendor): VaultTracker;
```

#### Parameters

| Paramater | Type     | Description                                             |
| --------- | -------- | ------------------------------------------------------- |
| v         | `Vendor` | A vendor instance (ethers.js or web3.js vendor) to use. |

### at

Connects a VaultTracker instance to a deployed VaultTracker smart contract on chain.

#### Signature

```typescript
at (a: string, o?: TxOptions): VaultTracker;
```

#### Parameters

| Paramater | Type        | Description                                                                      |
| --------- | ----------- | -------------------------------------------------------------------------------- |
| a         | `string`    | The address of the deployed VaultTracker smart contract.                         |
| o         | `TxOptions` | Optional transaction options to override ethers.js' default transaction options. |

#### Returns

The connected VaultTracker instance.

### vaults

Allows a user to retrieve vault information for a specific owner from the VaultTracker.

#### Signature

```typescript
vaults (o: string): Promise<Vault>;
```

#### Parameters

| Paramater | Type     | Description                       |
| --------- | -------- | --------------------------------- |
| o         | `string` | The address of the vault's owner. |

#### Returns

A promise that resolves with a `Vault` if the contract call succeeds and rejects otherwise.

### balancesOf

Allows a user to retrieve the notional and redeemable balances for a specific owner.

#### Signature

```typescript
balancesOf (o: string): Promise<[string, string]>;
```

#### Parameters

| Paramater | Type     | Description                       |
| --------- | -------- | --------------------------------- |
| o         | `string` | The address of the vault's owner. |

#### Returns

A promise that resolves with a tuple containing the notional and redeemable balance if the contract call succeeds and rejects otherwise.


# Swivel.py

A python library for interaction with the Swivel protocol

Swivel.py is a collection of what we call *Higher Order Contracts*. These are language specific, Python in this case, constructs that abstract and encapsulate the tedious and boilerplate logic of working with low-level smart contracts.

Swivel.py does not act as an exchange wrapper for the Swivel Exchange, and solely provides an interface to interact with our smart contracts. For examples of how to integrate with the Swivel Exchange, as well as helpers to do so, check out [Scrivel](https://docs.swivel.finance/developers/scrivel-python-examples).

### Installation

```
pip install -r requirements.txt
```

### Running Tests

```
pytest
```

#### Examples

Before we dive into the specifics, you should take a look at the classes in action. There is an entire [repo](https://github.com/Swivel-Finance/scrivel/tree/main/scrivel/examples) dedicated to just this. Scrivel shows everything from basic reads to more involved writes to entire market-making operations.

Remember that Swivel.py is a library with a very specific, and narrow, use case. Present the Swivel protocol as an object oriented, pythonic collection ready to be used in your own scripting.

***

#### Vendors

One principal concept to grasp is that Swivel.py relies on what in refers to as a `vendor` to handle low-level chores related to the Ethereum network. Web3.py is a supported vendor at this time, and there may be more in the future.

**W3**

The W3 Vendor class is a Web3.py specific Vendor that can be used with the Swivel.py Higher Order Contracts. Constructed with a Web3.py specific `Provider`, our class exposes (hoists) some useful methods from within Web3 itself.

You can see the Vendor class in use throught the [Scrivel examples](https://github.com/Swivel-Finance/scrivel/tree/main/scrivel/examples)

**Signer**

Our W3 class also constructs and appends a Signer class to itself. This is an abstraction of the EIP712 logic needed to sign a Swivel Order *offline*. You generally will not interact with the Signer directly as the Vendor itself exposes a `sign_order` method. Also note that, in order to sign an order *offline* you need to be in possession of the private key associated with the address of the order's *maker*. See here for an example.

**Private Key**

As mentioned above, you must have acess to the private key intented to be used for signing transactions *offline* and it should be exported to your shell as `PRIVATE_KEY`.

***

#### Higher Order Contracts

There are classes present for exposing the A.P.I (ABI) of deployed Swivel smart contracts in a pyhtonic way. Primarily

* swivel.py
* market\_place.py

will be your places of contact, as shown in [Scrivel](https://github.com/Swivel-Finance/scrivel/tree/main/scrivel/examples). There is a contract present for the VaultTracker which, while typically used internally by the MarketPlace, can be used in isolation to check balances.

The H.O.Cs are constructed with a Vendor instance, then connected to a deployment via the `at` method. Once established, the contract is ready to be used.

**Opts**

Note that all H.O.C method signatures match the exposed signatures of Swivel smart contract methods. There is also, in every case, an optional `opts` keyword that may be passed. This argument can be omitted in `call` (read) type operations generally, but in `send` (write) type operations the user should hydrate important values such as gas, gasPrice etc...

**Call, Send (and Transact)**

Another principal concept to grasp when using Swivel Higher Order Contracts is that the exposed methods do not attempt an actual low level `call` or `send` (read and write) type operation. Instead, a tuple of length 2 is always returned from any method invocation. The 2nd item in the tuple is always the `opts` dictionary (or None). Operations that are `send` (write) type will always assure that the `from` key is set with the users address. Any other important values (gas, gasPrice, etc...) should be set by the user by using the `opts` dictionary as described above.

The first item of the tuple will be, depending on the type (call, send), a *callable* or *transactable* object. Callable objects may be wrapped in the `call` helper to execute. Public constants and variables as well as any non-state-changing getters fall under this category. [Swivel calls](https://github.com/Swivel-Finance/scrivel/blob/main/scrivel/examples/swivel_calls.py) for example. Transactable objects are, intentionally, handled differently and are the reason why Swivel.py returns a tuple from contract method invocations. State changing send type operations require a signature, unless the account being used in unlocked. You are likely not working with unlocked accounts (except perhaps if you are hosting your own node and have your account unlocked locally, see below). Swivel.py exposes methods on the Vendor class (build\_transaction, sign\_transaction, etc...) to facilitate signing *offline* (given you have exported the correct private key to your shell). The convenience method `send` builds, signs and broadcasts an offline transaction. See [here](https://github.com/Swivel-Finance/scrivel/blob/main/scrivel/examples/order_examples.py) for some examples.

In the case you are working with unlocked accounts you can use the `transact` helper directly as there is no need to sign


# swivel

### Sub-modules

* swivel.abstracts
* swivel.contracts
* swivel.vendors


# swivel.abstracts

## Module `swivel.abstracts` <a href="#id" id="id"></a>

### Sub-modules

* swivel.abstracts.deployed
* swivel.abstracts.market\_place
* swivel.abstracts.swivel
* swivel.abstracts.vault\_tracker


# swivel.abstracts.deployed

### Classes

### Class `Deployed` <a href="#id" id="id"></a>

> ```
> class Deployed
> ```

Helper class that provides a standard way to create an ABC using inheritance.

**Descendants**

* swivel.abstracts.market\_place.MarketPlace
* swivel.abstracts.swivel.Swivel
* swivel.abstracts.vault\_tracker.VaultTracker

**Methods**

**Method `at`**

> ```
> def at(
>     self,
>     a,
>     opts=None
> )
> ```

Get a reference to the vendor specific contract instance deployed at a given address

### Parameters

a (string) the address of the deployed smart contract

opts (dict) optional tx options

**Method `tx_opts`**

> ```
> def tx_opts(
>     self,
>     o
> )
> ```

Sets default transaction options


# swivel.abstracts.market\_place

### Classes

#### Class `MarketPlace` <a href="#id" id="id"></a>

> ```
> class MarketPlace
> ```

Helper class that provides a standard way to create an ABC using inheritance.

**Ancestors**

* [swivel.abstracts.deployed.Deployed](#id-13)

**Descendants**

* [swivel.contracts.market\_place.MarketPlace](#id-17)

**Methods**

**Method `admin`**

> ```
> def admin(
>     self,
>     opts=None
> )
> ```

The stored admin address for this contract

### Returns

web3 callable, opts

**Method `c_token_address`**

> ```
> def c_token_address(
>     self,
>     u,
>     m,
>     opts=None
> )
> ```

Gets the compound token address associated with a given market

### Parameters

u (string) Underlying token address

m (int) Maturity epoch

opts (dict) optional call opts

### Returns

web3 callable, opts

**Method `create_market`**

> ```
> def create_market(
>     self,
>     m,
>     c,
>     n,
>     s,
>     opts=None
> )
> ```

Creates a new market

### Description

New instances of both ZcToken and VaultTracker are deployed, their addresses then being associated with the newly created market.

Note that this method is only callable by the admin

### Parameters

m (int) Epoch in seconds, the maturity of the market

c (string) Address of the Compound token associated with the market

n (string) Name for the new ZcToken s (string) Name for the new ZcToken

opts (dict) Optional transaction options

### Returns

web3 transactable, opts

**Method `markets`**

> ```
> def markets(
>     self,
>     u,
>     m,
>     opts=None
> )
> ```

Gets the market associated with the given underlying and maturity arguments

### Description

The returned Market object is { cTokenAddr, ZcTokenAddr, vaultAddr }

### Parameters

u (string) Underlying token address&#x20;

m (int) Muturity epoch opts (dict) optional call opts

### Returns

web3 callable, opts

**Method `mature_market`**

> ```
> def mature_market(
>     self,
>     u,
>     m,
>     opts=None
> )
> ```

Called after maturity, allowing all of the zcTokens to earn floating interest on Compound until funds are released

### Parameters

u (string) Underlying token address

m (int) Maturity epoch opts (dict) optional call opts

### Returns

web3 transactable, opts

**Method `pause`**

> ```
> def pause(
>     self,
>     b,
>     opts=None
> )
> ```

Allows the admin to pause / unpause market transactions

### Parameters

b Boolean which acts as a toggle. True to pause, False to unpause

### Returns

web3 transactable, opts

**Method `paused`**

> ```
> def paused(
>     self,
>     opts=None
> )
> ```

A boolean which indicates a pause in all markets if truthy

### Returns

web3 callable, opts

**Method `set_swivel_address`**

> ```
> def set_swivel_address(
>     self,
>     a,
>     opts=None
> )
> ```

Sets the address of the Swivel smart contract this market place is associated with

### Description

Note that this method is only callable by the admin once

### Parameters

a (address) The address of a deployed Swivel smart contract

opts (dict) Optional transaction options

### Returns

web3 transactable, opts

**Method `swivel`**

> ```
> def swivel(
>     self,
>     opts=None
> )
> ```

The address of the associated Swivel contract deployment

### Returns

web3 callable, opts

**Method `transfer_admin`**

> ```
> def transfer_admin(
>     self,
>     a,
>     opts=None
> )
> ```

Allows the current admin to transfer the title to another party

### Description

Note that this method is only callable by the admin

### Parameters

a (address) Address of the new admin

### Returns

web3 transactable, opts

**Method `transfer_vault_notional`**

> ```
> def transfer_vault_notional(
>     self,
>     u,
>     m,
>     t,
>     a,
>     opts=None
> )
> ```

Transfer vault notional from sender to a given address

### Parameters

u (string) Underlying token address

m (int) Muturity epoch

t (string) Address of the amount owner

a (int) Amount to transfer

opts (dict) Optional transaction opts

### Returns

web3 transactable, opts


# swivel.abstracts.swivel

### Classes

#### Class `Swivel` <a href="#id" id="id"></a>

> ```
> class Swivel
> ```

Helper class that provides a standard way to create an ABC using inheritance.

**Ancestors**

* [swivel.abstracts.deployed.Deployed](#id-13)

**Descendants**

* [swivel.contracts.swivel.Swivel](#id-18)

**Methods**

**Method `admin`**

> ```
> def admin(
>     self,
>     opts=None
> )
> ```

The stored admin address for this contract

### Returns

web3 callable, opts

**Method `cancel`**

> ```
> def cancel(
>     self,
>     order,
>     s,
>     opts=None
> )
> ```

Allows the cancellation of an order, preventing it from being filled further

### Parameters

order (dict) An offline swivel order

s (string) Valid ECDSA signature for the order

opts (dict) Optional tx opts

### Returns

web3 transactable, opts

**Method `combine_tokens`**

> ```
> def combine_tokens(
>     self,
>     u,
>     m,
>     a,
>     opts=None
> )
> ```

Allows users to deposit/burn 1:1 amounts of both zcTokens and vault notional, in the process 'combining' the two and redeeming underlying

### Parameters

u (string) Address of the underlying token

m (int) Maturity timestamp of the market

a (int) Amount of zctokens being redeemed

opts (dict) Optional tx opts

### Returns

web3 transactable, opts

**Method `domain`**

> ```
> def domain(
>     self,
>     opts=None
> )
> ```

The stored EIP712 domain hash for this contract

### Returns

web3 callable, opts

**Method `exit`**

> ```
> def exit(
>     self,
>     orders,
>     a,
>     s,
>     opts=None
> )
> ```

Allows a user to exit (sell) a currently held position to the marketplace

### Parameters

orders (tuple) Offline swivel orders

a (list) Order volume (principal) amounts relative to orders list

s (tuple) Valid ECDSA signatures for each order

opts (dict) Optional tx opts

### Returns

web3 transactable, opts

**Method `feenominators`**

> ```
> def feenominators(
>     self,
>     i,
>     opts=None
> )
> ```

The stored fee constants for this contract

### Parameters

i (int) Index of the fenominator array to return

### Returns

web3 callable, opts

**Method `hold`**

> ```
> def hold(
>     self,
>     opts=None
> )
> ```

The stored hold constant for this contract

### Description

TODO

### Returns

web3 callable, opts

**Method `initiate`**

> ```
> def initiate(
>     self,
>     orders,
>     a,
>     s,
>     opts=None
> )
> ```

Allows a user to initiate a position

### Parameters

orders (tuple) Offline swivel orders

a (list) Order volume (principal) amounts relative to orders list

s (tuple) Valid ECDSA signatures for each order

opts (dict) Optional tx opts

### Returns

web3 transactable, opts

**Method `market_place`**

> ```
> def market_place(
>     self,
>     opts=None
> )
> ```

The stored address of a market place contract associated with this contract

### Returns

web3 callable, opts

**Method `min_feenominator`**

> ```
> def min_feenominator(
>     self,
>     opts=None
> )
> ```

The stored constant representing the minimum value for any fee denominator

### Returns

web3 callable, opts

**Method `name`**

> ```
> def name(
>     self,
>     opts=None
> )
> ```

The stored name constant for this contract

### Returns

web3 callable, opts

**Method `redeem_vault_interest`**

> ```
> def redeem_vault_interest(
>     self,
>     u,
>     m,
>     opts=None
> )
> ```

Allows vault owners to redeem any currently accrued interest

### Parameters

u (string) Address of the underlying token

m (int) Maturity timestamp of the market

opts (dict) Optional tx opts

### Returns

web3 transactable, opts

**Method `redeem_zc_token`**

> ```
> def redeem_zc_token(
>     self,
>     u,
>     m,
>     a,
>     opts=None
> )
> ```

Allows zctoken holders to redeem their tokens for underlying tokens after maturity has been reached

### Parameters

u (string) Address of the underlying token

m (int) Maturity timestamp of the market

a (int) Amount of zctokens being redeemed&#x20;

opts (dict) Optional tx opts

### Returns

web3 transactable, opts

**Method `split_underlying`**

> ```
> def split_underlying(
>     self,
>     u,
>     m,
>     a,
>     opts=None
> )
> ```

Allows users to deposit underlying and in the process split it into/mint zcTokens and vault notional

### Parameters

u (string) Address of the underlying token

m (int) Maturity timestamp of the market

a (int) Amount of underlying being deposited

opts (dict) Optional tx opts

### Returns

web3 transactable, opts

**Method `transfer_admin`**

> ```
> def transfer_admin(
>     self,
>     a,
>     opts=None
> )
> ```

Allows the current admin to transfer the title to another party

### Description

Note that this method is only callable by the admin

### Parameters

a (address) Address of the new admin

### Returns

web3 transactable, opts

**Method `version`**

> ```
> def version(
>     self,
>     opts=None
> )
> ```

The stored version constant for this contract

### Returns

web3 callable, opts


# swivel.abstracts.vault\_tracker

### Classes

#### Class `VaultTracker` <a href="#id" id="id"></a>

> ```
> class VaultTracker
> ```

Persists and curates Vault objects associated with users

Note that a Vault is a Dict object in this form:

```
{ notional, redeemable, exchangerate }

```

**Ancestors**

* [swivel.abstracts.deployed.Deployed](#id-13)

**Descendants**

* [swivel.contracts.vault\_tracker.VaultTracker](#id-19)

**Methods**

**Method `admin`**

> ```
> def admin(
>     self,
>     opts=None
> )
> ```

The stored admin address for this contract

Note that this should always be the MarketPlace address

### Returns

web3 callable, opts

**Method `balances_of`**

> ```
> def balances_of(
>     self,
>     o,
>     opts=None
> )
> ```

Get Vault balances for a given user

### Parameters

o (string) Address of the vault owner

### Returns

web3 callable, opts

**Method `c_token_address`**

> ```
> def c_token_address(
>     self,
>     opts=None
> )
> ```

Adress of the compound token referenced by this vault tracker

### Returns

web3 callable, opts

**Method `maturity`**

> ```
> def maturity(
>     self,
>     opts=None
> )
> ```

An Epoch (in seconds) representing the time of maturity

### Returns

web3 callable, opts

**Method `maturity_rate`**

> ```
> def maturity_rate(
>     self,
>     opts=None
> )
> ```

The maturity rate (TODO: better description)

### Returns

web3 callable, opts

**Method `swivel`**

> ```
> def swivel(
>     self,
>     opts=None
> )
> ```

Address of the associated Swivel contract deployment

### Returns

web3 callable, opts

**Method `vaults`**

> ```
> def vaults(
>     self,
>     o,
>     opts=None
> )
> ```

Get a Vault for a given address

### Parameters

o (string) Address of the vault owner

### Returns

web3 callable, opts


# swivel.contracts

### Sub-modules

* swivel.contracts.market\_place
* swivel.contracts.swivel
* swivel.contracts.vault\_tracker


# swivel.contracts.market\_place

### Classes

#### Class `MarketPlace` <a href="#id" id="id"></a>

> ```
> class MarketPlace(
>     v
> )
> ```

Helper class that provides a standard way to create an ABC using inheritance.

### Parameters

v (W3) Instance of a vendor W3 class (no other vendors are supported as of now)

**Ancestors**

* swivel.abstracts.market\_place.MarketPlace
* swivel.abstracts.deployed.Deployed


# swivel.contracts.swivel

### Classes

#### Class `Swivel` <a href="#id" id="id"></a>

> ```
> class Swivel(
>     v
> )
> ```

Helper class that provides a standard way to create an ABC using inheritance.

### Parameters

v (W3) Instance of a vendor W3 class (no other vendors are supported as of now)

**Ancestors**

* swivel.abstracts.swivel.Swivel
* swivel.abstracts.deployed.Deployed


# swivel.contracts.vault\_tracker

### Classes

#### Class `VaultTracker` <a href="#id" id="id"></a>

> ```
> class VaultTracker(
>     v
> )
> ```

Persists and curates Vault objects associated with users

Note that a Vault is a Dict object in this form:

```
{ notional, redeemable, exchangerate }
```

### Parameters

v (W3) Instance of a vendor W3 class (no other vendors are supported as of now)

**Ancestors**

* [swivel.abstracts.vault\_tracker.VaultTracker](#id-16)
* [swivel.abstracts.deployed.Deployed](#id-13)


# swivel.vendors

### Sub-modules

* swivel.vendors.signer
* swivel.vendors.w3


# swivel.vendors.signer

### Classes

#### Class `Signer` <a href="#id" id="id"></a>

> ```
> class Signer
> ```

**Methods**

**Method `prepare_data`**

> ```
> def prepare_data(
>     self
> )
> ```

Get the initial EIP712 compliant data dictionary to sign

**Method `prepare_domain`**

> ```
> def prepare_domain(
>     self,
>     d,
>     i,
>     a
> )
> ```

Update the data dictionary with the 'domain' entry

**Method `prepare_message`**

> ```
> def prepare_message(
>     self,
>     d,
>     o
> )
> ```

Update the data dictionary with the 'message' entry (Order)

**Method `sign_order`**

> ```
> def sign_order(
>     self,
>     o,
>     i,
>     a,
>     k
> )
> ```

Sign an order, producing an EIP712 compliant signature

### Parameters

o (dict) Swivel Order object

i (int) ChainId

a (string) Address of the deployed verifying contract

k (bytes) Private key as bytes

### Returns

The signature hex with 0x prefix normalized


# swivel.vendors.w3

### Classes

#### Class `W3` <a href="#id" id="id"></a>

> ```
> class W3(
>     p,
>     a=None
> )
> ```

### Parameters

p (Web3.Provider) Provider being used to connect

a (address) An optional default account to use. Will default to .eth.accounts\[0] if omitted

**Methods**

**Method `build_transaction`**

> ```
> def build_transaction(
>     self,
>     a
> )
> ```

Return a suitable transaction object for signing

### Description

As per our pattern a\[1] is the tx\_opts dict. Note that you should include, at least, 'chainId' in that dict. Other optional properties are available, see <https://web3py.readthedocs.io/en/latest/web3.eth.account.html#sign-a-transaction.>

* 'maxFeePerGas'
* 'maxPriorityFeePerGas'
* etc...

**Method `contract`**

> ```
> def contract(
>     self,
>     address,
>     abi
> )
> ```

Get an instance of the vedor low-level contract object

### Parameters

address (address) The address of the deployed smart contract

abi (string) ABI of the deployed smart contract

### Returns

the vendor specific contract object

**Method `estimate_gas`**

> ```
> def estimate_gas(
>     self,
>     a
> )
> ```

Return an estimate of gas to be used in a transaction, as well as the price of the gas

### Parameters

a (tuple) Length 2 tuple whose values are a web3 transactable object and a tx\_opts dict. This is the common return of all Swivel.py H.O.C contract methods.

### Returns

gas, gas\_price

**Method `send`**

> ```
> def send(
>     self,
>     a
> )
> ```

Convenience method which builds, signs and broadcasts a transaction

**Method `send_raw_transaction`**

> ```
> def send_raw_transaction(
>     self,
>     t
> )
> ```

Given a raw signed transaction, broadcast it

### Parameters

t (transaction) A web3 transaction which has been signed

### Returns

A transaction hash suitable for web3's ...wait\_for\_transaction\_receipt method

**Method `sign_order`**

> ```
> def sign_order(
>     self,
>     o,
>     i,
>     a
> )
> ```

Sign an order, producing an EIP712 compliant signature

### Parameters

o (dict) Swivel Order object

i (int) ChainId

a (string) Address of the deployed verifying contract

### Returns

The signature hex

**Method `sign_transaction`**

> ```
> def sign_transaction(
>     self,
>     t
> )
> ```

Called after a transaction has been built with `build_transaction`

### Parameters

t (dict) A built transaction object from build\_transaction

### Returns

A signed transaction

***

Generated by *pdoc* 0.10.0 (<https://pdoc3.github.io>).


# Scrivel (Python Examples)

Scripting the Swivel Finance Protocol with Python

#### PSA

We suggest you create a virtual environment for this and every python project.&#x20;

**Install/ensure compatable python version**

This is a python project, i'm just going to assume you have a python available. If not, do that first. Scrivel expects at least a Python version of 3.7.3

**Assure you have pip available**

`which pip`. Depending on your system it may be aliased with ...3 so, `which pip3`. If not present install it.

**With virtualenv**

Once you have pip available use `pip install --upgrade virtualenv` (sudo it if you must...).

Now you are free to place the virtual environment for this project anywhere you want. This author uses a `~/python/` top level directory to house all virtualenvs (which this author makes for each python project).

```
virtualenv -p python3 ~/python/scrivel
```

With the env made, source it.

```
source ~/python/scrivel/bin/activate
```

Now you can move to installing things...

### installation

Clone the [repo](https://github.com/Swivel-Finance/scrivel), cd into the rood dir, (activate your virtual env if you have not) then

```
pip install -r requirements.txt
```

#### before you run the examples

Each of the files in `/scrivel/examples` needs its `shebang` modified to point to the python executable you created with virtualenv. For example if you followed the path above

```
#!/home/<your_user_name>/python/scrivel/bin/python
```

If not, just make it match wherever you put it.

#### private key

If you are performing transactions via the Swivel.py Vendor a private key is expected to be available in the shell environment as `PRIVATE_KEY`. This will be used to sign offline, your private key is never exposed or broadcast in any way.

**Constants**

You'll need to modify the constants located in `/scrivel/constants/__init__.py`:

* HTTP\_PROVIDER: (string) A suitable URL for a Web3.py HTTP Provider
* WS\_PROVIDER: (string) A suitable URL for a Web3.py WSS Provider
* PUB\_KEY: (string) Your public key you wish to use
* MARKET\_PLACE\_ADDRESS: (string) The address of the deployed MarketPlace smart contract you want to interct with
* SWIVEL\_ADDRESS: (string) The address of the deployed Swivel smart contract you want to interct with
* DAI\_UNDERLYING: (string) Address for the underlying token of an active DAI market
* DAI\_MATURITY: (int) Maturity timestap (unix epoch in seconds) for the above active DAI market
* VAULT\_ADDRESS: (string) Address of the vault associated with the above active DAI market

**note on the above DAI market**

As an example, you could use the addresses from the currently deployed contracts on Rinkeby:

```
DAI_UNDERLYING = '0x5592EC0cfb4dbc12D3aB100b257153436a1f0FEa'
DAI_MATURITY = 1669957199
VAULT_ADDRESS = '0xaEC3322CE4092a45b3B1B999c79B9F780E057BA5'
```

This is just one example market, it could, of course, be any other active market. USDC, etc... Feel free to make any constants you want for others obviously.

### run the examples

The example files can then be run by (assuming you are in the [repo](https://github.com/Swivel-Finance/scrivel) root dir)

```
python scrivel/examples/<foo>_<bar>.py
```

## todo

Profit.


# Contracts Overview

Swivel protocol smart contracts, their deployed addresses and annotated source code

## Contract Addresses:

### Mainnet:

**Swivel.sol:** 0x3b983B701406010866bD68331aAed374fb9f50C9

**Marketplace.sol:** 0x998689650D4d55822b4bDd4B7DB5F596bf6b3570

### Rinkeby:

**Swivel.sol:** 0x4ccD4C002216f08218EdE1B13621faa80CecfC98

**Marketplace.sol:** 0x9fa54f942D8b8e992501952C3e6E67F1A42595b8

## Mainnet zcTokens & nToken Vaults:

### zcUSDC

zcUSDC is a standard ERC-20 token, and there is a different zcUSDC for each maturity:

**zcUSDC-March:** 0x4bfbc830f0c3b6f1343efd8b36f31ff4d0028b56 \
Etherscan: <https://etherscan.io/token/0x4bfbc830f0c3b6f1343efd8b36f31ff4d0028b56>

**zcUSDC-June:** 0xab53b4dbab4a51ee866957726bae19efe28b5e5b\
Etherscan: <https://etherscan.io/token/0xab53b4dbab4a51ee866957726bae19efe28b5e5b>

### nUSDC Vaults

nUSDC is a non-standard erc and each `Vault` contract tracks not only a user's nUSDC balance, but their interest generated as well.

**nUSDC Vault-March:** 0xCAcF039F0BB37f3B37394db2Dc3Ae41c97Fa6594

**nUSDC Vault-June:** 0x3fA738e85cCF9702185fe43f5CdC7c4EcCA2eF7F

​


# Contracts

## Contract Overview:

<table data-header-hidden><thead><tr><th width="150">Contracts</th><th width="150">Docs</th><th width="150">Link</th><th width="150">LIBS</th><th>External</th></tr></thead><tbody><tr><td><strong>Contracts</strong></td><td>Docs</td><td><strong>Link</strong></td><td><strong>LIBS</strong></td><td><strong>External</strong></td></tr><tr><td>Swivel</td><td><a href="/pages/aiaGyUNlFUopbKuo7PFX">Docs</a></td><td><a href="https://github.com/Swivel-Finance/swivel/blob/main/contracts/v2/swivel/Swivel.sol">Link</a></td><td><a href="https://github.com/Swivel-Finance/swivel/blob/main/contracts/v2/swivel/Interfaces.sol">Interfaces.sol</a>, <a href="https://github.com/Swivel-Finance/swivel/blob/main/contracts/v2/swivel/Hash.sol">Hash.sol</a>, <a href="https://github.com/Swivel-Finance/swivel/blob/main/contracts/v2/swivel/Sig.sol">Sig.sol</a></td><td><a href="https://github.com/compound-finance/compound-protocol/blob/master/contracts/CToken.sol">CToken.sol</a></td></tr><tr><td>Marketplace</td><td><a href="/pages/jjWXZIEnk0w0e8iDLSrC">Docs</a></td><td><a href="https://github.com/Swivel-Finance/swivel/blob/main/contracts/v2/marketplace/MarketPlace.sol">Link</a></td><td><a href="https://github.com/Swivel-Finance/swivel/blob/main/contracts/v2/marketplace/Interfaces.sol">Interfaces.sol</a></td><td></td></tr><tr><td>VaultTracker</td><td><a href="/pages/givxAuGS8CloHSQlht11">Docs</a></td><td><a href="https://github.com/Swivel-Finance/swivel/blob/main/contracts/v2/marketplace/VaultTracker.sol">Link</a></td><td><a href="https://github.com/Swivel-Finance/swivel/blob/main/contracts/v2/marketplace/Interfaces.sol">Interfaces.sol</a></td><td><a href="https://github.com/compound-finance/compound-protocol/blob/master/contracts/CToken.sol">CToken.sol</a></td></tr></tbody></table>

## Contract Addresses:

### Mainnet:

**Swivel.sol:** 0x093e4D20D9b2c3c8f68E8a20262D8Fb8EBCE08FA

**Marketplace.sol:** 0x76A3F123c651CbE62c80dB5FE2539fb755DAfDCe

### Rinkeby:

**Swivel.sol:** 0x4ccD4C002216f08218EdE1B13621faa80CecfC98

**Marketplace.sol:** 0x9fa54f942D8b8e992501952C3e6E67F1A42595b8


# Swivel

Annotated source of the Swivel.sol smart contract

## constructor

```solidity
  function constructor(
    address m
  ) public
```

### Parameters:

| Name | Type    | Description                           |
| ---- | ------- | ------------------------------------- |
| `m`  | address | deployed MarketPlace contract address |

## initiate

```solidity
  function initiate(
    struct Hash.Order[] o,
    uint256[] a,
    struct Sig.Components[] c
  ) external returns (bool)
```

Allows a user to initiate a position

### Parameters:

| Name | Type                     | Description                                                         |
| ---- | ------------------------ | ------------------------------------------------------------------- |
| `o`  | struct Hash.Order\[]     | Array of offline Swivel.Orders                                      |
| `a`  | uint256\[]               | Array of order volume (principal) amounts relative to passed orders |
| `c`  | struct Sig.Components\[] | Array of Components from valid ECDSA signatures                     |

## initiateVaultFillingZcTokenInitiate

```solidity
  function initiateVaultFillingZcTokenInitiate(
    struct Hash.Order o,
    uint256 a,
    struct Sig.Components c
  ) internal
```

Allows a user to initiate a Vault by filling an offline zcToken initiate order

This method should pass (underlying, maturity, maker, sender, principalFilled) to MarketPlace.custodialInitiate

### Parameters:

| Name | Type                  | Description                                                     |
| ---- | --------------------- | --------------------------------------------------------------- |
| `o`  | struct Hash.Order     | Order being filled                                              |
| `a`  | uint256               | Amount of volume (premium) being filled by the taker's initiate |
| `c`  | struct Sig.Components | Components of a valid ECDSA signature                           |

## initiateZcTokenFillingVaultInitiate

```solidity
  function initiateZcTokenFillingVaultInitiate(
    struct Hash.Order o,
    uint256 a,
    struct Sig.Components c
  ) internal
```

Allows a user to initiate a zcToken by filling an offline vault initiate order

This method should pass (underlying, maturity, sender, maker, a) to MarketPlace.custodialInitiate

### Parameters:

| Name | Type                  | Description                                                       |
| ---- | --------------------- | ----------------------------------------------------------------- |
| `o`  | struct Hash.Order     | Order being filled                                                |
| `a`  | uint256               | Amount of volume (principal) being filled by the taker's initiate |
| `c`  | struct Sig.Components | Components of a valid ECDSA signature                             |

## initiateZcTokenFillingZcTokenExit

```solidity
  function initiateZcTokenFillingZcTokenExit(
    struct Hash.Order o,
    uint256 a,
    struct Sig.Components c
  ) internal
```

Allows a user to initiate zcToken? by filling an offline zcToken exit order

This method should pass (underlying, maturity, maker, sender, a) to MarketPlace.p2pZcTokenExchange

### Parameters:

| Name | Type                  | Description                                                       |
| ---- | --------------------- | ----------------------------------------------------------------- |
| `o`  | struct Hash.Order     | Order being filled                                                |
| `a`  | uint256               | Amount of volume (principal) being filled by the taker's initiate |
| `c`  | struct Sig.Components | Components of a valid ECDSA signature                             |

## initiateVaultFillingVaultExit

```solidity
  function initiateVaultFillingVaultExit(
    struct Hash.Order o,
    uint256 a,
    struct Sig.Components c
  ) internal
```

Allows a user to initiate a Vault by filling an offline vault exit order

This method should pass (underlying, maturity, maker, sender, principalFilled) to MarketPlace.p2pVaultExchange

### Parameters:

| Name | Type                  | Description                                                  |
| ---- | --------------------- | ------------------------------------------------------------ |
| `o`  | struct Hash.Order     | Order being filled                                           |
| `a`  | uint256               | Amount of volume (interest) being filled by the taker's exit |
| `c`  | struct Sig.Components | Components of a valid ECDSA signature                        |

## exit

```solidity
  function exit(
    struct Hash.Order[] o,
    uint256[] a,
    struct Sig.Components[] c
  ) external returns (bool)
```

Allows a user to exit (sell) a currently held position to the marketplace.

### Parameters:

| Name | Type                     | Description                                                         |
| ---- | ------------------------ | ------------------------------------------------------------------- |
| `o`  | struct Hash.Order\[]     | Array of offline Swivel.Orders                                      |
| `a`  | uint256\[]               | Array of order volume (principal) amounts relative to passed orders |
| `c`  | struct Sig.Components\[] | Components of a valid ECDSA signature                               |

## exitZcTokenFillingZcTokenInitiate

```solidity
  function exitZcTokenFillingZcTokenInitiate(
    struct Hash.Order o,
    uint256 a,
    struct Sig.Components c
  ) internal
```

Allows a user to exit their zcTokens by filling an offline zcToken initiate order

This method should pass (underlying, maturity, sender, maker, principalFilled) to MarketPlace.p2pZcTokenExchange

### Parameters:

| Name | Type                  | Description                                                  |
| ---- | --------------------- | ------------------------------------------------------------ |
| `o`  | struct Hash.Order     | Order being filled                                           |
| `a`  | uint256               | Amount of volume (interest) being filled by the taker's exit |
| `c`  | struct Sig.Components | Components of a valid ECDSA signature                        |

## exitVaultFillingVaultInitiate

```solidity
  function exitVaultFillingVaultInitiate(
    struct Hash.Order o,
    uint256 a,
    struct Sig.Components c
  ) internal
```

Allows a user to exit their Vault by filling an offline vault initiate order

This method should pass (underlying, maturity, sender, maker, a) to MarketPlace.p2pVaultExchange

### Parameters:

| Name | Type                  | Description                                                   |
| ---- | --------------------- | ------------------------------------------------------------- |
| `o`  | struct Hash.Order     | Order being filled                                            |
| `a`  | uint256               | Amount of volume (principal) being filled by the taker's exit |
| `c`  | struct Sig.Components | Components of a valid ECDSA signature                         |

## exitVaultFillingZcTokenExit

```solidity
  function exitVaultFillingZcTokenExit(
    struct Hash.Order o,
    uint256 a,
    struct Sig.Components c
  ) internal
```

Allows a user to exit their Vault filling an offline zcToken exit order

This method should pass (underlying, maturity, maker, sender, a) to MarketPlace.exitFillingExit

### Parameters:

| Name | Type                  | Description                                                   |
| ---- | --------------------- | ------------------------------------------------------------- |
| `o`  | struct Hash.Order     | Order being filled                                            |
| `a`  | uint256               | Amount of volume (principal) being filled by the taker's exit |
| `c`  | struct Sig.Components | Components of a valid ECDSA signature                         |

## exitZcTokenFillingVaultExit

```solidity
  function exitZcTokenFillingVaultExit(
    struct Hash.Order o,
    uint256 a,
    struct Sig.Components c
  ) internal
```

Allows a user to exit their zcTokens by filling an offline vault exit order

This method should pass (underlying, maturity, sender, maker, principalFilled) to MarketPlace.exitFillingExit

### Parameters:

| Name | Type                  | Description                                                  |
| ---- | --------------------- | ------------------------------------------------------------ |
| `o`  | struct Hash.Order     | Order being filled                                           |
| `a`  | uint256               | Amount of volume (interest) being filled by the taker's exit |
| `c`  | struct Sig.Components | Components of a valid ECDSA signature                        |

## cancel

```solidity
  function cancel(
    struct Hash.Order o,
    struct Sig.Components c
  ) external returns (bool)
```

Allows a user to cancel an order, preventing it from being filled in the future

### Parameters:

| Name | Type                  | Description                           |
| ---- | --------------------- | ------------------------------------- |
| `o`  | struct Hash.Order     | Order being cancelled                 |
| `c`  | struct Sig.Components | Components of a valid ECDSA signature |

## transferAdmin

```solidity
  function transferAdmin(
    address a
  ) external returns (bool)
```

### Parameters:

| Name | Type    | Description            |
| ---- | ------- | ---------------------- |
| `a`  | address | Address of a new admin |

## scheduleWithdrawal

```solidity
  function scheduleWithdrawal(
    address e
  ) external returns (bool)
```

Allows the admin to schedule the withdrawal of tokens

### Parameters:

| Name | Type    | Description                          |
| ---- | ------- | ------------------------------------ |
| `e`  | address | Address of (erc20) token to withdraw |

## blockWithdrawal

```solidity
  function blockWithdrawal(
    address e
  ) external returns (bool)
```

Emergency function to block unplanned withdrawals

### Parameters:

| Name | Type    | Description                          |
| ---- | ------- | ------------------------------------ |
| `e`  | address | Address of token withdrawal to block |

## withdraw

```solidity
  function withdraw(
    address e
  ) external returns (bool)
```

Allows the admin to withdraw the given token, provided the holding period has been observed

### Parameters:

| Name | Type    | Description                  |
| ---- | ------- | ---------------------------- |
| `e`  | address | Address of token to withdraw |

## setFee

```solidity
  function setFee(
    uint16 i,
    uint16 d
  ) external returns (bool)
```

Allows the admin to set a new fee denominator

### Parameters:

| Name | Type   | Description                          |
| ---- | ------ | ------------------------------------ |
| `i`  | uint16 | The index of the new fee denominator |
| `d`  | uint16 | The new fee denominator              |

## approveUnderlying

```solidity
  function approveUnderlying(
    address[] u,
    address[] c
  ) external returns (bool)
```

Allows the admin to bulk approve given compound addresses at the underlying token, saving marginal approvals

### Parameters:

| Name | Type       | Description                         |
| ---- | ---------- | ----------------------------------- |
| `u`  | address\[] | array of underlying token addresses |
| `c`  | address\[] | array of compound token addresses   |

## splitUnderlying

```solidity
  function splitUnderlying(
    address u,
    uint256 m,
    uint256 a
  ) external returns (bool)
```

Allows users to deposit underlying and in the process split it into/mint zcTokens and vault notional. Calls mPlace.mintZcTokenAddingNotional

### Parameters:

| Name | Type    | Description                                         |
| ---- | ------- | --------------------------------------------------- |
| `u`  | address | Underlying token address associated with the market |
| `m`  | uint256 | Maturity timestamp of the market                    |
| `a`  | uint256 | Amount of underlying being deposited                |

## combineTokens

```solidity
  function combineTokens(
    address u,
    uint256 m,
    uint256 a
  ) external returns (bool)
```

Allows users deposit/burn 1-1 amounts of both zcTokens and vault notional, in the process "combining" the two, and redeeming underlying. Calls mPlace.burnZcTokenRemovingNotional.

### Parameters:

| Name | Type    | Description                                         |
| ---- | ------- | --------------------------------------------------- |
| `u`  | address | Underlying token address associated with the market |
| `m`  | uint256 | Maturity timestamp of the market                    |
| `a`  | uint256 | Amount of zcTokens being redeemed                   |

## redeemZcToken

```solidity
  function redeemZcToken(
    address u,
    uint256 m,
    uint256 a
  ) external returns (bool)
```

Allows zcToken holders to redeem their tokens for underlying tokens after maturity has been reached (via MarketPlace).

### Parameters:

| Name | Type    | Description                                         |
| ---- | ------- | --------------------------------------------------- |
| `u`  | address | Underlying token address associated with the market |
| `m`  | uint256 | Maturity timestamp of the market                    |
| `a`  | uint256 | Amount of zcTokens being redeemed                   |

## redeemVaultInterest

```solidity
  function redeemVaultInterest(
    address u,
    uint256 m
  ) external returns (bool)
```

Allows Vault owners to redeem any currently accrued interest (via MarketPlace)

### Parameters:

| Name | Type    | Description                                         |
| ---- | ------- | --------------------------------------------------- |
| `u`  | address | Underlying token address associated with the market |
| `m`  | uint256 | Maturity timestamp of the market                    |

## validOrderHash

```solidity
  function validOrderHash(
    struct Hash.Order o,
    struct Sig.Components c
  ) internal returns (bytes32)
```

Varifies the validity of an order and it's signature.

### Parameters:

| Name | Type                  | Description                           |
| ---- | --------------------- | ------------------------------------- |
| `o`  | struct Hash.Order     | An offline Swivel.Order               |
| `c`  | struct Sig.Components | Components of a valid ECDSA signature |

### Return Values:

| Name                          | Type              | Description   |
| ----------------------------- | ----------------- | ------------- |
| `the`                         | struct Hash.Order | hashed order. |
| ## Events                     |                   |               |
| ### Cancel                    |                   |               |
| \`\`\`solidity                |                   |               |
| event Cancel(                 |                   |               |
| )                             |                   |               |
| \`\`\`                        |                   |               |
| Emitted on order cancellation |                   |               |

## Initiate

```solidity
  event Initiate(
  )
```

Emitted on any initiate\*

filled is 'principalFilled' when (vault:false, exit:false) && (vault:true, exit:true) filled is 'premiumFilled' when (vault:true, exit:false) && (vault:false, exit:true)

## Exit

```solidity
  event Exit(
  )
```

Emitted on any exit\*

filled is 'principalFilled' when (vault:false, exit:false) && (vault:true, exit:true) filled is 'premiumFilled' when (vault:true, exit:false) && (vault:false, exit:true)

## ScheduleWithdrawal

```solidity
  event ScheduleWithdrawal(
  )
```

Emitted on token withdrawal scheduling

## BlockWithdrawal

```solidity
  event BlockWithdrawal(
  )
```

Emitted on token withdrawal blocking

## SetFee

```solidity
  event SetFee(
  )
```

Emitted on a change to the feenominators array


# MarketPlace

Annotated source code of the MarketPlace.sol smart contract

### Functions

#### setSwivelAddress

```solidity
  function setSwivelAddress(
    address s
  ) external returns (bool)
```

We only allow this to be set once

**Parameters:**

| Name | Type    | Description                             |
| ---- | ------- | --------------------------------------- |
| `s`  | address | Address of the deployed swivel contract |

#### transferAdmin

```solidity
  function transferAdmin(
    address a
  ) external returns (bool)
```

**Parameters:**

| Name | Type    | Description            |
| ---- | ------- | ---------------------- |
| `a`  | address | Address of a new admin |

#### createMarket

```solidity
  function createMarket(
    uint256 m,
    address c,
    string n,
    string s
  ) external returns (bool)
```

Allows the owner to create new markets

**Parameters:**

| Name | Type    | Description                                                  |
| ---- | ------- | ------------------------------------------------------------ |
| `m`  | uint256 | Maturity timestamp of the new market                         |
| `c`  | address | cToken address associated with underlying for the new market |
| `n`  | string  | Name of the new zcToken market                               |
| `s`  | string  | Symbol of the new zcToken market                             |

#### matureMarket

```solidity
  function matureMarket(
    address u,
    uint256 m
  ) public returns (bool)
```

Can be called after maturity, allowing all of the zcTokens to earn floating interest on Compound until they release their funds

**Parameters:**

| Name | Type    | Description                                         |
| ---- | ------- | --------------------------------------------------- |
| `u`  | address | Underlying token address associated with the market |
| `m`  | uint256 | Maturity timestamp of the market                    |

#### mintZcTokenAddingNotional

```solidity
  function mintZcTokenAddingNotional(
    address u,
    uint256 m,
    address t,
    uint256 a
  ) external returns (bool)
```

Allows Swivel caller to deposit their underlying, in the process splitting it - minting both zcTokens and vault notional.

**Parameters:**

| Name | Type    | Description                                         |
| ---- | ------- | --------------------------------------------------- |
| `u`  | address | Underlying token address associated with the market |
| `m`  | uint256 | Maturity timestamp of the market                    |
| `t`  | address | Address of the depositing user                      |
| `a`  | uint256 | Amount of notional being added                      |

#### burnZcTokenRemovingNotional

```solidity
  function burnZcTokenRemovingNotional(
    address u,
    uint256 m,
    address t,
    uint256 a
  ) external returns (bool)
```

Allows Swivel caller to deposit/burn both zcTokens + vault notional. This process is "combining" the two and redeeming underlying.

**Parameters:**

| Name | Type    | Description                                         |
| ---- | ------- | --------------------------------------------------- |
| `u`  | address | Underlying token address associated with the market |
| `m`  | uint256 | Maturity timestamp of the market                    |
| `t`  | address | Address of the combining/redeeming user             |
| `a`  | uint256 | Amount of zcTokens being burned                     |

#### redeemZcToken

```solidity
  function redeemZcToken(
    address u,
    uint256 m,
    address t,
    uint256 a
  ) external returns (uint256)
```

Allows (via swivel) zcToken holders to redeem their tokens for underlying tokens after maturity has been reached.

**Parameters:**

| Name | Type    | Description                                         |
| ---- | ------- | --------------------------------------------------- |
| `u`  | address | Underlying token address associated with the market |
| `m`  | uint256 | Maturity timestamp of the market                    |
| `t`  | address | Address of the redeeming user                       |
| `a`  | uint256 | Amount of zcTokens being redeemed                   |

#### redeemVaultInterest

```solidity
  function redeemVaultInterest(
    address u,
    uint256 m,
    address t
  ) external returns (uint256)
```

Allows Vault owners (via Swivel) to redeem any currently accrued interest

**Parameters:**

| Name | Type    | Description                                         |
| ---- | ------- | --------------------------------------------------- |
| `u`  | address | Underlying token address associated with the market |
| `m`  | uint256 | Maturity timestamp of the market                    |
| `t`  | address | Address of the redeeming user                       |

#### calculateReturn

```solidity
  function calculateReturn(
    address u,
    uint256 m,
    uint256 a
  ) internal returns (uint256)
```

Calculates the total amount of underlying returned including interest generated since the `matureMarket` function has been called

**Parameters:**

| Name | Type    | Description                                         |
| ---- | ------- | --------------------------------------------------- |
| `u`  | address | Underlying token address associated with the market |
| `m`  | uint256 | Maturity timestamp of the market                    |
| `a`  | uint256 | Amount of zcTokens being redeemed                   |

#### cTokenAddress

```solidity
  function cTokenAddress(
    address u,
    uint256 m
  ) external returns (address)
```

Return the ctoken address for a given market

**Parameters:**

| Name | Type    | Description                                         |
| ---- | ------- | --------------------------------------------------- |
| `u`  | address | Underlying token address associated with the market |
| `m`  | uint256 | Maturity timestamp of the market                    |

#### custodialInitiate

```solidity
  function custodialInitiate(
    address u,
    uint256 m,
    address z,
    address n,
    uint256 a
  ) external returns (bool)
```

Called by swivel IVFZI && IZFVI

Call with underlying, maturity, mint-target, add-notional-target and an amount

**Parameters:**

| Name | Type    | Description                                         |
| ---- | ------- | --------------------------------------------------- |
| `u`  | address | Underlying token address associated with the market |
| `m`  | uint256 | Maturity timestamp of the market                    |
| `z`  | address | Recipient of the minted zcToken                     |
| `n`  | address | Recipient of the added notional                     |
| `a`  | uint256 | Amount of zcToken minted and notional added         |

#### custodialExit

```solidity
  function custodialExit(
    address u,
    uint256 m,
    address z,
    address n,
    uint256 a
  ) external returns (bool)
```

Called by swivel EVFZE FF EZFVE

Call with underlying, maturity, burn-target, remove-notional-target and an amount

**Parameters:**

| Name | Type    | Description                                         |
| ---- | ------- | --------------------------------------------------- |
| `u`  | address | Underlying token address associated with the market |
| `m`  | uint256 | Maturity timestamp of the market                    |
| `z`  | address | Owner of the zcToken to be burned                   |
| `n`  | address | Target to remove notional from                      |
| `a`  | uint256 | Amount of zcToken burned and notional removed       |

#### p2pZcTokenExchange

```solidity
  function p2pZcTokenExchange(
    address u,
    uint256 m,
    address f,
    address t,
    uint256 a
  ) external returns (bool)
```

Called by swivel IZFZE, EZFZI

Call with underlying, maturity, transfer-from, transfer-to, amount

**Parameters:**

| Name | Type    | Description                                         |
| ---- | ------- | --------------------------------------------------- |
| `u`  | address | Underlying token address associated with the market |
| `m`  | uint256 | Maturity timestamp of the market                    |
| `f`  | address | Owner of the zcToken to be burned                   |
| `t`  | address | Target to be minted to                              |
| `a`  | uint256 | Amount of zcToken transfer                          |

#### p2pVaultExchange

```solidity
  function p2pVaultExchange(
    address u,
    uint256 m,
    address f,
    address t,
    uint256 a
  ) external returns (bool)
```

Called by swivel IVFVE, EVFVI

Call with underlying, maturity, remove-from, add-to, amount

**Parameters:**

| Name | Type    | Description                                         |
| ---- | ------- | --------------------------------------------------- |
| `u`  | address | Underlying token address associated with the market |
| `m`  | uint256 | Maturity timestamp of the market                    |
| `f`  | address | Owner of the notional to be transferred             |
| `t`  | address | Target to be transferred to                         |
| `a`  | uint256 | Amount of notional transfer                         |

#### transferVaultNotional

```solidity
  function transferVaultNotional(
    address u,
    uint256 m,
    address t,
    uint256 a
  ) external returns (bool)
```

External method giving access to this functionality within a given vault

Note that this method calculates yield and interest as well

**Parameters:**

| Name | Type    | Description                                         |
| ---- | ------- | --------------------------------------------------- |
| `u`  | address | Underlying token address associated with the market |
| `m`  | uint256 | Maturity timestamp of the market                    |
| `t`  | address | Target to be transferred to                         |
| `a`  | uint256 | Amount of notional to be transferred                |

#### transferVaultNotionalFee

```solidity
  function transferVaultNotionalFee(
    address u,
    uint256 m,
    address f,
    uint256 a
  ) external returns (bool)
```

Transfers notional fee to the Swivel contract without recalculating marginal interest for from

**Parameters:**

| Name | Type    | Description                                         |
| ---- | ------- | --------------------------------------------------- |
| `u`  | address | Underlying token address associated with the market |
| `m`  | uint256 | Maturity timestamp of the market                    |
| `f`  | address | Owner of the amount                                 |
| `a`  | uint256 | Amount to transfer                                  |

#### pause

```solidity
  function pause(
    bool b
  ) external returns (bool)
```

Called by admin at any point to pause / unpause market transactions

**Parameters:**

| Name | Type | Description                                       |
| ---- | ---- | ------------------------------------------------- |
| `b`  | bool | Boolean which indicates the markets paused status |

### Events

#### Create

```solidity
  event Create(
  )
```

#### Mature

```solidity
  event Mature(
  )
```

#### RedeemZcToken

```solidity
  event RedeemZcToken(
  )
```

#### RedeemVaultInterest

```solidity
  event RedeemVaultInterest(
  )
```

#### CustodialInitiate

```solidity
  event CustodialInitiate(
  )
```

#### CustodialExit

```solidity
  event CustodialExit(
  )
```

#### P2pZcTokenExchange

```solidity
  event P2pZcTokenExchange(
  )
```

#### P2pVaultExchange

```solidity
  event P2pVaultExchange(
  )
```

#### TransferVaultNotional

```solidity
  event TransferVaultNotional(
  )
```


# VaultTracker

Annotated source code of the VaultTracker.sol smart contract

## constructor

```solidity
  function constructor(
    uint256 m,
    address c,
    address s
  ) public
```

### Parameters:

| Name | Type    | Description                                                  |
| ---- | ------- | ------------------------------------------------------------ |
| `m`  | uint256 | Maturity timestamp of the new market                         |
| `c`  | address | cToken address associated with underlying for the new market |
| `s`  | address | address of the deployed swivel contract                      |

## addNotional

```solidity
  function addNotional(
    address o,
    uint256 a
  ) external returns (bool)
```

Adds notional to a given address

### Parameters:

| Name | Type    | Description               |
| ---- | ------- | ------------------------- |
| `o`  | address | Address that owns a vault |
| `a`  | uint256 | Amount of notional added  |

## removeNotional

```solidity
  function removeNotional(
    address o,
    uint256 a
  ) external returns (bool)
```

Removes notional from a given address

### Parameters:

| Name | Type    | Description                  |
| ---- | ------- | ---------------------------- |
| `o`  | address | Address that owns a vault    |
| `a`  | uint256 | Amount of notional to remove |

## redeemInterest

```solidity
  function redeemInterest(
    address o
  ) external returns (uint256)
```

Redeem's interest accrued by a given address

### Parameters:

| Name | Type    | Description               |
| ---- | ------- | ------------------------- |
| `o`  | address | Address that owns a vault |

## matureVault

```solidity
  function matureVault(
    uint256 c
  ) external returns (bool)
```

Matures the vault

### Parameters:

| Name | Type    | Description                      |
| ---- | ------- | -------------------------------- |
| `c`  | uint256 | The current cToken exchange rate |

## transferNotionalFrom

```solidity
  function transferNotionalFrom(
    address f,
    address t,
    uint256 a
  ) external returns (bool)
```

Transfers notional from one address to another

### Parameters:

| Name | Type    | Description             |
| ---- | ------- | ----------------------- |
| `f`  | address | Owner of the amount     |
| `t`  | address | Recipient of the amount |
| `a`  | uint256 | Amount to transfer      |

## transferNotionalFee

```solidity
  function transferNotionalFee(
    address f,
    uint256 a
  ) external returns (bool)
```

Transfers, in notional, a fee payment to the Swivel contract without recalculating marginal interest for the owner

### Parameters:

| Name | Type    | Description         |
| ---- | ------- | ------------------- |
| `f`  | address | Owner of the amount |
| `a`  | uint256 | Amount to transfer  |

## balancesOf

```solidity
  function balancesOf(
    address o
  ) external returns (uint256, uint256)
```

Returns both relevant balances for a given user's vault

### Parameters:

| Name | Type    | Description               |
| ---- | ------- | ------------------------- |
| `o`  | address | Address that owns a vault |


# Ubiquitous Language V2

### Conventions

Terms are defined within their specified contexts. If encountered in a context but not explicitly re-defined or clarified for that context, the term is assumed to have the Shared Language definition.

Ubiquitous terms that occur within other terms' definitions are indicated using title case and `Markup` formatting.


# Shared Language

These terms fulfill the same meaning across the Swivel stack, although any variation or further clarification will be noted within specific contexts.

#### Asset

A currency, token, or other tradable object. In Swivel, `asset` refers to `Underlying` currency or Tokens.

#### Underlying

The lending currency of a given `Market`, typically a `Stable Coin` or `Token`.

#### Token

An `Erc20` compatible token deployed at a given Ethereum Address. May also be referenced as *Erc20* or *uToken*.

#### nToken

Swivel's native yield-bearing token, representing the remaining yield potential of the `Underlying` for a given `Market`. For example: `nDAI`, `nUSDC`.

#### zcToken

Swivel's native principal token, representing the principal lent to a given `Market`. For example: `zcDAI`, `zcUSDC`.

#### Balance

Amount of the `Underlying` or `Token` assets a given public key owns.

#### Market

An asset-duration (underlying-duration) pairing that identifies which `Orderbook` / instrument is being used.

#### Maturity

The duration a given `Market` generates yield, up to a specified date.

#### Volume

All orders expose an amount which can be filled, wholly or partially, by an `Order`. This will be represented by either the `Principal` or `Interest`, depending on whether the order is `Amplified` (deprecated: 'floating') or `Fixed`.

#### Yield

The amount of interest an `Order` has generated, expressed in terms of a percentage.

#### Liquidity Provider

On Swivel's orderbook-based protocol, Liquidity Providers are `Market Makers`.

#### Liquidity Incentives

Swivel incentivizes liquidity by providing token rewards only to those `Liquidity Providers` who's orders are `filled`.

#### Maker

A person who provides Limit orders to the orderbook.

#### Taker

A person who executes Market Orders, filling open orderbook orders.


# UI Language

These term definitions are understood in the context of the public interface at Swivel.finance.

#### Lend

You can lend `Underlying` assets by placing a `Fixed Yield` order.

#### Order

In the Front End context, an Order is any valid `Market Order` or `Limit Order` placed on a given `Market` to lend, buy or sell `Underlying` or `Token` assets.

#### Orderbook

The table of valid, open `Orders` for a given `Market`

#### Fill

Fill orders are `Orderbook` Orders that fulfill your `Market Order` or `Limit Order` partially or in full.

#### Fixed Yield

A Fixed Yield order uses the Swivel protocol to give the user an immediate yield for lending `Underlying` assets. When a Fixed Yield order is filled, Swivel mints an equal amount of `nToken` and `zcToken` on the `Underlying`, leaving the `zcToken` in your balance and immediately selling the `nTokens` on the `Orderbook`, and returning the `Underlying` to your `Balance`.

#### Amplified Yield (deprecated: 'Floating')

An Amplified Yield order purchases `nTokens` from the marketplace and adds them to your `Balance`, where they will continue to earn a variable yield until the given `Market` matures.

#### Sell

You can sell your `nTokens` or `zcTokens` back to the `Orderbook` at any time with a Sell order.

#### Market Order

Placing an `Order` as a `Taker`, transacting at the best available price on the `Orderbook`.

#### Limit Order

Placing an `Order` as a `Maker`, transacting at a determined price for the given order type and `Market`. `Valid` unfilled `Limit Orders` appear in your Open Limit Orders view. Depending on `Order` size and `Orderbook` volume, Limit Orders may be filled partially over an undetermined amount of time.

#### Position

The current state of your balance of `Underlying` and `Token` assets, for all active `Markets` you participate in.

#### Principal

* Buy Amplified Yield -> Principal is amount of yield exposure (nToken) purchased.
* Buy Fixed Yield -> Principal is amount of Underlying lent.
* Sell nToken -> Principal is amount of nToken sold.
* Sell zcToken -> Principal is amount of zcToken sold.

#### Premium

* Buy Amplified Yield -> Premium is amount of underlying spent on yield exposure (nToken).
* Buy Fixed Yield -> Premium is amount of generated yield, expressed in underlying asset.
* Sell nToken -> Premium is the amount of generated yield, expressed in underlying asset.
* Sell zcToken -> Premium is price per underlying received when full.


# Technical Language

These term definitions are understood in the context of Swivel's technical stack. UI terms above apply when seen in technical usage, unless re-defined within this Technical context.

#### Order

An Entity, stored off chain. UI analogs: *`Order`*, *`Market Order`,* *`Limit Order`*

**Order Struct:**

* **Key** - `bytes32` Keccack hash of (wallet address,nonce,time). May also be referred to as *orderKey*.
* **Maker** - `address` Address of this Order's creator
* **Underlying** - `address` Ethereum address of a deployed Erc20 token
* **Vault** - `bool` Boolean, true if an order interacts with a vault
* **Exit** - `bool` Boolean, true if the order is an exit operation
* **Principal** - `uint256` The amount of nTokens traded.
* **Premium** - `uint256` The amount of underlying paid.
* **Maturity** - `uint256` The maturity date of the market in seconds since epoch.
* **Expiry** - `uint256` Timestamp marking this order's expiration

#### Valid

An `Order` is only valid if

* non-cancelled,
* non-expired,
* not-fully-filled
* passes signature validation
* not temporarily insolvent
* not insolvent

#### Invalid Order

An order that is

* cancelled
* filled
* expired
* temporarily insolvent
* insolvent

**Cancelled**

Only an `Order` may be cancelled. If it is, an entry into the on-chain *cancelled* mapping is stored. No `Fills` will then be accepted for this order.

**Full**

The order has been filled in its entirety.

**Temporarily Insolvent**

If a wallet's available balance is equal to an `Order`s amount, Swivel enforces a solvency check. During this intermediary period, the order will be marked as *temporarily insolvent*.

**Insolvent**

If an order is placed and the underlying assets are subsequently not available, the order is marked as insolvent.

**Expired**

An Order which has aged past its Duration. Like a cancelled Order, it may no longer be filled.

#### Event

An observable occurance that is recorded either on-chain or off-chain in Swivel's event store.

#### Message

A visible message about an `Event` that is sent from Swivel and can be listened for by a user or service.

#### Signature

As ECDSA cryptographic signature following the EIP-712 standard which we use to verify the authenticity of an `Order`. You will see the `Components` of a Signature (V, R, and S) used throughout the protocol. The Hash and Sig solidity libraries exist to service this functionality. It should be noted and enforced that `Components` are derived from a `Signature` and that the two are not equivalent. a `Signature` is a 64-bytes and its derived `Components` are a *tuple* of length 3 consisting of two 32-bytes, the canonical *R* and *S*, and a single uint *V*.

An Order's signature is considered `valid` if the extracted public key matches that of the maker.

#### EIP-712 Domain

Mentioned here as the term `Domain` has very specific Domain Driven Design implications. You may see or hear the term domain intermingled with other verbage for the EIP-712 standard such as:

* TypeHash
* Separator
* Message

Any use of these terms, specifically *domain* should be prefixed with EIP-712 to prevent language degradation and the confusion that follows it.

Implementation of Signature and Components are each tightly coupled to the EIP-712 standard.

#### Approve

Terms such as approve and approval(s) when referencing specific functionality of the `Underlying` token. Use specifiers to avoid confusion with the compound token if needed. *underlying approval* for example.

#### Transfer

Terms such as transfer, transfers and transfer from when referencing specific functionality of the `Underlying` token. As with approve, specify which token if necessary, *uToken transfer* etc...

#### Side

Indicates whether the bond is `fixed` and is lending `principal`, or is `floating` and is paying `interest`.

#### Event Store

An Ordered, Persisted, Immutable record of event data.

#### Event Sourcing

The data strategy for storing and retrieving events from the event store.

#### Messages

Messages are published with predefined meanings that are used to observe the occurance of events.

#### Deployments

The Swivel development team has a number of deploys for Production, Staging, and Development.

**Production**

The product deployment. This is used for all live user-facing deployments on any given chain or L2. e.g. `production.swivel.exchange` (updated from previous lang `mainnet.swivel.exchange`)

**Staging**

The staging deployment is a our advertised test net. Reflects promises about being a mirror of production, but without real money risk. It should be stable and function exactly like production. E.g. `staging.swivel.exchange` (updated from previous lang `rinkeby.swivel.exchange`)

**Development**

The Development deployment is a private, non-public facing Testnet version of the product. It has no promises about functionlity and will frequently break. E.g. `development.swivel.exchange`.


# Compound Language

Some terms used in the context of the Compound protocol, and how Swivel utilizes it.

### Compound Language

Some terms used in the context of the Compound protocol, and how Swivel utilizes it.

#### Compound Token

A CErc20 at an address passed to the constructor of the Swivel contract at deployment.

Pass an array of underlying token addresses + array of CERC20 addresses to create a public mapping of address -> address

#### Mint

When an agreement is initiated and after funds have been sent to the Swivel contract, cTokens are minted on the Compound protocol to generate interest.

The number of cTokens minted is calculated in terms of the underlying token consumed/transferred rather than the # of cTokens to be minted.

#### Redeem

When an agreement has completed and "Release" is called, cTokens are redeemed on the Compound protocol to return an agreement's underlying deposit as well as the interest generated over the agreement's lending term.

The number of cTokens redeemed is calculated in terms of the underlying token to be returned, rather than the # of cTokens to be consumed/transferred.

#### Exchange Rate

Exchange Rate refers to the 2e26+ uint returned from the Compound Protocol by exchangeRateCurrent().

In order to calculate the interest generated by an agreement, the current ratio of underlying:cToken is stored in each agreement upon its initiation(exchangeRateCurrent()).

Over time this ratio increases such that when "Release" is called, the difference between stored / current exchange rate can directly calculate the yield an agreement has realized.

#### CToken is Erc20

Note that all functionality of the Erc20 standard is available to the Compound Token. Use *CErc20* or *cToken* to specify.


# Finance Terms

#### Yield Strategy

An individual or organization's activity or collection of financial instruments to obtain yield, and the subject of `Rate Profile Optimization`.

#### Rate Profile Optimization

Set of activities performed by an individual or organization to obtain lower cost and/or lower risk on their borrowing/capital seeking, or higher return at acceptable levels of risk for their lending/investment.

#### Liquidity

The efficiency or ease with which an asset or security can be converted into ready cash without affecting its market price. The most liquid asset of all is cash itself.

#### Market Maker

An individual or organization that stands ready to buy and sell assets on a regular and continuous basis at a publicly quoted price.

#### Capital Efficiency

In traditional terms Capital Efficiency refers to the ratio of capital expenditures to production additions. In DeFi applications, this is considerably affected by the accumulation of gas fees required to transact on most blockchains.


# Community & Media

A collection of community and media resources.

### Community Links

Twitter: <https://twitter.com/SwivelFinance>

Discord: [https://discord.gg/swivel](https://discord.gg/xHQHQuxk)

Substack: <https://swivel.substack.com>

Telegram: None

### Media Resources

#### Banner

![](/files/-McBRjzq7HKbvHUoN9LD)

#### Logo + Wordmark 1 (SVG)

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

#### Logo 1 (SVG)

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

#### Logo + Wordmark 2 (PNG)

![](/files/-McBRvobamOiGfoQ80gE)

#### Logo 2 (PNG)

![](/files/-McBRxr8UVvbznxO89_R)

####


# Other Resources


# Institutions

A collection of resources for institutions and enterprises.


# Rate Profile Optimization

Loosely defined, rate profile optimization is the set of activities performed by an individual or organization to obtain lower cost and/or lower risk on their borrowing/capital seeking, or higher return at acceptable levels of risk for their lending/investment. The objectives of rate profile optimization may also include seeking financing for specific objectives at the lowest cost, filling a time, return or risk gap in a portfolio, reducing risk, or optimizing funding by accessing alternative sources of lower cost liquidity.


# Instruments and Participants

Over the past forty years, the market for rates instruments used to support rate profile optimization has grown to over $464 trillion (Source: [BIS, May 2020](https://stats.bis.org/statx/srs/table/d7?f=pdf) ) and spans an array of instruments including:

* Fixed for floating rate interest rate swaps (“vanilla swaps”)
* Fixed for fixed rate (eg basis swaps)
* Interest only and principal only swaps
* Overnight interest swaps
* Contracts for difference and maturity swaps
* Structured products based on underlying cash flows (eg strips, etc)
* Caps, floors, collars and other agreements limiting the extent to which market rate changes can impact a borrowing relationship

The participants in these markets include:

* Corporate treasury desks and funding desks
* Institutional investors and asset managers
* Speculators and proprietary trading functions
* Brokers and other market makers
* Liquidity management functions of banks and other large financial institutions
* Risk management functions
* Insurance companies


# Market Opportunities and Pricing

Historically the markets for interest rate swaps have been intermediated by large banks and swap dealers with AAA credit ratings. Following the credit crisis regulators have mandated the use of central counterparty execution and clearing facilities to address the risk of default of a single major institution. These markets, though large and relatively liquid, have only been available for larger institutional players. The collateral requirements and large ticket sizes (in the millions of dollars in notional for most standardized swaps) and significant fees from the banks making markets in these instruments have been barriers to entry for smaller institutions and investors seeking the benefits of hedging or speculating in rates markets.&#x20;

With the advent of smart-contract-based digital securities, the unit cost of issuing a rate optimizing security has dropped to minimal levels. The ability to generate a new contract in near real time at ticket sizes as small as a few dollars opens up the access to rate strategies to a much wider range of investors and speculators, while providing hedging tools and funding optimization to thousands who previously could not practically engage in any of these strategies.<br>

**How the instruments are priced**\
In traditional financial markets, a swap is priced based on the fluctuation in value of a given variable interest rate or rates. On the day both parties enter into a swap contract, the value of the notional principal and interest payments on both sides should be equal. A swap is then priced based on the difference between the fixed and floating rates of the underlying assets. A swap’s value shifts over time in correlation with the difference in realized value between the underlying cash flows from the two legs of the swap, and the projected difference in the rates for remaining periods.<br>


# Counterparty Risk Management

In traditional finance swap parties are exposed to the risk of default by their counterparty. Dealers will often lay off this risk by entering into corresponding deals with other participants. In the Swivel method, we isolate counterparty risk in two important ways:

1. Rather than a daily or other periodic market to market, the premium is paid up front at the outset of the contract. The principal lender either receives the premium and enters the loan, or nothing occurs. There is no exposure to repayment risk.
2. The principal is held in a time-locked vault contract which automatically returns the underlying ownership and control of the principal balance to the lender at maturity. Again, there is no exposure to repayment risk

In this simple but important innovation, Swivel removes the challenge of counterparty risk, and eliminates the complexity of daily swap valuation and movements of net payment between the parties. Unless either party needs to exit the agreement, there is no need for any activity other than at outset and maturity.<br>

### **Floating for Floating without Counterparty Risk**

Each side of the transaction generates a zero coupon token representing the future value of the floating interest payments and principal repayment, with the discounted value descending over time as the coupon payments are made and passed to the holder of the token.Two things need to be assured for the exchange to be insulated from counterparty risk:

1. The zero coupon token is associated with a corresponding binding and enforceable legal agreement obliging the issuer to exchange their interest stream for that of their counterparty, and&#x20;
2. Enforcement of the terms are guaranteed either by a trusted third-party custodian or a fail-safe vault smart contract

Assuming these conditions are met, the risk then becomes the lesser of the enforceability of the legal contract or the risk of non-compliance by the custodian or failure of the vault contract. None of these increase the direct risk between the parties.<br>


# Benefits and drawbacks of standardization

Traditional markets use a variety of conventions to standardize swaps. One convention is to standardize maturity to foot to IMM dates, in what are called MAC (market agreed coupon) swaps. Because of the standardization of settlement and payment dates, MAC swaps offer the benefit of fungibility and can be tracked as a collective, simplifying position keeping, accounting and risk management. Another method of standardization is the so-called standard par swap, where payment terms and tenors are standardized. Standard par swaps are not as standardized as MAC swaps: On any trading day, par swaps are initiated with fixed rates that may vary across all of the different par rates that prevailed at the times of the trades. Furthermore on all following days, the settlement and maturity dates of new swaps of a given tenor will change as well.

The drawbacks of standardization include large ticket sizes, which preclude smaller investors from utilizing them, as well as the fact that standardized settlement dates may not exactly match the period the investor is looking to hedge, creating periods where risk is not effectively managed. <br>


# User Needs

\
Each type of user in the rates market has different sets of objectives, but share the common goal of maximizing their return on investment at an acceptable level of risk, and/or obtaining the best possible cost for borrowing and other funding needs. If we look at the different users in the current market, we can discern a range of functional requirements for a rate optimization platform, some of which will be shared among a range of user types.

Note that this discussion is focused on the needs of these particular users to optimize their rate profile. Credit and counterparty risk management are not addressed here; the assumption is that these considerations are either minimized through the transaction mechanics (more on this later) or addressed in the pricing of the deal between the partie&#x73;**.**<br>


# Corporate Treasury and Funding

The corporate treasury user has a straightforward mandate: to seek lower interest rates on borrowing, and highest return at acceptable rates of risk on free cash. The treasury function may also seek to isolate the business functions from rate volatility and currency exposure. Treasury functions are also seeking specific maturity dates to match known funding needs, project timelines, or other cash outlays. The treasury function will seek instruments to exchange fixed for floating rates as well as floating for floating, in some cases to manage corresponding currency risk and differences in rates among different countries in which the entity operates.

The treasury may also seek hedges to minimize the volatility of debt repayment, bond obligations or other fixed outlays against borrowed capital. Further, corporate treasury functions may also have short term funding requirements met by commercial paper issues, which they may want to hedge against rate fluctuations. Depending on the scope and breadth of commercial activities, treasury functions may at times apply the full range of interest rate derivatives.<br>


# Institutional Investors and Asset Managers

Institutional investors include pensions, mutual funds, hedge funds, family offices and other enterprises investing on behalf of others. The institutional investor purchases and sells rate optimization instruments to maximize returns on their portfolio, to manage risk, and in some cases to isolate specific returns from an investment. For example, a fund might find the current floating interest rates for a Norwegian bond attractive, but wish to stabilize the return through a floating-for-fixed swap, and remove the currency risk by swapping the NOK coupon for USD.&#x20;

Asset managers may also use interest rate derivatives in conjunction with currency trades to protect their base currency returns, against which their performance is attributed. Institutional investors will typically trade vanilla and basis swaps, with occasional use of other instruments to meet specific investment strategies. Caps, floors and collars will be purchased to lock in specific returns or hedge downside risk.<br>


# Speculators and Proprietary Trading Functions

Speculators and prop trading functions may use rate derivatives to hedge their risk, but they may also take positions based on assumptions about the directions of interest rates or to exploit arbitrage or rate improvement opportunities across markets. These participants may trade a wide range of instrument types.<br>


# Brokers and Market Makers

Brokers and market makers enter into transactions to generate fees and profit on spreads. Their activity provides liquidity to the market. Often the broker will enter into one or more corresponding trades to keep their positions risk-neutral. Some will offer markets across a wide range of rates derivatives while others may limit their activity to a specific sector or type of swap.<br>


# Liquidity Management, Funding and Resource Management

Liquidity management and funding use rates contracts to manage the risk and optimize returns on available funds. The instruments used will typically be aligned with the cash and funding markets the institution is operating in.<br>


# Risk Management and Insurance

Risk managers and insurance companies will often employ rates derivatives to hedge volatility on their fixed income portfolios held or the fixed income liabilities the institution has issued.<br>


# Smaller Institutions and Individuals

These participants are currently largely excluded from the market due to cost and credit worthiness. As a result, the needs these smaller players may have--such as reduction of exposure to rate volatility, seeking lower cost funding, or maximizing returns on fixed income investments, are not currently being addressed. While simple fixed for floating transactions are undoubtedly the most immediately useful solution to this market segment, other instruments including basis swaps may well be attractive offerings as well.<br>


# Swivel for Enterprise

A discussion of Swivel's potential use within institutional and enterprise environments.

### Overview

Swivel is building decentralized infrastructure for interest-rate derivatives. This includes various cash flow instruments, with the first product being similar to a fixed-for-floating rate swap. Swivel’s foundations are a series of smart contracts to support an order-book based marketplace for interest rate derivatives. Starting with a simple fixed-for-floating exchange, Swivel intends to develop a series of instruments to enable risk management, funding optimization and hedging.&#x20;

Our initial focus allows investors seeking stable predictable cash flows to receive fixed rates, and risk seeking investors to leverage floating rate positions. Over time, we plan to use the order book venue to introduce a range of digital instruments for rate profile optimization.

For large and small scale enterprises including financial institutions and institutional investors, Swivel offers a service with a range of advantages to different roles in your organization:

* **Optimize rate profiles**
* **Reduce cost of funding**&#x20;
* **Improve treasury management**&#x20;
* **Improved Risk management through hedging**&#x20;
* **Improved liquidity management**
* **Market making fees and attractive incentives**&#x20;
* **Offer retail and institutional clients an alternative to traditional fixed income products with potential for high returns, suitable for both stable return and risk-seeking investor profiles**
* **Low ticket size, reduced barriers to entry and thus the ability to offer sophisticated rate management service to individual investor and smaller enterprise clients**

**Fixed-rate yields** provide **risk averse lenders** with the guaranteed cash flows and avoidance of variability in income streams that may be necessary for their use case. These users have the incentive to lock in the **highest rate possible.** For **interest rate speculators,** leveraged money-market vaults provide risk-tolerant lenders and risk averse borrowers the exposure necessary to execute their strategies. These users have the incentive to pay the **lowest premium possible** for this exposur&#x65;**.**

Swivel brings the ability to exchange interest rates among market participants **without the need for bank intermediation and bank fees.** In addition, the **efficiency and low unit cost** of our solution enables lenders and borrowers to enter the market at **very small ticket sizes,** facilitating their access to interest rate management tools that were previously restricted to the costly domain of large institutional investors.

Swivel’s **short-term strategy is focused on a single use case,** the exchange of principal at a stable fixed rate for leveraged floating rate returns. This allows us to quickly bring an audited, secure solution to market. At the same time, we will be building an order book-based marketplace and growing liquidity around a platform that can in future support a **wide range of future interest management products,** including but not limited to basis swaps, interest and principal only products, and other predictable (both deterministic and non-deterministic) future cash flow instruments.&#x20;

### **How Swivel works**

Swivel’s platform directly facilitates the ability to manage risk by allowing users to **trade predictable cash flows (fixed-rate) via receiving tokenized zero-coupon bonds** or the ability to **leverage capital exposure by purchasing interest coupons.** While the first implementation of this model is a straightforward mechanism to exchange fixed for floating cash flows on the Compound Finance platform, in future the same model can be extended to meet a variety of investment, risk management, treasury and funding needs, as well as interoperable solutions across multiple yield-providing venues.&#x20;

Investors **seeking stable returns** post orders on our order book for a desired amount of principal, as well as rate sought and desired maturity date. Maturity dates are synchronized to **support fungible positions** and **assure an orderly market** with straightforward dates to compare returns against.

**I**nterest rate speculators fill the order, paying an upfront premium equal to the rate sought and in return receive a time-locked vault of the tendered principal, which is then invested in floating rate positions. The principal balances are tendered against synchronized maturity dates, making comparisons across dates transparent and supporting fungible positions against common maturities. The floating rate side is **highly leveraged,** offering these participants the **possibility of significant returns.**&#x20;

### **Flexible Order Book**&#x20;

Swivel is differentiated from other projects by the application of a **unique, flexible orderbook infrastructure** that allows the entry/exit of any fixed rate zero-coupon bond, or any corresponding floating interest coupon position through a shared pricing mechanism.&#x20;

**Support for Efficient Risk Management and Return Seeking**

Users and market makers can use Swivel’s orderbook to **accurately execute strategies** and take positions with a **precision** not possible on an AMM (Automated Market Maker).

**Advantages for market makers**&#x20;

Swivel offers **attractive incentives** for market makers. Institutions with large positions in other venues can offset their risk by making markets while taking countervailing positions on Swivel, and generating market making fees on the spreads between venues.&#x20;

Swivel’s orderbook facilitates active capital allocation with respect to underlying money-market rates, ensuring market-makers can **manage risk and retain an edge** in times of rate volatility.

The orderbook’s shared pricing mechanism results in **dynamic pricing** and significantly **enhanced capital efficiency.** Each user has the ability to enter into positions that more exactly meet their appetites for risk, reward and tenor than wholesale financial markets, without the need for bank intermediation or predatory fees. Swivel facilitates **exchange of value and risk** at a level of **precision** that previously has been unavailable to individual investors and small enterprises.&#x20;

### **Future Developments**&#x20;

With our capital efficient issuance and order book mechanisms, we provide the initial capability to exchange fixed for floating rate positions, in the future we will enable the ability to efficiently manage a **number of various cash-flows.** These programmable cash-flows then enable a number of **structured instruments** that are core to efficient capital allocation and risk-management. We may also provide instruments to manage the differences in risk and maturity dates across different cash instruments, enabling more **accurate hedging and improved fungibility.**<br>


# Overview

An overview of Swivel in the context of enterprise.

Swivel is building decentralized infrastructure for interest-rate derivatives. This includes various cash flow instruments, with the first product being similar to a fixed-for-floating rate swap. Swivel is built upon a series of smart contracts that support an order-book based marketplace for interest rate derivatives. Starting with a simple fixed-for-floating exchange, Swivel intends to develop a series of instruments that enable efficient risk management, funding optimization and exposure hedging.&#x20;

Our initial focus allows investors seeking stable predictable cash flows to receive fixed rates, and risk seeking investors to leverage floating rate positions. Over time, we plan to use the order book venue to introduce a range of digital instruments for rate profile optimization.

For large and small scale enterprises including financial institutions and institutional investors, Swivel offers a service with a range of advantages to different roles in your organization:

* **Optimize rate profiles**
* **Reduce cost of funding**&#x20;
* **Improve treasury management**&#x20;
* **Improved Risk management through hedging**&#x20;
* **Improved liquidity management**
* **Market making fees and attractive incentives**&#x20;
* **Offer retail and institutional clients an alternative to traditional fixed income products with potential for high returns, suitable for both stable return and risk-seeking investor profiles**
* **Low ticket size, reduced barriers to entry and thus the ability to offer sophisticated rate management service to individual investor and smaller enterprise clients**

**Fixed-rate yields** provide **risk averse lenders** with the guaranteed cash flows and avoidance of variability in income streams that may be necessary for their use case. These users have the incentive to lock in the **highest rate possible.** For **interest rate speculators,** leveraged money-market vaults provide risk-tolerant lenders and risk averse borrowers the exposure necessary to execute their strategies. These users have the incentive to pay the **lowest premium possible** for this exposur&#x65;**.**

Swivel brings the ability to exchange interest rates among market participants **without the need for bank intermediation and bank fees.** In addition, the **efficiency and low unit cost** of our solution enables lenders and borrowers to enter the market at **very small ticket sizes,** facilitating their access to interest rate management tools that were previously restricted to the costly domain of large institutional investors.

Swivel’s short-term strategy is focused on a single use cas&#x65;**,** the exchange of principal at a stable fixed rate for leveraged floating rate returns. This allows us to quickly bring an audited, secure solution to market. At the same time, we will be building an order book-based marketplace and growing liquidity around a platform that can in future support a **wide range of future interest management products,** including but not limited to basis swaps, interest and principal only products, and other predictable (both deterministic and non-deterministic) future cash flow instruments.&#x20;


# How Swivel works

A basic description of Swivel's core mechanic.

Swivel’s platform directly facilitates the ability to manage risk by allowing users to **trade predictable cash flows (fixed-rate) via receiving tokenized zero-coupon bonds** or the ability to **leverage capital exposure by purchasing interest coupons.** While the first implementation of this model is a straightforward mechanism to exchange fixed for floating cash flows on the Compound Finance platform, in future the same model can be extended to meet a variety of investment, risk management, treasury and funding needs, as well as interoperable solutions across multiple yield-providing venues.&#x20;

Investors **seeking stable returns** post orders on our order book for a desired amount of principal, as well as rate sought and desired maturity date. Maturity dates are synchronized to **support fungible positions** and **assure an orderly market** with straightforward dates to compare returns against.

Interest rate speculators fill the order, paying an upfront premium equal to the rate sought and in return receive a time-locked vault of the tendered principal, which is then invested in floating rate positions. The principal balances are tendered against synchronized maturity dates, making comparisons across dates transparent and supporting fungible positions against common maturities. The floating rate side is **highly leveraged,** offering these participants the **possibility of significant returns.**&#x20;


# Flexible Order Book

A look at Swivel's largest differentiator.

Swivel is differentiated from other projects by the application of a **unique, flexible orderbook infrastructure** that allows the entry/exit of any fixed rate zero-coupon bond, or any corresponding floating interest coupon position through a shared pricing mechanism.&#x20;

**Support for Efficient Risk Management and Return Seeking**

Users and market makers can use Swivel’s orderbook to **accurately execute strategies** and take positions with a **precision** not possible on an AMM (Automated Market Maker).

**Advantages for market makers**&#x20;

Swivel offers **attractive incentives** for market makers. Institutions with large positions in other venues can offset their risk by making markets while taking countervailing positions on Swivel, and generating market making fees on the spreads between venues.&#x20;

Swivel’s orderbook facilitates active capital allocation with respect to underlying money-market rates, ensuring market-makers can **manage risk and retain an edge** in times of rate volatility.

The orderbook’s shared pricing mechanism results in **dynamic pricing** and significantly **enhanced capital efficiency.** Each user has the ability to enter into positions that more exactly meet their appetites for risk, reward and tenor than wholesale financial markets, without the need for bank intermediation or predatory fees. Swivel facilitates **exchange of value and risk** at a level of **precision** that previously has been unavailable to individual investors and small enterprises.&#x20;


# Future Developments

A discussion of future extensions to Swivel.

With our capital efficient issuance and order book mechanisms, we provide the initial capability to exchange fixed for floating rate positions, in the future we will enable the ability to efficiently manage a **number of various cash-flows.** These programmable cash-flows then enable a number of **structured instruments** that are core to efficient capital allocation and risk-management. We may also provide instruments to manage the differences in risk and maturity dates across different cash instruments, enabling more **accurate hedging and improved fungibility.**


# Delegated Credit

Credit delegation is one method that allows a borrower to receive credit when they do not have sufficient collateral. However, the lender must trust the borrower; credit delegation does not support a trustless model.

In credit delegation, two parties can enter into a trusted agreement where the depositor’s capital can be borrowed by the counterparty. Once the trusted borrower is locked into a legally defined lending arrangement with the lender, the borrower can access the capital without providing collateral. Borrowers preserve liquidity by not tying other assets to the loan, and such a relationship may also provide additional flexibility to the borrower. <br>


# Challenges of Delegated Credit

The challenge of such relationships is they must be based on specific lines of trust. The lender must conduct their own due diligence on the borrower, and ascertain whether the borrower can be trusted to repay. Furthermore, the lender may lack access to financial intelligence about the borrower’s ongoing behavior, and be blind to indications of deteriorating credit worthiness.<br>

This model may be effective on a small scale, and between parties who are well known to each other. But as decentralized markets for delegated credit scale up in size, the overhead of individual  due diligence for each lending relationship is bound to become burdensome. Beyond that, the relationship-based trust model is unlikely to be economically sound in the long run. Extrapolating that a large-scale decentralized economy can operate from an informal “I’ll get the next round of beers” form of mutualism is bound to result in error and loss.<br>

This implies a need for trusted sources of credit information in order to preserve a scalable, liquid market for under collateralized lending. Traditional credit scores rely on the fact that repayment schemes are, in reality, more flexible than their legal terms admit. Credit scores take in data points such as late or partial repayment to compile the score.<br>

In a world of atomic transactions, where transactions are automatically executed on schedule by smart contract, that signal of impending default is absent. Unless there is pre-existing or validated trust, the lender can’t rely on prior performance as an indicator of future behavior. Thus some level of trust intermediation, through a third party or service, is essential if rational allocation of lending at understood levels of risk is to occur.<br>


# Credit Pools

One option to support a solution similar to credit scoring would be for borrowers to be grouped into pools based on their reputational or credit scores. Lenders could inspect the scores and elect to loan to the pools which best met their risk tolerance and desired return. The pool could provide important benefits of risk reduction via diversification and presumably lower individual due diligence.<br>


# Intermediating Trust in Credit Delegation

There are several models as to how this intermediation of trust might work:

1. Centralized models akin to typical credit scoring systems, where the scoring agency takes in an actor’s economic behavior and performance vs installment credit and creates a ranking
2. Decentralized models where a range of actors provide reputation scoring for participants based on their interactions with the participant
3. Centralized scoring performed by intelligent algorithms or credit oracles. One way this could work is with a zero knowledge proof operating within an enclave: an actor could present the algorithm with an encrypted file of the necessary information to create a credit score. The algorithm, running within an enclave, would decrypt the file within the protected zone and run the score. Noone except the provider would have access to the unencrypted data, and the ZK algorithm would store and publish only the final scoring, not the data used to prepare it.


# Litepaper

A Basic Description and Visualization of the Swivel Protocol's mechanics.

## Introduction

Concerns surrounding protocols like Compound and Aave have become acceptable for all but the most risk-averse market participants. However, the volatility of DeFi rates still precludes many from effective portfolio/risk management, and others from market participation entirely. \
\
Swivel enables this wider market participation by providing the capital efficient infrastructure and professional trading interface necessary for tokenized cash-flows.

### Tokenizing Cash-Flows (Yield Tokenization)

At it's core, Swivel is built around the concept of cash flow-tokenization (Yield Tokenization).&#x20;

Swivel provides lenders the ability to split an interest generating token into two separate cash-flow tokens until a future date. One token representing the future yield generated (YTs), and another representing ownership of an underlying token, redeemable at that future date (PTs).

In Swivel's design these two are referred to as *YTs* (yield-generating tokens), and *PTs* (tokens redeemable at maturity).

This flexible architecture facilitates a number of interesting use-cases, namely fixed-yield lending and yield boosting (rate-trading), and provides the core infrastructure necessary for fixed-maturity rehypothecation (options markets, futures markets, etc.,).

![Splitting USDC into ptUSDC and ytUSDC](/files/NMk6U5weWoFcvtCt0lJO)


# Principal Tokens (PTs)

ERC-20 Tokens that represent a 1-1 claim for underlying upon maturity.

### Overview

Principal tokens, ***PTs***, are ERC-20's which are redeemable 1:1 at maturity for an underlying token.&#x20;

As users lock-in fixed yields, their deposit is split into PTs and YTs (yield tokens) and the the YTs minted are sold to fuel a fixed-yield.&#x20;

This leaves the lender with an immediate fixed-yield and their minted PTs.

**Fixed-Yield Lending:**

**Alice has 1000 USDC.**\
**Alice fills Bob's order, splitting 1000 USDC into 1000 ptUSDC and 1000 ytUSDC.**\
**Alice sells 1000 ytUSDC to Bob for 50 USDC.**\
**Alice then has 1000 ptUSDC. At maturity Alice redeems her 1000 ptUSDC for 1000 USDC.**\
**This leaves Alice with 1050 USDC.**

![Lending 1000 USDC at 5% for 1 Year](/files/rtNIp2Vf02FSkyKSUGb2)

### Pricing

Given PTs represent a 1-1 redemption only upon maturity, they are discounted at a rate based on the predicted amount of interest that may have otherwise been generated until the maturity/redemption date (the YT price).

Accepting that this potential yield decreases as time passes, PTs appreciate towards par and reach par as maturity is reached.

Further, because a YT represents the predicted future yield, the discount on a PT is inversely proportional to the cost of an YT.

At maturity, PTs begin to appreciate above par, accruing the yield generated on a given money-market (e.g. Compound) until redeemed.


# Exiting/Selling PTs

An example of common market interactions

As rates fluctuate, active market participants may require the ability to fluidly move in and out of positions.

To facilitate this market participation, Swivel provides the ability to frictionlessly exit or sell a PT position.

Exiting PTs early by purchasing YTs and then redeeming for underlying:

**Alice has 1000 ptUSDC.**\
**Alice fills Bob's order, purchasing 1000 ytTokens.**\
**Alice redeems 1000 ptUSDC and 1000 ytUSDC for 1000 USDC and then pays Bob 50 USDC.**\
**This leaves Alice with 950 USDC.**

![](/files/ao3iXSRgmMumkk74qql1)

PTs can also be sold to counterparties looking to take fixed-yield positions through the orderbook:

**Alice has 1000 ptUSDC.**\
**Alice fills Diane's order, in the process Alice splitting Diane's 1000 USDC into ptUSDC and ytUSDC.**\
**Alice purchases 1000 ytUSDC from Diane and redeems her 1000 ptUSDC + 1000 ytUSDC for 1000 USDC.**\
**Alice then pays Diane a 50 USDC premium for the purchased ytUSDC.**\
**This leaves Alice with 950 USDC.**\
*(Simplified to 1000 ptUSDC <-> 950 USDC)*

![Selling PTs to initiating fixed-yield counterparties.](/files/HeX3i465VCnjDW7CdTLZ)

<br>


# Secondary AMM's

A discussion of potential secondary markets and cross-chain access to fixed-yields.

PTs can also be traded on a secondary AMM in order to enter or exit lending positions, or alternatively attempt to amplify yield by providing liquidity.\
(see: Risks of LPing in derivative marketplaces)

Entering:

**Alice has 1000 USDC and wants a fixed yield.**\
**Alice purchases 1050 ptTokens for 1000 USDC, maturing in one year for a 5% yield.**

Exiting:

**Alice has 1050 ptTokens and wants to exit.**\
**Alice sells 1050 ptTokens for 1000 USDC.**

![](/files/AwNSAY3y0VVWRoVbmDex)


# Yield Tokens (YTs)

Yield Tokens contained in Swivel's Vaults which represent the claim to underlying yields.

### Overview

When a user buys YTs, they create a vault that tracks their balances within a given market.

Each vault contains two balances, *Notional* and *Redeemable.*

#### **Notional (YTs)**

Notional Tokens ***(YTs)*** represent a 1-1 deposit, currently generating interest in an underlying protocol. Once maturity has been reached, interest-generation ceases and YTs become worthless.

As such, YTs are deprecating assets that experience time-decay. As time passes, YTs decrease in value, and as they approach maturity, an their value approaches 0.

#### Redeemable

The ***Redeemable*** represents the amount of accrued interest currently available to redeem.&#x20;

As users interact with their vault, interest is accumulated to the redeemable balance, and this balance can be redeemed at any time.

\
**Buying nTokens:**
-------------------

**Bob has 50 USDC.**\
**Bob fills Alice's order selling 1000 ytUSDC at .05/ea (5%), paying Alice an immediate $50 premium.**\
**Once filled, Alice mints 1000 ptUSDC and 1000 ytUSDC, transferring 1000 ytUSDC to Bob.**\
**Bob then owns 1000 ytUSDC (the right to the yield generated by 1000 USDC).**

![](/files/6CgWVQTzF5mvRRidBgXF)

### Pricing

Given YTs represent a 1-1 deposit into an underlying money-market, and the claim to the deposit's future yield, they are priced based on the expected yield generated until maturity.

This potential future yield decreases as time passes and as such, YTs depreciate and experience theta-decay.

Of note, because a PT represents an underlying token stripped of YT yields, the cost of a YT is inversely proportional to the discount on a PT.


# Exiting/Selling YTs

An example of common market interactions

As with PTs, as rates fluctuate, active market participants require the ability to fluidly move in and out of YT positions. To facilitate this market participation, Swivel provides the ability to exit/sell YTs on our orderbook.&#x20;

Selling YTs to an initiating counterparty:

**Bob has 1000 ytUSDC.**\
**Bob fills Charlie's order for 1000 ytUSDC, and in return receives 50 USDC.**\
**This leaves Bob with 50 USDC + any accrued interest.**

![Selling YTs to an initiating YT counterparty](/files/9Op3eFjCZqdypv6TnuUr)

YTs can also be sold to counterparties redeeming their PTs early:

**Bob has 1000 ytUSDC.**\
**Bob fills Alice's order, selling Alice 1000 ytTokens.**\
**Alice redeems 1000 ptUSDC + 1000 ytUSDC for 1000 USDC and then pays Bob 50 USDC.**\
**This leaves Bob with 50 USDC + any accrued interest.**

![Selling YTs to an exiting PT counterparty](/files/soONQtc1ThEFWIesjt0V)


# AMM vs. Orderbook

An overview of capital efficiency within Interest-Rate Derivative and Cash-Flow Markets

AMM's have insofar proven to be *the* effective mechanism for bootstrapping liquidity, however the efficacy and capital efficiency of AMM's within derivative markets has proven to be questionable at best.

Without the ability to adjust quoted prices with regard to standard derivative pricing variables, liquidity providers are exposed to significant risk and constantly give up an edge to the market. (As seen in LP returns)

![-25% APY for HEGIC LP's ](https://cdn.substack.com/image/fetch/w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fbucketeer-e05bbc84-baa3-437e-9518-adb32be77984.s3.amazonaws.com%2Fpublic%2Fimages%2F198e2c1b-e12c-4c41-879b-f2d5716f44f2_2276x646.jpeg)

Swivel instead attempts to bootstrap liquidity by providing the same token incentives present on most AMM's, but with the enhanced capital efficiency and flexibility that an orderbook can provide for all market participants.

In my previous article, “[So… Why an Orderbook?](https://swivel.substack.com/p/so-why-an-orderbook)” I walked through the reasoning behind our decision to implement an orderbook for interest-rates and cash-flow tokens.

![](/files/aajoFFbB8IW3fhJbPIsV)

As a quick TL;DR, the primary benefits are:

* Increased general capital efficiency (similar to spot markets)
* The ability for LPs to manage inventory with respect to:
  * Underlying rates
  * Time-decay (Theta)
  * Sensitivity to rate variance (Delta)
  * Underlying rate volatility (Vega)
* Combined Principal Token and Yield Token liquidity pools (+100% capital efficiency)
* Free limit orders + order cancellation

## Instrument-Specific Optimizations

If then attempting to address Swivel's market with an AMM, one would need both a time-appreciating AMM for zero-coupon tokens (similar to Element), and a time-depreciating AMM for interest-coupons (similar to Pendle).&#x20;

With Swivel's flexible orderbook, these separate AMM's are not necessary as a user can enter the marketplace with an underlying currency (USDC, ETC, BTC, etc.,), or alternatively with either zero-coupon tokens or money-market notional (interest-coupons) when exiting positions.&#x20;

As a result Swivel's users benefit from the generalized efficiencies provided by an orderbook, and the further **\~2x** enhanced capital efficiency when compared to two separate AMM's.

## **Minting YTs (Interest-Coupons)**

Swivel’s issuance of interest-coupon&#x73;*,* termed *Yield Tokens* (YTs)*,* is optimized in two ways:

1. YTs include interest-generation and tracking functionality within their transfer function which:

   * Reduces the deposit overhead present in designs which require increasing deposits over time&#x20;
   * Reduces complexity in YT pricing
   * Allows interest to be redeemed at any time&#x20;

2. Swivel atomically mints tokens as orders are filled which reduces the number of transactions necessary for most use cases.


# Swivel Safety Module (SSM)

An introduction to staking with the Swivel Safety Module

As introduced on our substack, the Swivel Safety Module (SSM) serves as a central mechanism for stakeholder empowerment while acting as an effective protocol backstop.

Through the Swivel Safety Module SWIV stakeholders can stake their SWIV tokens alongside ETH at a 80:20 ratio, in the process providing liquidity to an 80/20 weighted Balancer pool while implicitly insuring deposits on the Swivel protocol.

This design allows our most confident stakeholders to commit their SWIV towards protecting the protocol while earning significant premiums alongside the protocols growth.

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

## Shortfall Events

A shortfall event is defined as a loss that has occurred on Swivel that has originated from faults that directly relate to the Swivel protocol. Such events would include the loss of funds on Swivel.sol relating to bugs or hacks of the Swivel protocol as well as any admin errors or faults relating to the management of the Swivel protocol.

Losses originating from external protocols that are isolated to those external protocols are not covered by the SSM. For example, if Aave has their own shortfall event, depositors on Swivel are not insured by both the SSM as well as Aave's security module, and instead would rely on the Aave security module to cover their deposit.

Facing ambiguity, determining a shortfall event, and the payout of funds for a shortfall event will rely on governance.

## APR Explained

The yields that SSM stakers (stkSWIV holders) recieve are comprised of a number of revenue streams.

* Swivel Protocol Fees: The SSM earns 50% of all fees currently generated on the Swivel protocol. The fee share is variable dependent on future governance proposals.
* Balancer LP Fees: As all deposits are also providing liquidity, the SSM also earns all fees generated by an 80/20 Balancer pool comprised of SWIV/ETH.
* SWIV Incentives: Each epoch a given amount of SWIV are allocated in incentives to the SSM.
* External Incentives: Each Balancer Pool is eligible for incentives through balancers veBAL gauge system.

## Cooldown Times & Limited Loss

In order to ensure the solvency of the SSM during a shortfall event, cover of the Swivel protocol is limited to 33% of the current value of the SSM.

Further, in order to ensure users do not withdraw in preparation for an upcoming payout, withdraws must be queued and set on a cooldown before being processed.

Specifically, users must queue their withdrawal 2 weeks before their expected withdrawal date, and then have a 1 week window to then withdraw their funds.

## Risks

As already mentioned, while a staker's loss is limited to 33% of their stake, stakers are taking on the risks involved in covering deposits on the Swivel protocol. This is discussed in more detail above under [#shortfall-events](#shortfall-events "mention").

Further, depositors are also exposed to the volatility and potential impermanent loss of the 80/20 Balancer pool.&#x20;


# Staking

How to stake your SWIV in the Swivel Safety Module

Navigate to the Staking page in Swivel V4 to add funds to the Safety Module. Make sure that you have some SWIV and ETH in your connected wallet so that you have funds to pool.

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

Click the "Stake" button (or "Stake More" if you already have staked funds) to open the transaction interface.

<figure><img src="/files/ClNAqQFzObs1wA5d43qU" alt="" width="364"><figcaption></figcaption></figure>

Choose an amount to stake by typing in the amount field or selecting a percent of total available balance.

<figure><img src="/files/uyyjdXodwEaKK31zgkxa" alt="" width="375"><figcaption></figcaption></figure>


# Withdrawing

How to withdraw your staked SWIV and Rewards

You can withdraw your staked assets following a [cooldown period](/swivel-safety-module-ssm#cooldown-times-and-limited-loss). To begin the cooldown process, use the Withdraw transaction interface on the Staking page.

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

The interface is reactive to your current withdraw state and will indicate if you have funds currently in the cooldown period or ready to withdraw whenever applicable.&#x20;

Click on "Queue For Withdrawal" (or "Queue More For Withdrawal" if a cooldown period is currently active).

<figure><img src="/files/QBM4P3RvQRhgaGYBWoIl" alt="" width="371"><figcaption></figcaption></figure>

In the following interface you can type the amount you would like to remove in SWIV or use the percent selector for a measured amount of the total balance. The transaction will automatically calculate the correct amount of ETH to withdraw as well.&#x20;

<figure><img src="/files/XHv2R5Xz4t0rAyfVa8Rl" alt="" width="371"><figcaption></figcaption></figure>

If you already have a cooldown period active that has no completed, you will be shown a warning that queing more funds for withdraw will **Reset the Cooldown Period**

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




---

[Next Page](/llms-full.txt/1)

