# APY.Finance

## Resources

* [Discord](https://discord.gg/uzqAsmZ)
* [Telegram](https://t.me/apyfinancechat)
* [Twitter](https://twitter.com/apyfinance)
* [Medium](https://medium.com/apy-finance)


# APY Tokens

## Overview

The APY token is the APY.Finance governance token. As platform's features are built out, the token will be used to govern them.

{% hint style="info" %}
APY token contract address: 0x95a4492F028aa1fd432Ea71146b433E7B4446611
{% endhint %}

{% hint style="info" %}
**Token links**

* [Coin Gecko](https://www.coingecko.com/en/coins/apy-finance)
* [Etherscan](https://etherscan.io/token/0x95a4492F028aa1fd432Ea71146b433E7B4446611)
* [CoinMarketCap](https://coinmarketcap.com/currencies/apy-finance/)
  {% endhint %}

### Token Specs

| Field        | Value       |
| ------------ | ----------- |
| Type         | ERC-20      |
| Symbol       | APY         |
| Decimals     | 18          |
| Total Supply | 100,000,000 |

## Use Cases

APY token will be developed in three stages. Each stage releases new token features that grant greater control over the entire APY.Finance system.

### **Stage 1: Updating system-wide parameters** <a href="#id-4b60" id="id-4b60"></a>

APY token holders can vote to change system parameters such as **fees, risk score, and rebalance thresholds**.

**Fees:** The percentage of yield generated that will go to APY token holders for maintaining the protocol. This is initially set to 0.

**Risk Score:** Every strategy will have an associated risk score. APY token holders decentralize risk assessment by proposing and pushing risk score updates as the landscape changes.

**Rebalance Thresholds:** Determines how aggressive or conservative the strategies should be when rebalancing for higher yield.

### **Stage 2: Updating existing strategies** <a href="#b398" id="b398"></a>

APY token holders can vote to change strategy specific parameters such as **locking periods, collateralization ratios, and account segmentation.**

**Locking periods:** Some strategies may require locking of assets to boost yield. And example of this is Curve vote-locking.

**Collateralization ratios:** Any time leverage is used, a safe buffer of over-collateralization must be maintained to avoid liquidation. This can be more aggressive for higher yield, or more conservative for less risk.

**Account segmentation:** A strategy can interact with a protocol using any number of accounts. This allows for techniques such as the staging of different locking periods.

### **Stage 3: Proposing new strategies** <a href="#a322" id="a322"></a>

APY token holders can vote to propose new strategies for the strategy portfolio.

These proposal mechanics must be carefully designed to prevent conflicts of interest that arise from a strategy's influence over large amounts of capital.

## APY Token Distribution

![](/files/-MOhav-9c5GvD13jFaVY)

| Distribution                    | Description                                                                                                                                         |
| ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| Seed Investors                  | <ul><li>20,000,000 APY tokens (20.0%)</li><li>1 year vesting</li></ul>                                                                              |
| Strategic Investors             | <ul><li>16,500,000 APY tokens (16.5%)</li><li>1 year vesting</li></ul>                                                                              |
| Team & Advisors                 | <ul><li>20,000,000 APY tokens (20.0%)</li><li>4 year vesting, 1 year cliff</li></ul>                                                                |
| Community Initiatives           | <ul><li>12,300,000 APY tokens (12.3%)</li><li>Initiatives will benefit community developers who participate in the APY.Finance ecosystem.</li></ul> |
| Public Liquidity Mining Rewards | <ul><li>31,200,000 APY tokens (31.2%)</li><li>Rewards will benefit users and stakers who participate in the APY.Finance ecosystem.</li></ul>        |


# User Guide

This guide helps you get started using the APY.Finance platform and discover all the amazing things you can do.

### **Connect your wallet**

For secure connections and safe transactions, the platform supports Metamask. Before you begin make sure you have Metamask installed: <https://metamask.io/download.html>

### **Navigating from the Home page**

The Home page shows you the core functionality available in the platform, such as Earning Yield, and Earning Rewards for providing liquidity to the Balancer or Uniswap liquidity pools. High level information about the platform, such as the Total Value Locked (TVL), Annual Yield, and number of Active Strategies are displayed here as well.

## **Earning Yield**

Press the Earn Yield button at the top of the Home Page to go to the Yield farming section of the platform. You can use stablecoins including DAI, USDC, or USDT to earn yield from our active strategies.

![](https://lh6.googleusercontent.com/D24gESlebQnYEwq28XKfvkJPqP9uyghBhLplmr34xRylkVZOWho2swyewzg_CS2T1Ryfz7ifHd4OFUGQdzYwEQgRMhtMA17g9QFlaSOw27H-2_00AQyHcLNwJJqngoeK3WsekOvm)

### **Deposit Stablecoins**

To deposit stablecoins into APY and begin earning yield, you must select one of the supported stablecoin options: DAI, USDC or USDT token on the deposit form.

&#x20;<img src="/files/Ws4MNOHLGUyHaahiYsTj" alt="" data-size="original">

To Enable deposits, press the Enable button at the bottom of the form, and complete the transaction on Metamask.&#x20;

![](/files/BsfDOIsDy1gQcKdPsjFX)

Once enabled, you will have the ability to deposit the stablecoin of your choice  into the platform, and earn yield. Enter the amount you wish to deposit, and press Deposit, and complete the transaction on Metamask.

![](/files/I66OBwOW9A6MHbk0Tlym)

### **Claim**

Overtime, you will earn yield for the stablecoins that you deposit into the system. You can claim the rewards you earn at any time. To claim your rewards, scroll towards the bottom of the Yield page, and on the right side you will see a total number of claimable APY.&#x20;

![](/files/ydO7gwQb3mFiCQjsPbwf)

To claim rewards, press the Claim APY button, and complete the transaction on Metamask.

### **Withdraw**&#x20;

Once you're ready to withdraw the stablecoins you deposited into the platform, you can return to the Yield page, switch to the Withdraw form, and withdraw the appropriate amount out of the platform.&#x20;

Note: for users withdrawing large amounts of deposited stablecoins from the platforms at one time (>10% of the TVL), your transaction may trigger the [Reserve Pool Safeguard](/getting-started/reserve-pool-safeguard).

![](/files/x5LjWqJa12WGnG0oXkhZ)

## **Support**

If you have any technical questions, please visit our forum at <https://forum.apy.finance/> and search for the answer or send an email to <support@apy.finance>.


# Reserve Pool Safeguard

The platform has a reserve-pool safeguard which prevents the pools and user’s funds from being drained in the rare black-swan event of a system-wide hack or exploit.&#x20;

With the safeguard in place, account holders that own a large portion of the TVL will not be able to instantaneously make large withdrawals of \~10% or more of the TVL at the time of withdrawing.&#x20;

To avoid the necessity of making large withdrawals over a longer period of time, contact [reservepool@apy.finance ](https://finance.us17.list-manage.com/track/click?u=364c817c91a8f54732894b7c6\&id=54e0c3bcba\&e=e0c0049e0b)prior to withdrawing to ensure these withdrawals don’t activate these safeguards.


# Litepaper

## Overview

The APY.Finance platform is a yield farming robo-advisor that runs a portfolio of yield farming strategies from a single pool of liquidity.

Key features of APY.Finance include:

* Capture growth across the DeFi industry with a single deposit.
* Diversified portfolio of yield farming strategies to reduce smart contract risk and yield volatility.
* Automatic portfolio rebalancing to optimize risk-adjusted yield.
* Over 99% gas savings on rebalance fees compared to independent manual yield farming.
* Over 80% gas savings on deposit and withdrawal fees compared to other yield farming aggregators.

![](/files/-MKMPzz76FIvXDETJwDg)

## APY Liquidity Pool

The APY liquidity pool is actually a collection of contracts that handle the deposit and withdrawal of a single currency. These contracts work together to form a single pool of liquidity. When a sender deposits into a contract, they are issued APT tokens to represent their share of the pool.

Each liquidity contract determines the notional value of its reserves using existing Chainlink aggregators. We use the ETH denominated aggregators because they are updated more frequently and have more sponsors.

{% hint style="info" %}
You can view some of the Chainlink aggregators we use [here](https://feeds.chain.link/).
{% endhint %}

## APY Strategy Portfolio

The APY strategy portfolio is a library of strategy contracts that interact with financial primitives to earn yield.

### Types of Assets

Every strategy has an asset schema that describes the types of assets and which assets are used for each type.

| Type                | Description                                        | Example    |
| ------------------- | -------------------------------------------------- | ---------- |
| Input assets        | Required to begin earning yield from the strategy. | DAI, USDC  |
| Intermediary assets | Held by the contract while running the strategy.   | cDAI, yCRV |
| Output assets       | Generated by the strategy and swapped for yield.   | COMP, CRV  |

### Types of Sequences

Every strategy has three different sequences that are used over the course of its life-cycle.

| Sequence | Description                               | Example                             |
| -------- | ----------------------------------------- | ----------------------------------- |
| Entry    | Deploys input assets to the strategy.     | Using DAI to mint cDAI.             |
| Loop     | Performs regular upkeep for the strategy. | Swapping COMP for DAI to mint cDAI. |
| Exit     | Unwinds the strategy.                     | Retrieving DAI by redeeming cDAI.   |

These assets and sequences for each strategy are used by the APY manager to process deposits, withdrawals, new portfolio optimizations, and to earn yield.

### Yield Estimates

Every strategy has a view function to calculate the yield estimate for a given amount of input assets at the current block state. This estimate is used when comparing strategies and determining optimal strategy allocations.

### Risk Scores

Every strategy has a risk score associated with it. This score is represented by a number between 0 and 10e18. The initial risk score is set when the strategy contract is first deployed, however it can be updated through governance proposals.

The team looks at a variety of risk factors to asses the risk score using the DeFi Score whitepaper as a template.

Risk scores are used to weight a strategy's estimated yield to get a risk-adjusted yield. It is this risk-adjusted yield that is primarily used when optimizing portfolio allocations.

{% hint style="info" %}
You can read the DeFi Score whitepaper [here](https://github.com/ConsenSys/defi-score/blob/master/whitepaper.md).
{% endhint %}

### Upcoming Strategies

| Strategy                      | Description                                                 |
| ----------------------------- | ----------------------------------------------------------- |
| Compound DAI^3                | COMP farming with leveraged DAI using dYdX flash loan.      |
| Boosted yCRV                  | CRV farming with 1 week locked veCRV with the yCRV pool.    |
| DODO USDT-USDC                | DODO farming with the USDT-USDC DODO pool.                  |
| DeFiDollar DUSD-USDC Balancer | DFD, BAL, and CRV farming with the DUSD-USDC Balancer pool. |

## APY Manager

The APY manager automates the movement of liquidity through the APY system.

### Rebalancing

The manager contract contains a `rebalance` function that sets in motion several important processes:

1. If there is any reserves sitting idle in the liquidity pool from new deposits, they will be deployed proportionally to the current strategy portfolio.<br>
2. If the notional amount of withdrawal requests is less than the amount idle reserves in the liquidity pool, the reserves will be locked for withdrawal and the requests will pass.<br>
3. If the notional amount of withdrawal requests exceeds the amount of idle reserves in the liquidity pool, portions of the strategy portfolio will be unwound until all the withdrawal requests can be processed. These reserves are then locked for withdrawal and the requests will pass.<br>
4. If the notional value of assets in any strategy are no longer within a certain threshold of the currently selected allocation ratios, it will be rebalanced to match the desired ratios.<br>
5. Executing each strategy's loop sequence if the threshold conditions for a loop are met.

{% hint style="info" %}
The `rebalance` function can be called by any external address.
{% endhint %}

#### Automation

Because Ethereum does not natively support trigger-based automation, this `rebalance` function must be called regularly for the system to function. To prevent dependencies on a centralized authority for automation, third parties have an incentive to make rebalance calls.

Rebalance incentives are issued from a rebalance pool that reserves small portions of yield earned by the strategy portfolio.

#### Swapping

The APY manager handles swaps between liquidity pool assets and the strategy portfolio input assets. When the proportions of available liquidity pool assets do not match the desired proportions of input assets, they are swapped to meet thresholds.

Example:

* There are 3 portfolio strategies and the current portfolio optimization expects a ratio of 50/25/25.
* The first and second strategies require DAI and the third strategy requires USDC.
* The liquidity pool is 50/50 DAI and USDC.

Given these conditions, the APY manager will swap half of the USDC reserves for DAI before deploying to the strategy portfolio on the next rebalance.

{% hint style="info" %}
The transaction fees and slippage of these swaps are considered when determining the transaction cost of a portfolio optimization.
{% endhint %}

### Portfolio Optimization

Portfolio optimization for risk-adjusted yield that varies based on the amount of deployed liquidity is essentially a network flow problem. For portfolios with fewer strategies, the optimal portfolio allocation can be computed on-chain. However, as the number of strategies inevitably increases, the computation required to optimize the portfolio will begin to exceed the block gas limit.

To solve this issue, the APY platform allows off-chain computation of portfolio allocations that can be submitted to the APY manager for verification. The APY manager compares this new set of allocations with the old set using the on-chain yield estimates for each strategy. If the new set of allocations results in a greater risk-adjusted yield, and the transaction costs of rebalancing are lower than the gain in yield by a threshold, the new set of allocations can be automatically accepted.

Because it is unnecessary to verify that an allocation is perfectly optimal, only that it is more optimal, the APY platform can safely allow this off-chain computation without relying on a central authority to sign off on new allocations.

### Generic Strategy Executor

The generic strategy executor is a type of strategy contract that will be used heavily with the second and third phase of governance.

The executor takes a series of arbitrary function calls to external contracts and encodes them into sequences of call data that are then used in place of a standard strategy's enter, loop, and exit sequences.&#x20;

{% hint style="info" %}
The executor can use a library of adapters to process the return values of external function calls for use as parameters in other function calls in the sequence.
{% endhint %}

To produce a single step of call data from a function call, the contract takes the 4 byte keccak256 encoded function selector and combines it with a set of parameters encoded using the contract ABI specification.

{% hint style="info" %}
You can read the official Solidity documentation to learn more about encoding function calls [here](https://solidity.readthedocs.io/en/latest/abi-spec.html#function-selector).
{% endhint %}

This architecture allows for the development of a drag-and-drop style UI that takes any sequence built by a user and uses the external contract ABIs to create the arrays of call data accepted by the executor contract. Designing strategies with executor contract will dramatically lower the barrier-of-entry for governing strategies by eliminating the need for specialized knowledge of smart contract engineering.

Because of the wide range of possibilities with generic call data execution, safeguards are in place to limit the attack surface. This includes whitelists of external contracts and whitelists of function selectors.&#x20;

## APY Token

APY is our ERC-20 governance token. It will be used to vote on system-wide parameters, changes to strategies in the portfolio, and the inclusion of entirely new strategies. Our governance roadmap covers the different stages of decentralization the platform will undergo as it progresses towards full community ownership. The APY team will make critical decisions with feedback from the community to stay nimble in the early stages of development.

## Liquidity Mining Program

The APY liquidity mining program is an incentive for liquidity providers to deposit their stablecoin into the APY platform. Accounts earn APY tokens for every block they have a deposit in the APY platform. We have allocated 31.2% of the token supply to this purpose and the initial emission rate of rewards started at 30,000 per day.

{% hint style="info" %}
You can read more about our token distribution [here](/getting-started/apy-tokens).
{% endhint %}

Every week the team runs a script to calculate the block-by-block rewards for each account that has deposited into the APY platform. The script uses the following formula to calculate account rewards per block from an amount of rewards issued per second:

$$
r\_{ib}=a(t\_b - t\_{b-1})\frac{v\_{ib}}{\sum\_{j=0}^n v\_{jb}}
$$

Once the script is finished a blob of balances is released in the APY GitHub blob repository.

{% hint style="info" %}
You can view the weekly APY balance blobs [here](https://github.com/apy-finance/apy-blobs).
{% endhint %}

### Vesting Claims Contract

Rewards from the APY liquidity mining program vest over a period of 6 months. Vesting rewards discourages those just looking to sell the tokens, leaving greater rewards available for those that see the long term utility of APY governance.

{% hint style="info" %}
Instructions on how to use the vesting claim contract is available [here](broken://pages/-MKHETUyiyksElWPVW7h).
{% endhint %}

The formula used to calculate the vested rewards for an account is shown below:

$$
v\_i=\sum\_{j=0}^n ar\_i(T-t\_i)-c\_i
$$

The standard vesting contracts used by many projects have high gas costs because they perform all vesting calculations on-chain. Normally performing calculations on-chain allows for greater decentralization, but in the case of vesting contracts, the rewards must still be issued by a centralized admin key.

The APY vesting contract instead uses signature based claims. Vesting calculations are done off-chain and the amounts are signed by an admin key. The resulting signature can be used by an account to process their claim at a much lower gas cost than typical vesting contracts.

The signatures are generated according to the EIP-712 standard using the OpenZeppelin ECDSA implementation. The contract uses a unique domain separator and per-claim nonces to protect against replay attacks. An insufficient domain separator can result in replay attacks stemming from other networks or other contracts. The nonces prevent an account from receiving multiple signatures with increasing rewards unclaimed rewards and then claiming them all at once.

{% hint style="info" %}
You can view the EIP-712 standard [here](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md).
{% endhint %}


# The Convex Index

Broad and diversified exposure to the Convex protocol

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

The Convex Index offers broad and diversified exposure to an integral part of Decentralized Finance, the Curve ecosystem. A user can gain exposure through a single deposit, receiving tokens tracking the index. The index is low-risk, giving consistent returns from liquidity rebates, and useful for diversifying both traditional and crypto portfolios. Periodic rebalancing and reinvestment are optimally executed, greatly reducing the costs associated with the Ethereum blockchain.

## Introduction <a href="#id-7b40yo40o9ze" id="id-7b40yo40o9ze"></a>

With the emergence of cryptocurrencies as a new and promising asset class, many institutional investors are wondering how to gain exposure in a safe manner that does not require significant overhead. “Crypto”, as it is called, is infamous for its lack of user-friendliness, high transaction costs, and constantly shifting environment requiring vigilance against hacks and panics.

From the turmoil, a handful of “blue chip” decentralized finance (DeFi) protocols have emerged unscathed. In particular, Curve Finance, and its symbiote, Convex Finance, together have total liquidity greater than 15% of the total value in DeFi. These protocols rely heavily on fees and rebates generated from providing stablecoin liquidity and offer safer and more consistent returns than outright bets on individual assets such as Bitcoin or Ethereum.

While these opportunities are very much real, for the investor seeking to participate in these protocols, the challenges of ease-of-use and high transaction costs still remain.

The solution we offer is “The Convex Index”, a well-diversified portfolio of Convex positions that gives exposure to the highest quality yield sources in the Curve ecosystem.

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

The following background may be useful as a brief refresher on investment basics and as a common foundation for discussing the Convex Index.

### **The need for diversification**

The saying “don’t keep all your eggs in the same basket” has been known since the 17th century, but until the Nobel Prize-winning work of Markowitz in 1954, it was not generally recognized that multiple baskets could only eliminate certain kinds of risk, *diversifiable risk*. Markowitz showed careful portfolio construction could greatly reduce risk by removing diversifiable risk while maximizing return.

The selection of assets with different exposures and the correlations between them is therefore of primary importance. Additionally, asset managers avoid choosing very similar assets to limit exposure to the same tail risk. An approach that works in both ways is to select across categories, such as economic sectors, or by geography. This can reduce correlation and avoid excessive exposure to the same risk, e.g. US stocks and European stocks are subject to different political regimes, while stocks and government bonds respond differently to monetary policy or global trade conditions.

The needs of an institutional investor are quite different from that of an individual investor. The former is seeking new exposures that complement their existing allocations, ideally providing additional returns while reducing diversifiable risk. It is important that any new exposure be to an instrument that is transparent in design and construction, as otherwise it is difficult to properly manage risk.

### **Building blocks for portfolio construction**

Diversification is of key importance in investing. In an efficient market, you can only expect to be compensated for risk that is non-diversifiable. This explains why financial advisors advocate creating a suitably diversified portfolio; however, lack of access to a variety of markets and instruments has hindered the ability to properly diversify a portfolio. Many large institutions still found themselves handcuffed to mutual funds who charged expensive fees and offered limited liquidity.

This began to change in the 1970s with the birth of index funds, whose sole value proposition was to cheaply track a stock market index such as the S\&P 500. While initially pooh-poohed by mutual fund managers who could not believe people would pay to be “average”, a large body of academic research developed, suggesting that “beating the market” was at best only achieved by a very tiny elite of fund managers. Large institutions increasingly began investing in index funds. Through the popularization efforts of John Bogle and others, retail investors also began to flood the index fund market.

Exchange-traded funds (ETFs) started with the SPDR ETF in 1993 and grew out of the seeds laid by index funds. If an index fund offers investors an inexpensive and convenient exposure to a broad selection of assets, then an ETF is like an index fund “on steroids”. An ETF share is extremely liquid and trades like a stock, unlike an index fund whose shares can only be redeemed at the end of the trading day. The diversity and low-cost of ETFs lets investors easily achieve their chosen mix of risk and reward.

To see the impact of ETFs, consider that for decades common wisdom stated a stock and bond portfolio is beneficially diversified by the addition of commodities; however, access to commodities markets has been difficult for the average investor. With the rise of commodity ETFs, the average retail investor can diversify a stock and bond portfolio with a commodities ETF. Further diversification into real-estate ETFs or other sectors is cheap and accessible, with new kinds of ETFs being created every year.

The low cost, diversity, and flexibility of ETFs lets even active managers engage in tactical tilts or handle rebalancing costs more effectively, while letting more passive managers fill in gaps in their strategic allocations. Not surprisingly, ETFs have grown tremendously in popularity, with currently 3.9 trillion in AUM.

### **The Curve and Convex protocols**

Curve Finance is the largest DeFi protocol with almost 20 billion USD in value locked across multiple chains, which is almost 9.5% of total value locked across all of DeFi.

Curve’s main claim to fame is an extremely low-cost swap between assets that maintain a peg, such as stablecoins. Since the fees are low, Curve incentivizes liquidity providers (LPs) with “rewards” (rebates), not only their own CRV token, but with tokens from partner protocols, such as Compound, Synthetix, Frax, among many others.

Curve also enhances rewards (the “boost”) for LPs who choose to time-lock CRV tokens. In order to achieve the maximum rate of rewards, an LP must typically lock a sizable amount for 4 years. The locked tokens are no longer tradeable and so this represents a significant commitment.

Lockers gain voting power proportional to the time and amount locked. They can vote in weekly gauge votes, which determine the rewards rates for the different Curve pools. They also receive a portion of the fees generated by the platform.

The Convex protocol was created with the goal of maximizing the boost for LPs. Convex continually locks CRV and also participates in gauge votes in an effort to maximize earned CRV. An LP can delegate liquidity shares to Convex, who then earns the enhanced rewards rate and gives the LP boosted rewards minus a suitable fee.

In addition, Convex offers its own rewards for LPs who choose to delegate to them. The CVX token has outperformed the CRV token since inception. The boosted CRV rate and CVX rewards have made Convex the biggest holder of locked CRV (\~50%), with many choosing to delegate their liquidity shares to Convex. The CVX token can also be locked to provide voting power and determine how Convex distributes its votes.

Curve and Convex have both been rigorously audited for security by top firms. APY.Finance has also closely scrutinized their contracts and found them to be very carefully designed and well-written. Neither protocol has ever been hacked nor has any major exploit been found.

## The Index Portfolio <a href="#q7bhunivsozo" id="q7bhunivsozo"></a>

The Convex Index balances diversity, returns, and transaction costs.

### Overview <a href="#l9or7m9n1b9m" id="l9or7m9n1b9m"></a>

A useful index gives broad exposure to a particular category. By “broad exposure”, we mean the opportunity to make the potential returns of the category, without picking winners over losers. The category must be specific enough to constrain the return and risk characteristics of the index. This makes it easier to fit into a portfolio and manage overall performance.

![Figure 1: While US Treasuries have become highly correlated to the S\&P 500, a portfolio of Curve positions offers lower correlation while hedging Bitcoin exposure. (Feb. 2021 - Feb. 2022)](/files/X4JqrzW3X4BkYpsA7r7M)

For the Convex Index, we have focused on the specific strategy of providing liquidity to stablecoin pools, particularly those on Curve, the dominant stablecoin platform. This is an important source of yield for crypto traders, particularly during bear markets. We believe this is a good entrypoint for many institutional investors, as the index’s volatility is not only much lower than that of the mainstay cryptos but offers diversification to them and traditional assets.

|              | Bitcoin | Ethereum | Curve Portfolio | S\&P 500 | Treasuries | 60/40 Portfolio |
| ------------ | ------- | -------- | --------------- | -------- | ---------- | --------------- |
| Volatility   | 74.4%   | 94.3%    | 1.1%            | 12.6%    | 3.7%       | 7.8%            |
| Sharpe ratio | 0.331   | 1.08     | 8.31            | 0.937    | -0.975     | 0.716           |

*Figure 2: A Curve portfolio has less volatility than Treasuries with a compelling Sharpe ratio compared to equities and mainstay crypto (Feb 11 2021 - Feb 17 2022)*

The platform provides exposure to the index by managing a portfolio of liquidity provider positions in Curve (through Convex). A user can buy tokens representing shares of the index. These tokens accrue yield instantly with no additional steps. Since these tokens follow the ERC20 standard, they can easily be managed by a custodial wallet as with other crypto assets following the standard.

The platform is significantly cheaper than managing the components of the index directly. The cost of a deposit into our platform is less than the cost of an allocation to a single Convex position. These costs easily multiply due to rebalancing and the periodic claiming of rewards.

The risks of the Convex Index come from several areas. Fundamentally, there is smart contract risk from APY.Finance, Curve, and Convex. Since rewards are primarily given in CRV and CVX tokens, there is market risk from those tokens, although somewhat limited due to the short duration held before they are reinvested into the portfolio. There is also liquidity risk, as transaction costs and the supply vs demand of stablecoins changes due to overall market conditions, which affects rebalancing. Last but not least, there is stablecoin risk, as each stablecoin has different tail risks that may cause them to deviate from the peg.

### Basket Selection <a href="#fylvk4wvz3rm" id="fylvk4wvz3rm"></a>

Components are selected by filtering the universe of Convex listings with the following series of screens.

#### **Underlying asset USD stability**

The index focuses on delta-neutral returns from USD pegged stablecoin pools. If any assets in the pool show volatility relative to USD they are filtered out. This includes pools with assets pegged to BTC or ETH, and pools that could suffer impermanent loss because they pair a token with ETH.

#### **Annualized pool returns**

The index filters out a subset of the lowest APR Convex listings, which is currently 50% of the full set, that passed the underlying asset USD stability screen. This screen allows sufficient diversity without sacrificing yield.

#### **Slippage**

To ensure efficient rebalancing, the index requires the Curve pool for a Convex listing to have an amplification coefficient high enough to support low slippage for the pool's composition. The higher the value of the coefficient, the more imbalanced a pool's composition can be while supporting slow slippage when depositing or withdrawing.

#### **Pool TVL**

The index filters out Convex listings that have a TVL under a threshold, currently set to $50M, to reduce the risk of insufficient exit liquidity when rebalancing and dilution of returns.

#### **Underlying asset volume**

The index requires accurate pricing from a Chainlink aggregator to calculate index token price. To be included in the index, each underlying asset in the pool must have at least $3M in daily volume otherwise there is a risk of mispricing from market inefficiency.

#### **Depeg risk**

The biggest risk to the index is an underlying asset depegging from USD. Due diligence is done on each underlying asset to analyze the peg mechanics. If there are risks uncovered during the due diligence process, the pool is filtered out.

#### **Discretionary overlay**

The due diligence team reserves the right to veto the inclusion of a pool if there’s a red flag that does not fit into any of the existing screens. Additionally, the community of governance token holders has final approval for inclusion in the form of a governance proposal vote.

### Index Weights and Enhanced Indexing <a href="#id-8a4dnvqua5m" id="id-8a4dnvqua5m"></a>

A score is calculated for each selected Convex listing using a proprietary algorithm that is fed historical data from the corresponding Curve pool. These scores determine the target weights for each listing.

Position sizes often deviate from the target weights to optimize transaction costs. The primary technique for optimizing transaction costs is transaction batching. To resize every position whenever capital is deposited or withdrawn, to keep the index in perfect balance, would have a significant impact on returns due to transaction costs. Instead, positions are resized incrementally, to bring the index closer to the target weights over time.

Similarly, when TVL stays constant, but the weights change, a rebalance of positions may be necessary to match the new target weights. Each potential rebalance between positions is tested for optimal trade execution before it is performed. If the test fails, the rebalance is not performed. The rebalance is periodically retested after failure and will be performed if a subsequent test passes.

When the test fails for an extended period of time, the position size will deviate from the target weights. The index’s preference for low slippage pools helps reduce the necessary deviation caused by enhanced indexing optimization.

Optimal trade execution for a rebalance is tested by calculating the estimated returns from the current date, to the Convex gauge weight voting period end date, for the unbalanced position and the rebalanced position. The difference between these two returns must exceed, by a certain threshold, the slippage and transaction costs of the rebalance between positions.

## The Index Token <a href="#w8r03hc2glqs" id="w8r03hc2glqs"></a>

Currently, users participate in the platform by depositing one of three major stablecoins, USD Coin, Dai, or Tether. In return, they receive tokens representing a share of the index portfolio returns, denominated in the appropriate stablecoin. The majority of user deposits are deployed into the portfolio, leaving only a small remainder for withdrawals. The necessity of keeping funds unallocated for withdrawals creates drag on performance.

Wrapping the Convex Index portfolio in a single index token improves capital efficiency for the platform, reduces cost and complexity for the user, and allows cross-chain Convex exposure. Most users will not interact directly with the platform but buy and sell the index token on exchanges. Participants with sufficient capital to meet the platform’s minimum requirements would deposit and withdraw from the platform to engage in arbitrage and keep the value of the index token pegged to net asset value.

### **Platform Efficiency**

When the primary method for modulating exposure to the Convex Index is exchanging index tokens, there is reduced volume of platform deposits and withdrawals. The benefits are twofold:

1. Lower volume means lower reserve requirements to fulfill instant withdrawals. Because reserve pool capital cannot be deployed to the Convex Index portfolio, it is a primary source of capital inefficiency. Reducing the reserve pool size directly translates to higher returns for the index.<br>
2. Lower volume means less rebalances between reserve pools. This saves on transaction costs and lowers the risk of a forced withdrawal from a Curve pool during a period of high slippage.

### **User Simplicity**

Token swaps are one of the simplest to understand and cheapest DeFi actions a user can perform. Almost any user can figure out how to trade tokens, even if more advanced concepts such as staking, LPing, and collateralization are out of reach. When a user can purchase an index token to include the Convex Index in their portfolio, they no longer need to concern themselves with withdrawal fees, available reserves, boost-lock mechanics, etc.

### **Cross-chain Compatibility**

One of the biggest challenges for cross-chain platforms is the operational overhead from running multiple instances of the platform on each network. An index token with the standard ERC20 implementation can be bridged to any EVM compatible L1 or L2 network to give users on those networks access to the platform without requiring additional platform instances.

An index token also solves the problem of liquidity fragmentation across networks. Liquidity concentrates on the network where the platform is deployed while ownership of the liquidity is distributed across other networks in the form of the index token.

## Index Token Mechanics <a href="#id-3kdq6m4bwgmj" id="id-3kdq6m4bwgmj"></a>

Two groups of users contribute to the index token mechanics: the end-user, and the arbitrageur. The end-user acquires the index token because it has desirable properties that improve the performance of a wide range of portfolios, and the arbitrageur earns a return from the end-user by keeping the index token pegged to the index portfolio performance.

### **End-user**

The end-user rarely exchanges the index token, but holds it for long periods of time. They care about index token liquidity, where it’s listed, and its compatibility with wallets.

### **Arbitrageur**

The arbitrageur frequently exchanges the index token, but holds it for short periods of time. They care about platform features, gas cost, and index portfolio metrics, so they can perform effective arbitrage.

### **Arbitrage Mechanics**

When investors in a traditional ETF purchase shares, they do not deposit capital directly into the fund, they purchase the shares on the market. To keep these shares priced accurately, an ETF has authorized participants that can deposit capital directly to mint new shares, allowing them to arbitrage the shares on the market for a return, and keep the share price pegged.

The index token uses a similar mechanic to hold its peg. Instead of authorized participants, the ability to directly deposit capital is permissionless, allowing any sufficiently sophisticated user to engage in arbitrage for profit.

The arbitrageur has two opportunities, when the index token is trading at a premium and when the index token is trading at a discount.

#### **Premium Arbitrage**

If the market price of the index token is at a premium relative to the index portfolio value, arbitrageurs can mint new tokens by depositing capital directly into the platform. These new tokens are sold on the open market, bringing the price down and earning a return for the arbitrageur.

#### **Discount Arbitrage**

If the market price of the index token is at a discount relative to the index portfolio value, arbitrageurs can purchase the tokens on the open market, which raises the price. These purchased tokens can then be redeemed directly on the platform to withdraw capital equal to the true value of the token relative to the index portfolio, earning a return for the arbitrageur. An arbitrageur needs to be mindful of withdrawal fees and the size of the reserve pools when performing discount arbitrage.

## Platform <a href="#t7k88frtc0z2" id="t7k88frtc0z2"></a>

### Overview <a href="#tt45tssighfm" id="tt45tssighfm"></a>

The smart contracts comprising the platform were built from the ground up to incorporate best practices in securing and managing capital. Different subsystems can only be operated by the relevant administrator role, with each role being protected by a separate multisig wallet.

The flow of funds through the platform is designed so that user deposits move to only one smart contract, the LP Account, which is permitted to only transfer funds to whitelisted destinations, registered Curve or Convex contract accounts. The whitelist registration is controlled by a more privileged multisig than the one operating the LP Account.

The only unauthenticated interactions with the platform happen through the liquidity pools to allow users to deposit and withdraw funds. However, users are limited to withdrawing what is available in reserve pools. At any given time, since most deposited liquidity is being managed by the LP Account, part of the portfolio must be periodically unwound to replenish the reserves for withdrawals. This means an exploit of the liquidity pools can only result in the loss of at most the funds in the reserve pools, a minority of deposited funds.

As the LP Account enters (and exits) positions, it receives (and redeems) tokens from the Curve or Convex protocols that represent deposited funds. These tokens are priced by an innovative Chainlink feed which also aggregates the total value for the portfolio. As yield is accrued by the portfolio, the feed ensures the user’s share appropriately reflects the increased value. The use of Chainlink as an oracle eliminates many dangers associated with blockchain pricing mechanisms, and the dynamic composition of our feed allows us to scale without introducing additional points of failure.

![Figure 1: System architecture](/files/LiqY90IfxZkPqxN4vR2F)

### User deposits and withdrawals <a href="#omgqbn8usepl" id="omgqbn8usepl"></a>

Users can deposit into the platform with any of three stablecoins: USD Coin, Dai, or Tether. For each stablecoin, there is a separate liquidity pool which will create APT tokens for each deposit. The total value of all three types of APT tokens for a user comprises the entire account value for the user. These tokens incorporate the accrued interest from the platform with no additional user actions required.

The amount of APT created for a user deposit is calculated simply to be the same percentage of the total APT created as the deposit as percentage of the pool’s total value. The pool’s total value is comprised of the USD value of its reserve and the USD value of its deployed capital, including any accrued yield. This latter value is tracked using another token, mAPT (see next section).

### Transfers to and from the LP Account <a href="#id-81ag8swqdto6" id="id-81ag8swqdto6"></a>

When sufficient capital has built up in the reserve pools, most of it gets transferred over to the LP Account, with the remainder left to satisfy small withdrawals. The LP Account can also transfer unused capital back to the pools. Periodically capital is unwound from positions and swapped into USDC, DAI or Tether, if needed, to replenish reserve pools.

Every time capital is transferred from a liquidity pool to the LP Account, an amount of mAPT token is created for the pool. The mAPT token allows us to track how much is owed to each pool. When capital is transferred back to the pool, the corresponding amount of mAPT is destroyed.

### Managing positions <a href="#b6wm0dnd4fcj" id="b6wm0dnd4fcj"></a>

A Curve pool allows swaps between any two tokens held by the pool. A liquidity provider (LP) provides the liquidity for swaps by depositing the requisite tokens into the pool. The depositor receives yield-bearing tokens, called “LP tokens”, that entitle the holder to a portion of the liquidity in the pool and any accrued fees. These LP tokens can be deposited into Convex to gain additional liquidity rebates. The result is what we call a Convex position.

A Convex position gains yield from trading fees and additional rebates from protocol tokens. The primary rebates comprising a bulk of the total yield are CRV and CVX tokens. Partner protocols can also contribute rebates, which can be an important source of additional yield (typically greater than the accrued fees, but less than the CRV & CVX yield).

Unwinding (part of) a position requires withdrawing LP tokens from Convex and then removing liquidity from the corresponding Curve pool. The received tokens from the pool may not match the token types needed (for either user withdrawal or adding to a position) and may require swaps.

A Convex position continually earns its rebate tokens. These tokens must be claimed (“harvested”) and then swapped for stablecoins so they can be reinvested into Convex positions.

Consideration of transaction costs for all these operations are crucial as poor execution can easily exceed the gains made during the rebalancing period.

### Tracking and valuing positions <a href="#hwzo3df7hc3" id="hwzo3df7hc3"></a>

As mentioned in the section “User deposits and withdrawals”, in order to create or redeem APT, the pool’s deployed value must properly track the value it is owed by the LP Account.

The deployed value is calculated as the pool’s ownership percentage of total mAPT created multiplied by the Chainlink aggregator’s total value. The Chainlink total value must properly reflect the entire portfolio managed by the LP Account in order to create or redeem APT in the right amounts.

Rather than naively having Chainlink attempt to price all assets held by the LP Account, some of which are rather illiquid, APY.Finance has a system of allocation contracts that works with a custom Chainlink feed to value the entire portfolio.

Each Convex position is decomposed by an allocation contract into liquid base assets which can be safely be priced by Chainlink. Each allocation contract is registered with our Chainlink Registry contract. Chainlink queries this registry to obtain the symbol, balance, and decimal precision of each base asset in the decomposition. Using this information, Chainlink can price each asset balance and return the total value.

## Summary <a href="#id-8x5jut5kgmzi" id="id-8x5jut5kgmzi"></a>

Whether your portfolio is composed of traditional assets or contains crypto assets such as Bitcoin, the Curve and Convex protocols offer beneficial diversification and competitive returns as compared to other safe haven assets.

The complexity of these protocols necessitate having sufficient technical prowess to operate them. Awareness of the dangers of the underlying assets and the protocols being plugged into Curve is critical for proper risk management. Obtaining consistent, compounding returns requires careful execution in order to avoid bleeding from costs.

Our team’s years of experience in traditional and decentralized finance lets us effectively navigate these challenges. The Convex Index’s evolving composition reflects our deep knowledge of Curve and Convex. Our rigorous screening process weeds out risks that may not be readily apparent to those without crypto native fluency.

The platform is designed to minimize loss of funds and role-based access is built into every operation. Efficiency in execution and managing the risk of the portfolio is only possible because of the idea at the heart of the platform: a single pool of liquidity participating in a dynamic portfolio, something not done by any other DeFi platform.


# 2022 Roadmap

The Convex Index 2022 Roadmap

### Phase 0: Foundation \[Complete]&#x20;

* Establish DAO Treasury&#x20;
* Convex Index Litepaper Release

### Phase I: Release&#x20;

* DAO Launch&#x20;
* Convex Index Launch

### Phase II: Upgrade&#x20;

* DAO Profit-Share&#x20;
* Index Token Launch

### Phase III: Scale&#x20;

* Cross-Chain Expansion&#x20;
* Launch New Enhanced Indices


# Liquidity Mining Pool

There are three liquidity pool contracts for APY.Finance. Each contract handles a specific currency and issues its own APT token to represent a user’s stake in the pool. There is a contract for DAI, USDC, and USDT. These contracts are orchestrated by the APY manager to act as a single pool.

The liquidity pool contracts use a proxy pattern for upgradeability. Transactions are sent to the proxy contract address, but the functions they call are from the implementation contract.

Each pool contract is also an ERC-20 token with 18 decimals and the symbol “APT”. The contract is called `APYPoolToken`.

All of the following examples will use web3.js and the DAI liquidity pool contract.

## Adding Liquidity

The transaction sender must first approve the pool proxy contract to transfer their deposit tokens:

```javascript
await daiToken.methods.approve(daiPoolToken.address, daiBalance);
```

Then the sender must call the `addLiquidity` function on the pool contract with the amount of tokens they wish to deposit:

```javascript
await daiPoolToken.methods.addLiquidity(daiBalance);
```

## Removing Liquidity

The transaction sender must first approve the pool proxy contract to transfer their APT tokens:

```javascript
await daiAptToken.methods.approve(
    daiPoolToken.address,
    daiAptBalance
);
```

{% hint style="info" %}
APT represents a share of the pool. The total supply of APT represents the total amount of stablecoin deposited in the pool contract.
{% endhint %}

Then the sender must call the `redeem` function on the pool contract with the amount of APT the wish to redeem:

```javascript
await daiPoolToken.redeem(daiAptBalance);
```

{% hint style="info" %}
Redeeming the entire balance of APT will withdraw the sender’s entire deposit.
{% endhint %}

## Contract Addresses

### Mainnet

| Contract       | Address                                    |
| -------------- | ------------------------------------------ |
| DAI Liquidity  | 0x75CE0E501e2E6776FcAAa514f394a88a772A8970 |
| USDC Liquidity | 0xe18b0365D5D09F394f84eE56ed29DD2d8D6Fba5f |
| USDT Liquidity | 0xeA9c5a2717D5Ab75afaAC340151e73a7e37d99A7 |

### Kovan

The contracts deployed to Kovan use the DAI, USDC, and USDT tokens available from the Aave [faucet](https://testnet.aave.com/faucet).

| Contract       | Address                                    |
| -------------- | ------------------------------------------ |
| DAI Liquidity  | 0xf587EC50e2E6518F7f016d5A78561109Ab96FEa1 |
| USDC Liquidity | 0xA138299A1BB17e90F2edCc2d567358C4BEeCa092 |
| USDT Liquidity | 0x80073EeF3C57Ba05dC25E5cD5b78C5f9fb18e4D8 |

### APYPoolToken ABI

<https://gist.github.com/opz/9d07671b0bc978aba5251e3183bc890c>


# APY.Finance Security

A review of the security measures developed to secure the APY.Finance platform from financial vulnerabilities, hacks and exploits.

## Overview

The APY.Finance platform enables users to earn low-fee and risk-optimized yield by pooling liquidity in a heavily diversified yield farming portfolio.

The yield farming portfolio is managed with a Gnosis Safe referred to as the LP Safe. The liquidity pools collect user deposits and supply them to the LP Safe for yield farming. The oracle system ensures that the yield accrued by the LP Safe is fairly distributed to users by pricing their shares as the TVL increases.

The platform can be broken down into three major systems:

* Liquidity management
* Portfolio management
* Oracle management

These three systems implement the seven major functions of the platform:

* User deposit
* User withdraw
* Fund LP Safe
* Withdraw from LP Safe
* Deploy strategy
* Unwind strategy
* Oracle update

The following sections will cover each system, explain the functions associated with that system, and highlight the security measures put in place to protect the functions in that system.

![](/files/-McQ2oj1LENzxMn1sHGS)

*Figure 1: System architecture*

## Liquidity Management

The focus of the liquidity management system is allowing users to share the liquidity they’ve pooled together. Without this system, any liquidity sent to the LP Safe for yield farming could not be returned to the user with their fair share of earned yield.

The biggest risks to liquidity management are from arbitrage or oracle skew. These risks, if not properly mitigated, could lead to loss of funds from liquidity pools.

The liquidity management system handles:

* User deposit
* User withdraw
* Fund LP Safe
* WIthdraw from LP Safe

Liquidity management is protected with the following security features:

* Same-asset deposit/withdraw
* Withdrawal fee
* Off-chain oracle
* Reserves pools

###

### Liquidity Functions

The two layers of liquidity management are:

* The control of liquidity between users and liquidity pools.
* The control of liquidity between liquidity pools and the LP Safe.

PoolTokenV2 is the interface for users and acts as both the liquidity pool and the liquidity token for users in a pool (APT).

The PoolManager is controlled by the Admin Safe and is able to increase or decrease the liquidity available to the LP Safe by funding or withdrawing from one or more PoolTokenV2. Separating liquidity management from strategy management using the PoolManager as a gateway helps mitigate malicious users from manipulating third party DeFi protocols leveraged by strategies to drain liquidity from the platform.

The same way that APT tracks a user’s share of a liquidity pool, the internal share token, mAPT, tracks a pool’s share of the capital allotted to the LP Safe. This token effectively allows the platform to treat each pool as a user depositing into the LP Safe.

### User Deposit

When a user deposits, their liquidity is transferred to the APY.Finance platform and their share of the platform is tracked using the APT token.

![](/files/-McQ2oj2oQLlLuabbNsN)

*Figure 2: User deposit flow*

1. User calls addLiquidity on a PoolTokenV2.<br>
2. addLiquidity transfers stablecoins from the user to the PoolTokenV2. This is considered the user’s deposit.<br>
3. The OracleAdapter gets the stablecoin prices and TVL by calling latestRoundData on the appropriate Chainlink aggregators.<br>
4. The PoolTokenV2 gets the price of the user’s stablecoin from the OracleAdapter to determine the USD value of the user’s deposit.<br>
5. The PoolTokenV2 uses its balance of stablecoin and the stablecoin price from the OracleAdapter to get the USD value of tokens already in the pool.<br>
6. The PoolTokenV2 calls getDeployedValue on mAPT to get the USD value of liquidity the PoolTokenV2 has sent to the LP Safe.
   1. The TVL from the OracleAdapter is compared to the mAPT balance of the PoolTokenV2 to calculate getDeployedValue.<br>
7. Once the PoolTokenV2 has the USD value of its stablecoin balance and the USD value of stablecoin that it’s sent to the LP Safe, the two values are summed to produce the total liquidity owned by the PoolTokenV2.<br>
8. The USD value of the user’s deposit is compared to the total liquidity to determine the amount of APT the PoolTokenV2 should mint and transfer to the user. The amount of APT minted determines the users share of the pool.

###

### User Withdraw

When a user withdraws, they redeem an amount of APT to receive their fair share of the platform’s liquidity in stablecoin.

![](/files/-McQ2oj3xsbplq7u08El)

*Figure 3: User withdraw flow*

1. User calls redeem on a PoolTokenV2.<br>
2. The PoolTokenV2 burns the amount of APT the user is trying to redeem. The user’s APT balance represents their share of the platform and the amount of APT they redeem is the portion of their share they wish to withdraw.<br>
3. The OracleAdapter gets the stablecoin prices and TVL by calling latestRoundData on the appropriate Chainlink aggregators.<br>
4. The PoolTokenV2 uses its balance of stablecoin and the stablecoin price from the OracleAdapter to get the USD value of tokens already in the pool.<br>
5. The PoolTokenV2 calls getDeployedValue on mAPT to get the USD value of liquidity the PoolTokenV2 has sent to the LP Safe.
   1. The TVL from the OracleAdapter is compared to the mAPT balance of the PoolTokenV2 to calculate getDeployedValue.<br>
6. Once the PoolTokenV2 has the USD value of its stablecoin balance and the USD value of stablecoin that it’s sent to the LP Safe, the two values are summed to produce the total liquidity owned by the PoolTokenV2.<br>
7. The amount of APT redeemed is compared to the total supply of APT and the total liquidity to calculate the portion of liquidity the redeemed APT represents.<br>
8. The PoolTokenV2 uses the stablecoin price from the OracleAdapter to calculate the amount of stablecoin the portion of liquidity represents.<br>
9. The PoolTokenV2 transfers the amount of stablecoin to the user.

####

### Fund LP Safe

The LP Safe manages the yield farming portfolio on behalf of users. It is necessary to fund the LP Safe with liquidity from the liquidity pools so it can be used in the portfolio.

When using this function, it is important that the OracleAdapter is not unlocked until the Chainlink TVL feed is verified to be accurate. Subsequent attempts to fund or withdraw from the LP Safe, without an updated TVL, can cause errors in the amount of liquidity owed to each liquidity pool.

![](/files/-McQ2oj4a279RL0ugOQY)

*Figure 4: Fund LP Safe flow*

1. Admin Safe multisig calls fundLpSafe on the PoolManager.<br>
2. The PoolManager loops through each PoolTokenV2 that will fund the LP Safe and performs the following sequence:
   1. Calculates the USD value of the stablecoin that will be transferred to the LP Safe from the PoolTokenV2.<br>
   2. Calculates the amount of mAPT to mint for the PoolTokenV2 to track its share of liquidity controlled by the LP Safe.
      1. The TVL from the OracleAdapter is compared with the USD value of stablecoin that will be transferred from the PoolTokenV2 to calculate the amount of mAPT to mint.<br>
   3. Transfers the stablecoin from the PoolTokenV2 to the LP Safe.<br>
   4. Mints the calculated amount of mAPT to the PoolTokenV2 to track its share of the liquidity controlled by the LP Safe.<br>
3. The PoolManager calls lock on the OracleAdapter to ensure that no user deposits or withdrawals are processed until the Chainlink oracle has had time to update the TVL aggregator to a new value.

###

### Withdraw from LP Safe

Users can only withdraw stablecoin that is held in a PoolTokenV2. If there is not enough stablecoin in a PoolTokenV2, a portion must be withdrawn from the LP Safe so it can be available to users.

When using this function, it is important that the OracleAdapter is not unlocked until the Chainlink TVL feed is verified to be accurate. Subsequent attempts to fund or withdraw from the LP Safe, without an updated TVL, can cause errors in the amount of liquidity owed to each liquidity pool.

![](/files/-McQ2oj5kNdYvFaA-29P)

*Figure 5: Withdraw from LP Safe flow*

1. Admin Safe multisig calls withdrawFromLpSafe on the PoolManager.<br>
2. The PoolManager loops through each PoolTokenV2 that will withdraw liquidity from the LP Safe and performs the following sequence:
   1. Calculates the USD value of the stablecoin that will be transferred from the LP Safe to the PoolTokenV2.<br>
   2. Calculates the amount of mAPT to burn from the PoolTokenV2 mAPT balance to account for the liquidity that has been returned to the PoolTokenV2 and is no longer controlled by the LP Safe.
      1. The TVL from the OracleAdapter is compared with the USD value of stablecoin that will be transferred from the PoolTokenV2 to calculate the amount of mAPT to mint.<br>
   3. Transfers the stablecoin to the PoolTokenV2 from the LP Safe.<br>
   4. Burns the calculated amount of mAPT from the PoolTokenV2 mAPT balance to account for the liquidity that has been returned to the PoolTokenV2 and is no longer controlled by the LP Safe.<br>
3. The PoolManager calls lock on the OracleAdapter to ensure that no user deposits or withdrawals are processed until the Chainlink oracle has had time to update the TVL aggregator to a new value.

### Liquidity Security

The two main risks to liquidity management are arbitrage and oracle skew. Each of these risks have two security features, the first aims to completely protect the platform from the risk, the second aims to limit the impact of the risk if security failure occurs regardless.

#### Same-Asset Deposit/Withdraw

Users can only withdraw with the same type of stablecoin they used to deposit. This prevents the platform from being used to conduct zero-slippage, zero-fee arbitrage between stablecoins.

#### Withdrawal Fee

A substantial withdrawal fee that stays in effect for 24 hours after a deposit makes all but the most extreme arbitrage opportunities, should they exist, unprofitable. Limiting the withdrawal fee to 24 hours prevents honest users from being impacted by the security measure.

#### Off-chain Oracle

Chainlink is used as the off-chain oracle calculating TVL. The Chainlink TVL feed uses 9 nodes, each pulling data from at least 3 different APIs to mitigate downtime or price corruption. The values are calculated off-chain and then stored on-chain as a static value. This prevents a malicious user from skewing oracle values with flash loans or large amounts of capital and withdrawing more than their fair share of liquidity from the platform.

#### Reserve Pools

Each liquidity pool keeps a portion of TVL in what is referred to as the reserve pool. Users are only able to withdraw from the reserve pool, and the reserve pool can only be replenished when the Admin Safe instructs the PoolManager to withdraw funds from the LP Safe. This security measure limits the amount of liquidity that can be drained from the platform in the event that a malicious user is able to successfully cause oracle skew and withdraw more than their fair share of liquidity.

## Portfolio Management

The purpose of the portfolio management system is to earn yield with pooled user liquidity. This is the part of the platform that interacts with external DeFi protocols.

The biggest risks to the portfolio management system are administrative error and access control vulnerabilities. If the administrative tools used to manage the portfolio are used incorrectly, have errors in their implementation, or if the access control for the portfolio was compromised, it could lead to a loss of funds.

The portfolio management system handles:

* Deploy strategy
* Unwind strategy

Portfolio management is protected with the following security features:

* Gnosis Safe

### Portfolio Functions

The core component of the portfolio management system is a Gnosis Safe referred to as the LP Safe (Liquidity Provider Safe).

After the LP Safe has been funded by the liquidity pools, LP Safe signers can build a sequence of batched transactions that will deploy the liquidity to any DeFi protocol. Once yield has been earned on the deployed liquidity, the LP Safe can also unwind liquidity from any DeFi protocol to supply it back to the liquidity pools.

The portfolio management system benefits from the significant tooling built around the Gnosis Safe contracts. The UI makes it easier for permissioned accounts to manage the platform’s yield farming and the transaction service allows for monitoring of executed transactions.

### Deploy Strategy

Liquidity held by the LP Safe can be deployed to DeFi protocols for the purpose of yield farming in what is referred to as a strategy. Any signer on the LP Safe can batch transactions that, when executed, perform the deployment of liquidity.

![](/files/-McQ2oj6RpwIMp2CSvrM)

*Figure 6: Deploy strategy flow*

1. An LP Safe signer first decides on a DeFi protocol to use for a yield farming strategy.<br>
2. An LP Safe signer builds a transaction with the Gnosis Safe wallet to call lock on the OracleAdapter. This prevents users from making deposits and withdrawals while the LP Safe performs actions that could impact the TVL.<br>
3. An LP Safe signer builds a transaction with the Gnosis Safe wallet to call addAssetAllocation on the TvlManager. The asset allocation added should use a periphery contract, such as Curve.sol, to track the balance of any liquidity the LP Safe will deploy to the DeFi protocol it will use for yield farming.<br>
4. An LP Safe signer builds a transaction batch using the Gnosis Safe wallet that performs the sequence of transactions that adds liquidity, stakes LP tokens, and any other actions required to yield farm with the chosen DeFi protocol.<br>
5. After the transaction batch has been confirmed and sufficient time has elapsed for the Chainlink TVL price feed to update, an LP Safe signer builds a transaction to call unlock on the OracleAdapter to reopen user deposits and withdrawals.

### Unwind Strategy

Liquidity deployed to strategies by the LP Safe can be unwound for either redeployment to another strategy or withdrawal back to liquidity pools. Any signer on the LP Safe can batch transactions that, when executed, perform the unwind of liquidity.

![](/files/-McQ2oj7wT9GSOwKw6NS)

*Figure 7: Unwind strategy flow*

1. An LP Safe signer first decides on an underperforming DeFi protocol for rebalancing or for unwinding in preparation for withdrawal back to the liquidity pool.<br>
2. An LP Safe signer builds a transaction with the Gnosis Safe wallet to call lock on the OracleAdapter. This prevents users from making deposits and withdrawals while the LP Safe performs actions that could impact the TVL.<br>
3. If a strategy is being completely unwound, an LP Safe signer might build a transaction with the Gnosis Safe wallet to call removeAssetAllocation on the TvlManager. This asset allocation will no longer be used when the oracle system calculates TVL.<br>
4. An LP Signer builds a transaction batch using the Gnosis Safe wallet that performs the sequence of transactions that unstakes LP tokens, removes liquidity, and any other actions required to exit the chosen DeFi protocol.<br>
5. After the transaction batch has been confirmed and sufficient time has elapsed for the Chainlink TVL price feed to update, an LP Safe signer builds a transaction to call unlock on the OracleAdapter to reopen user deposits and withdrawals.

### Portfolio Security

Because the portfolio management system is controlled heavily by governance, the main risks come from administrative error and access control vulnerabilities. The primary way these risks are mitigated are through the use of a Gnosis Safe.

#### Gnosis Safe

All yield farming strategies are run through a Gnosis Safe referred to as the LP Safe. The Gnosis Safe has several features that make it ideal for mitigating risk to the platform management system.

**Transaction Builder**

The Gnosis Safe wallet allows signers to build transactions and interact with DeFi protocols in an intuitive way without requiring scripts. This reduces the chance of administrative error where a signer executes a faulty transaction that leads to a loss of funds.

**Transaction Service**

The Gnosis Safe transaction service logs transactions executed by the Safe. Being able to view past transactions that have been executed will allow signers to detect if failures have occurred and avoid executing transactions out of order, thereby reducing the chance of administrative error.

**Asset Dashboard**

The Gnosis Safe wallet contains a dashboard where a signer can view all the assets held by a Safe and their USD value. This assists signers in tracking the yield farming strategies currently deployed and reduces the chance of administrative error where a signer forgets to add a particular asset allocation.

**Secure Code**

The Gnosis Safe has been audited and is widely used in the industry without incident. This reduces the likelihood that there is an access control vulnerability in the code.

## Oracle Management

The purpose of the oracle management system is to price user shares of the liquidity pools. Without the oracle system, users would never be able to recover their share of liquidity or receive their share of the yield.

The biggest risks to the oracle management system are front-running, Chainlink failure, and failure to calculate the full TVL. Any one of these risks could lead to a loss of funds. Oracles are mission critical to DeFi platforms and are also one of the most commonly exploited components. The most devastating hacks in the DeFi industry have targeted vulnerable oracles.

The oracle management system handles:

* Chainlink oracle update

Oracle management is protected with the following security features:

* Oracle locks
  * Failure locks
  * Asset allocation locks
  * Funding locks
  * Manual time locks
* Manual override

### Oracle Functions

The oracle management system has two major responsibilities:

* Providing stablecoin prices
* Calculating TVL

Both of these responsibilities are primarily powered by Chainlink nodes. Stablecoin prices are pulled from data provider APIs then pushed to aggregators. TVL is calculated by the Chainlink external adapter using the TvlManager, then pushed to the TVL aggregator. It is important to note that this TVL excludes stablecoin that is undeployed and held in the liquidity pools.

Because the TVL can comprise many different assets, farming pools, and staked tokens, the platform uses the TvlManager to track everything with a set of structs referred to as asset allocations. Each asset allocation represents a balance of underlying assets that can be priced by a data provider. Liquidity tokens, for example, often do not have a queryable price, and must therefore be broken down into the underlying assets they represent. The TvlManager uses periphery contracts, such as contracts/periphery/Curve.sol and contracts/periphery/Aave.sol, to decompose these underlying asset balances.

Because Chainlink nodes are an asynchronous off-chain process from the rest of the platform, any dependencies the platform has on Chainlink must be carefully implemented to prevent the possibility of race conditions.

### Chainlink Oracle Update

Oracle updates originate with the off-chain Chainlink node. The nodes check either stablecoin prices or TVL every minute and if the value has deviated by at least 1% from the previous recorded value, or it has been more than 24 hours since the last update, a new Chainlink oracle round will start. Once enough nodes have submitted a value, the round ends and the median value is pushed to the aggregator.

The Chainlink external adapter totals the value of all the asset allocations registered with the TvlManager to calculate the TVL. It is critical that all value in the platform, except for stablecoin held in the liquidity pools, is represented as asset allocations. It is necessary to exclude the liquidity pools from the TVL to properly calculate mAPT mint amounts.

![](/files/-McQ2oj8lVnTOTSiygvI)

*Figure 8: Oracle update flow*

1. Chainlink nodes detect a deviation of greater than 1% from the last recorded aggregator value.<br>
2. Oracle round begins and Chainlink nodes submit values. Stablecoins are priced using multiple data providers and TVL is calculated from asset allocations stored in the TvlManager. The following process calculates TVL:
   1. The Chainlink external adapter calls getAssetAllocationIds on the TvlManager to get a list of IDs for every registered asset allocation.<br>
   2. The Chainlink external adapter loops through each ID and calls balanceOf, decimalsOf, and symbolOf to retrieve data for that asset allocation.<br>
   3. The asset allocation symbol is used to look up the price of the asset from the asset allocation from one of the available data providers.<br>
   4. The balance of the asset allocation is multiplied by the price of the asset to get the USD value of the asset allocation.<br>
   5. All the asset allocations are summed to get the TVL.<br>
3. The round can complete if enough nodes have submitted values. The median value is taken and recorded in an aggregator.

### Oracle Security

The risk of front-running and failure to calculate the full TVL, is a result of Chainlink’s asynchronous nature and is mitigated by oracle locks. The risk of Chainlink failure is a result of relying on a third party dependency and is mitigated by manual overrides.

### Oracle Locks

Oracle locks are an essential feature used to secure the oracle management system. If a platform operation is performed that could have a significant impact on TVL, it is necessary to lock oracle dependent features until Chainlink has had the time to detect the change and run a new round. The most common scenarios for this risk is when funding or withdrawing from the LP Safe, and adding or removing asset allocations.

The reason time-limited oracle locks are used instead of checking for the last oracle update time is because there are valid situations in which a lock should be used as a precaution, but the TVL will not deviate over the threshold required for an update. To avoid the possibility of a DoS, all locks have a time expiry.

There are four different types of locks that have been used to safeguard the oracle management system:

#### **Failure Locks**

When the Chainlink aggregator returns an invalid value (either a zero or a negative number), reverts when called, or has not had an update in over 24 hours the OracleAdapter will automatically lock. These locks do not need an expiry because they result from unambiguous on-chain conditions. When the conditions resolve, the OracleAdapter will be automatically unlocked.<br>

**Asset Allocation Locks**

When a new asset allocation is added, or an existing one is removed, it could impact the TVL calculation because there is a change to balances being summed by the Chainlink external adapter. The OracleAdapter automatically locks for the default lock period, which is specified in the number of blocks, when there is a change in asset allocations.

**Funding Locks**

When the PoolManager funds the LP Safe or withdraws from the LP Safe, it could impact the TVL calculation because the liquidity pools are not tracked by the TvlManager. The OracleAdapter automatically locks for the default lock period when there is a fund or withdraw from the LP Safe.

**Manual Time Locks**

There are conditions that are not automatically detectable in which the OracleAdapter should also be locked. It is possible for the LP Safe to manually lock the OracleAdapter for a specified period of blocks. During normal system operation, an LP Safe signer should ensure that the OracleAdapter is manually locked before performing batched transactions to interact with other DeFi protocols.

### Manual Override

In the event of price feed corruption, the Chainlink aggregators will appear to have valid values, but the values could be skewed or at extreme ranges, such as a maximum integer value or the smallest decimal value when adjusted for decimal places. When this happens, it can lead to a loss of funds if a malicious user takes advantage of the discrepancy between the reported TVL or stablecoin price, and the actual values.

To mitigate the impact of price feed corruption, the OracleAdapter allows the Admin Safe to manually set override values for both stablecoin prices and TVL. Override values have an expiry and while they are in effect, they supersede all other OracleAdapter return values with the exception of a manual time lock.

###


# Boost-Locking

Boost-Locked APY and Enhanced Liquidity Mining Rewards: Technical specifications

Boost-Locked APY (blAPY) is an ERC20-like contract that will allow APY token holders to lock APY tokens for a specified duration in return for an amount of blAPY reflecting lock amount and duration.

This allows for various applications, including additional voting strength, reduction of current and future platform fees, and the first proposed application: enhancing liquidity mining (LM) rewards. Any application where using a quantified measure of user commitment makes sense may benefit.

Enhancing LM rewards will reward users who have explicitly demonstrated a long-term commitment to the vision of APY.Finance. Each user will be assigned a boost score, a weighted average between their usual deposit value and a proportion of TVL based on their blAPY share. The boost score will be used in lieu of deposit value to calculate the share of the rewards.

In the best case scenario, users who maximize their blAPY will enjoy a 2.5-times greater reward than users with the same deposit value who have no blAPY. Boosted yield amount will depend on the overall actions taken by all users, as rewards earned are proportional to the total sum of boost-locks. In order to keep their enhanced rewards, users will need to continually maintain their blAPY balance by extending the lock or increasing the amount locked.

## Escrow contract

APY.Finance will deploy an escrow contract, based on an audited VotingEscrow contract used by Curve. Slight modifications have been made by APY.Finance to allow users to withdraw in an emergency shutdown.

A user locks a specified amount of APY into the escrow for a specified lock period. This results in a blAPY balance which represents a user’s commitment to the project.

In the event the community decides to cease usage of the contract, the (protected) shutdown function can be called. When the contract is shutdown, users will not be able to create or add to their blAPY, but they will be able to withdraw their locked APY, terminating any existing lock.&#x20;

## blAPY

A user’s blAPY balance is based on: \
1\. Amount locked up \
2\. Time until lock expiry

More precisely,

blAPY balance = locked APY amount \* (time to lock expiry / max lock duration)

where max lock duration is 4 years.

**Examples:** \
100 APY deposited for 1 year → 100 \* (1 year / 4 years) = 25 blAPY \
200 APY deposited for 6 months –> 200 \* (0.5 year / 4 years) = 25 blAPY \
100 APY deposited for 4 years → 100 \* (4 years / 4 years) = 100 blAPY

Note that a smaller locked amount can be compensated for by a larger lock duration and a smaller lock duration can be compensated for by a larger locked amount.

Your blAPY balance will decrease over time as the lock expiry approaches:

**Example:** \
100 APY deposited for 1 year now gives 25 blAPY.\
In 3 months, you will have 100 \* (1 year - 3 months) / 4 years = 100 \* (0.75 / 4) = 18.75 blAPY.\
In 6 months, you will have 100 \* (1 year - 6 months) / 4 years = 100 \* (1 - 0.5) / 4 = 12.5 blAPY.

In order to maintain or increase your blAPY balance, you will need to extend the lock expiry or increase the locked amount. Lock durations can be selected (and later increased) in increments of 1 week but the expiry can never be more than 4 years in the future.

## Weekly Rewards Generation and the Boost Score

For the first incentive based on blAPY, we propose to adjust the current calculation for weekly rewards generation by incorporating a user’s blAPY into their proportional share of the rewards.

Current calculation for weekly rewards :

User’s weekly rewards = (user APT value / TVL) \* weekly emissions rate

Proposed, new calculation for weekly rewards:

User’s weekly rewards = (user’s boost score / total boost score) \* weekly emissions rate

where

**Lock score** = min( 0.4 \* user APT value + 0.6 \* TVL \* (blAPY Balance / blAPY Total Supply), user APT value)

and

**Total lock score** = sum of all user lock scores

A user’s *relative lock score*, i.e. user lock score / total lock score, is what actually determines the earned portion of the emitted rewards. However, it can’t be known at a given time without knowing the decisions of all other users at the same time.

A user’s boost is defined as:

**Boost** = user lock score / (0.4 \* user total APT value)

```
Relative boost = user relative lock score / (user total APT value / TVL)
```

Note that the boost has a minimum value of 1 and a maximum value of 2.5. The relative boost also has a max of 2.5 but can be below 1, e.g. the situation when everyone has the max boost except you.


