# YieldBlox Documentation

### Welcome!

This is the YieldBlox documentation page. Your place for all things related to the YieldBlox protocol -- a DeFi money market protocol built on [Stellar](https://www.stellar.org) using [Stellar Turrets](https://turrets.stellar.org).

#### What you'll find here:

* [User Documentation](/user-docs/general)

  Information on how the protocol works, answers to questions you may have, and useful visuals\\
* [Technical Documentation](https://github.com/script3/yieldblox-docs/blob/master/broken-reference/README.md)\
  Protocol entities, equations, and protocol information\\
* [Resources](/resources/technical-resources)\
  Developer resources, external audits, contact information, social media, and YieldBlox logos and emotes

Explore the docs to find out more!


# General

## What is YieldBlox?

YieldBlox is a decentralized finance (DeFi) protocol for lending and borrowing built on [Stellar](https://www.stellar.org). Users carry out all protocol functions using YieldBlox's smart contracts hosted on [Stellar Turrets](https://tss.stellar.org). These can be accessed either directly using API calls, or through a front-end such as Script3's [YieldBlox web app](https://www.yieldblox.finance/).

## What is a decentralized finance protocol?

A decentralized finance protocol is a financial application that does not rely on or require its users to trust a central intermediary. This is often achieved by building the protocol using immutable smart contracts that run on a distributed network. In YieldBlox's case, it operates using smart contracts built with the Stellar Turrets smart contract engine. There is no central organization that controls YieldBlox and no organization YieldBlox relies on to continue operating. This means that YieldBlox is non-custodial, trust-minimized, and censorship-resistant.

## What is unique about YieldBlox?

The DeFi money market landscape is competitive. There are a variety of money market protocols built on programmable blockchains like Ethereum and Solana. Nevertheless, YieldBlox has made several improvements on existing money market protocol models and created a unique offering.

**Platform Focus**

Stellar is a unique blockchain in that it's an ideal backend for fintech platforms. It's easy for a small team to spin up a mobile application and plug into the Stellar network to provide their users with payment and trading capabilities. YieldBlox was built with these platforms in mind. Platforms can use YieldBlox to provide their users with lending and borrowing tools without reducing the decentralization of their platform. In addition, platforms can leverage YieldBlox's unique tokenomics model and isolated lending markets to bootstrap growth of their own platform, ease anchor adoption, and build a non-custodial revenue model. A further discussion of this potential can be found in [this article](https://medium.com/script3/yieldblox-will-transform-capital-and-incentives-in-the-stellar-ecosystem-828be5023765) written by Script3.

**High Capital Efficiency**

For money markets, high capital efficiency is directly correlated with high utility. The higher a money market protocol's capital efficiency is, the more useful deposits are for users. The most straightforward way to increase capital efficiency is by increasing the loan-to-value ratios offered by the protocol. However, this comes with an increased risk of underwater positions. YieldBlox's unique [Default Protection](/user-docs/lending-borrowing/default-protection) mechanism greatly reduces the risk that underwater positions pose, allowing the protocol to safely offer high loan-to-value ratios.

**Unique Tokenomics**

Tokenomics, when designed correctly, are an invaluable tool for a DeFi protocol. YBX, YieldBlox's utility token utilizes a [five-level tokenomics model](/user-docs/ybx-tokens/ybx-tokenomics) that touches every portion of the protocol.

**Built on Stellar**

YieldBlox is the first DeFi protocol built on Stellar. Stellar is an excellent platform for DeFi protocols with extremely fast transactions, low fees, and an ecosystem that is well equipped to tokenize real-world assets. Additionally, Stellar's focus on developing countries means YieldBlox will be able to serve a user base that has traditionally been hard for DeFi protocols to tap into.

## What are the benefits of YieldBlox?

YieldBlox brings a decentralized, on-ledger money market to the Stellar ecosystem.\
Within the ecosystem, this promises to:

* Increase and trading payment liquidity
* Improve capital productivity
* Reduce reliance on lending intermediaries like banks
* Serve a global market with a cost of less than $0.01 per transaction

## How do I use YieldBlox?

Script3 maintains a [web app](https://testnet.yieldblox.finance) that allows users to interact with the protocol.

The web app currently supports the following wallets:

* [**Freighter**](https://www.freighter.app)
* [**Albedo**](https://albedo.link)

As other interfaces begin to integrate YieldBlox, a list of these integrations will be shown here!

***

More technical users can also use YieldBlox directly through the Turret network that supports it. Please see the [Stellar Turrets documentation](https://turrets.stellar.org) and the technical-docs section for more information.

## Does YieldBlox have fees?

While they are very small, YieldBlox does have four types of fees:

**Network Fees**

YieldBlox users must pay [Stellar Network fees](https://developers.stellar.org/docs/glossary/fees/) and Stellar Turret fees for each transaction. Both of these fees are extremely low. We expect them to amount to less than one cent (< $0.01) per transaction.

**Interest Rates**

Borrowers on YieldBlox must pay [interest fees](/user-docs/lending-borrowing/interest-rates) to lenders. These fluctuate based on demand.

**Withdrawal Fees**

YieldBlox users must pay [withdrawal fees](/user-docs/lending-borrowing/lending) when they withdraw assets from the protocol. These are paid to the YieldBlox DAO treasury

**Liquidation Fees**

YieldBlox liquidators must pay [liquidation fees](/user-docs/lending-borrowing/liquidations) when they liquidate another user. These are a small portion of the liquidation incentive that they receive for the liquidation, they are paid to the YieldBlox escrow pool.

## Can YieldBlox be changed or upgraded?

Yes. The YieldBlox protocol can be changed or updated using the [governance](/user-docs/governance) model.

## How does governance work?

The YieldBlox protocol is updated and maintained using a [governance](/user-docs/governance) token model. Users receive [YBX tokens](/user-docs/ybx-tokens) for lending or borrowing, and these tokens can be [escrowed](/user-docs/escrowing) and then used to make and vote on protocol updates and changes.

## What's a YBX token?

[YBX](/user-docs/ybx-tokens) is YieldBlox's platform token. It is issued to those who use the protocol, and can be [escrowed](/user-docs/escrowing) to propose and vote on [governance](/user-docs/governance) proposals that modify the protocol.

## Are there risks when using YieldBlox?

Using any application involves risk. There are four main risks user's should consider when using YieldBlox.

**Smart Contract Risk**

YieldBlox functions using smart contracts. If a bug was discovered and exploited it could result in loss of user funds. To mitigate this risk, the YieldBlox Protocol is currently seeking third-party audits, and will have a bug bounty to further ensure security.

**Turret Protocol Risk**

Yieldblox's smart contracts are built using the Stellar Turret's protocol. If a vulnerability was discovered in Turrets it could result in loss of user funds. More information on turret risks and an audit of the turret's protocol can be found on the [Stellar Turrets website](https://turrets.stellar.org).

**Malicious Turret Host Collusion**

The Stellar Turret's protocol functions by uploading a smart contract to a set of turret's hosted by trusted organizations in the Stellar ecosystem. Each of these hosts creates a unique signing keypair that is associated with the smart contract. The protocol associated with the uploaded smart contract then adds these keypairs as signers to the protocol accounts that must be controlled by the smart contract using whatever signature structure they deem appropriate. When a user runs the contract by sending a request to a turret the turret builds and signs a Stellar transaction XDR based on the smart contract and returns the XDR and signature to the user. The user then attaches as many signatures as necessary to reach the protocol account's [signing threshold](https://developers.stellar.org/docs/glossary/multisig/#thresholds) to one of the returned XDRs and submits it to the network.

The catch is that turret signing keys can sign transactions without the smart contract being ran. The smart contract is more of an instruction set for turret coordination rather than a strict rule set. Therefore, if turret hosts were to become malicious, they could collude to sign malicious transactions. More information on this risk can be found on the [Stellar Turrets website](https://turrets.stellar.org). YieldBlox mitigates this risk by only using turrets hosted by trustworthy ecosystem organizations and by requiring the majority of turrets to sign a transaction before it can be accepted by the network. Furthermore, the YieldBlox governance system can replace a turret on short notice should the turret become unreliable. More details on the Turrets supporting the YieldBlox protocol can be found in the developer docs section.

**Stellar Decentralized Ledger Risk**

As with all decentralized ledgers Stellar comes with its unique set of risks. You can read more about the Stellar Consensus Protocol and it's risks [here](https://developers.stellar.org/docs/glossary/scp/).


# Lending & Borrowing

![](/files/-MfiyWrovfkj4fvisGF8)

Lending and borrowing are the core functionalities of YieldBlox. Users can deposit assets into the YieldBlox protocol where they are lent to a variety of borrowers. Borrowers use their lent assets as collateral to borrow other assets. They pay interest to the protocol which distributes it to lenders.

Learn more about lending and borrowing on YieldBlox:

* [**Lending**](/user-docs/lending-borrowing/lending)\
  The basics of lending on YieldBlox, including how it works, what pool tokens are, and more!<br>
* [**Borrowing**](/user-docs/lending-borrowing/borrowing)\
  The basics of borrowing on YieldBlox, including how it works, what collateral is, and repayment.<br>
* [**Interest Rates**](/user-docs/lending-borrowing/interest-rates)\
  How interest rates work and how to change them.<br>
* [**Health Factors**](/user-docs/lending-borrowing/health-factors)\
  What a health factor is and how to increase it.<br>
* [**Liquidations**](/user-docs/lending-borrowing/liquidations)\
  Describes what liquidations are and how they work on YieldBlox.<br>
* **Proposed Future Features**
  * **Isolated Lending Pools**
  * **Token Delegation**
  * **Lines of Credit**\
    How YieldBlox facilitates lines of credit.


# Lending

## How does lending work on YieldBlox?

Lenders provide assets to the lending pool and receive interest in return. Borrowers can [borrow](/user-docs/lending-borrowing/borrowing) these assets by posting [collateral](/user-docs/lending-borrowing/borrowing#what-is-collateral) and paying interest at loan repayment.

Loans can be taken out for any time period, as long as the user maintains an account [health factor](/user-docs/lending-borrowing#whats-a-health-factor) above 1.00. If the accounts health factor falls below 1.00, the accounts loans can be [liquidated](/user-docs/lending-borrowing/liquidations) by another protocol participant until their account health factor increases to 1.02.

When a lender deposits money in the YieldBlox protocol, they receive pool tokens that act as a certificate of deposit. These tokens track the [proportion of the pools lending balance](/technical-docs/math#pool-token-issuance) that the user owns. Users can burn these token at any time to withdraw their lent assets and all accrued interest.

## What are pool tokens?

When users deposit assets into the YieldBlox lending pool, they receive pool tokens which represent their [share of the balance](/technical-docs/math#pool-token-issuance) of that asset in the lending pool. This is a sort of certificate of deposit. These tokens are Stellar assets, so they are transferrable and tradeable. The amount of underlying assets associated with these pool tokens increases over time, as borrowers pay interest into the lending pool. Lenders can burn these tokens to [withdraw their lent assets](/technical-docs/math#asset-payout) along with their share of the interest accrued by the pool. Because interest is paid back into the pool, lenders' interest yields are auto-compounded.

Pool tokens are also used as collateral. Borrowers collateralize pool tokens they receive from depositing assets in the lending pool. Once they repay their loan (or a portion of their loan), they can withdraw their collateralized pool tokens (or a portion of their collateralized pool tokens). Because pool tokens are used as collateral, YieldBlox can lend the underlying assets associated with collateralized pool tokens. As a result, borrowers receive interest on collateral deposits.

## Why would users lend on YieldBlox?

In exchange for lending with YieldBlox, lenders receive interest from borrowers and [YBX](/user-docs/ybx-tokens#how-do-i-get-ybx-tokens) issuance from the protocol. In addition, when lending on YieldBlox, users retain control of their funds. The protocol is decentralized, trust-free, and non-custodial. Only the protocol smart contracts have control over user funds, and users can withdraw their funds at any time.

Lenders should note that to receive YBX issuance, they must deposit the pool tokens they received from lending as collateral.

## What is the interest rate for lending on YieldBlox?

Lending interest rates equal the *borrowing interest rate* multiplied by the *utilization ratio* since interest paid by borrowers is distributed proportionally to lenders. Borrowing interest rates are [demand-based](/user-docs/lending-borrowing/interest-rates#how-do-loan-interest-rates-work) and calculated using the utilization ratio. This means borrowing interest rates increase as the percentage of protocol assets lent to borrowers increases. Currently, an asset's borrowing interest rate ranges from 5% at 0% utilization to over 100% at 97%+ utilization. However, [governance proposals](/user-docs/governance) can modify the rate at which interest rates adjust based on utilization rates.

## How do lenders receive interest?

Borrowers pay their accrued interest into the lending pool when they repay their loan. When lenders withdraw their lent assets, they also withdraw their share of the interest earned by the pool. This works because interest is paid into the lending pool and pool tokens represent a user's share of the pools balance of the lent asset. So, when interest is paid into the pool, the [amount of the underlying asset](/technical-docs/math#asset-payout) associated with a pool token increases.

## Who controls my lent assets?

You do! Assets lent to the protocol are controlled by YieldBlox's smart contracts. Therefore, you can use those smart contracts to withdraw your lent assets at any time.

## What assets can be lent?

Any Stellar-based asset approved by [protocol governance](/user-docs/governance) can be lent with YieldBlox. More assets will be added to the protocol over time through governance proposals voted on by YBX holders.

## How do lenders withdraw lent assets?

Lenders can withdraw assets by using YieldBlox's smart contracts to burn the pool tokens they received for lending assets. Doing so will also withdraw all interest the lender has accrued. Withdrawing assets from the protocol also incurs a small [withdrawal fee](#What-are-withdrawal-fees?)

## What are withdrawal fees?

When lenders withdraw assets from YieldBlox by burning pool tokens they pay a small withdrawal fee to the protocol. This fee is sent to the YieldBlox DAO treasury account. The fee amount is set by [Yieldblox Governance](/user-docs/governance)

## Is there any situation where lenders can't withdraw assets?

If an assets utilization ratio is too high, there may not be sufficient liquidity for a lender to withdraw assets because too much of the asset balance is currently lent out. However, due to YieldBlox's [demand-based interest rate model](/user-docs/lending-borrowing/interest-rates), this is extremely unlikely. Interest rates are extremely high (over 100%) at high utilization ratios, which heavily incentivizes borrowers to repay their loans and new entities to lend to the protocol, thus adding liquidity and lowering the utilization ratio.


# Borrowing

## How does borrowing work on YieldBlox?

When borrowing, users deposit assets into the lending pool and withdraw assets they wish to borrow from the pool. To repay, the borrower returns the borrowed assets to the lending pool. Then they are allowed to withdraw their collateral if they choose.

## What is collateral?

Collateral is the assets the borrower pledges to secure the repayment of a loan. If a loan ever becomes undercollateralized, meaning its repayment is at risk, the loan is liquidated, and a portion of the borrower's collateral is forfeited. YieldBlox uses [pool tokens](/user-docs/lending-borrowing/lending#what-are-pool-tokens) as collateral. This means that borrowers will receive interest on their collateral deposits!

## What is accepted as collateral?

Any asset on [Stellar's network](https://developers.stellar.org/docs/start/introduction/) that has been approved by protocol [governance](/user-docs/governance) can be converted into pool tokens and used as collateral.

## How much collateral do I need?

Borrowers must have a [health factor](/user-docs/lending-borrowing/health-factors) of above 1.10 after loan origination in order to borrow assets from YieldBlox. They must maintain a health factor of above 1.00 in order to avoid liquidation. Health factors are based on a collateral assets loan-to-value ratio, so collateral requirements vary depending on the asset the user is collateralizing. Loan-to-value ratios are set by governance proposals, so they can change.

## What happens to the collateral?

The assets provided for collateral are converted into pool tokens, so they can be lent out. This allows borrowers to generate interest on their collateral deposits. These pool tokens are then locked in claimable balances claimable by only the pool account. Collateralized pool tokens can be reclaimed by the borrower once they repay their loan. In the case of a liquidation, liquidators will withdraw the collateralized [pool token](/technical-docs/math#pool-token-issuance) rather than its associated underlying asset.

## How do I repay my loan?

Borrowers repay loans by returning all borrowed assets and accrued interest to the YieldBlox lending pool. After doing so, they can withdraw their collateral deposits if they wish.

## Can borrowers repay only part of their loan?

Yes! Borrowers can repay portions of loans at any time. Doing so also lowers their collateral requirements allowing them to withdraw collateral if they wish to.

## Can I repay my loan with collateral?

Yes! YieldBlox enables borrowers to repay loans with collateral. To do so, the collateral balance will be sold for the underlying borrow asset and used to repay the loan. Users must specify the [path payment](https://developers.stellar.org/api/resources/operations/object/path-payment-strict-send/) each collateral balance takes to become the underlying borrow asset.


# Interest Rates

## How do loan interest rates work?

YieldBlox's interest rates are based on demand and will fluctuate based on the borrowed assets utilization ratio. Interest rates accrue onto the borrower's liability balance over the lifecycle of their loans. Interest does not need to be repaid until loan repayment.

## What is a Utilization Ratio?

An assets [utilization ratio](/technical-docs/math#utilization-ratio-calculations) is the percentage of deposited assets in the pool that are currently lent out. It is used to calculate the [variable interest rate](/technical-docs/math#interest-rate-calculations) paid by borrowers.

## Where do the interest fees go?

The fees generated by interest are paid to the lending pool. Lenders will receive these fees when they burn the pool tokens they received by lending.

Additionally, the underlying assets YBX fee allocation value is greater than 0, a corresponding portion of interest fees are used to repurchase and distribute YBX to [YBX escrows](/user-docs/escrowing). For example if an assets YBX fee allocation is set to .1, 10% of interest paid by borrowers of that asset is used to purchase YBX and send it to the YBX escrow pool, which will distribute the YBX to escrows when they burn their veYBX upon escrow unlock. YBX fee allocations are set by [YieldBlox Governance](/user-docs/governance).


# Health Factors

## What's a health factor?

An account's *health factor* is a measure of the account's collateralization levels. It is based on the account's total liability value, collateral value, and collateral liquidation factors.

To originate a loan, a user must ensure their health factor will be above 1.10 after the loan has been originated. If a user account's health factor falls below 1.00, their positions can be liquidated until their health factor reaches 1.02. See a rough health factor scale below:

![](/files/Uyyn267Mtrzk1qDLrmgv)

An accounts health factor is calculated with a user's liability value (outstanding loan value + accrued interest), collateral value, and the loan-to-value ratio of their collateral[this formula](/technical-docs/math#health-factor).

$$
H=\frac {\sum^{|C|}*{i=1}LtVi\*V*{ci}} {\sum^{|L|}*{i=1}V*{li}}
$$

Where:

* $$H=$$ the account's health factor
* $$|C|=$$ the number of collateralized assets held by the account
* $$LtV\_i=$$ the loan-to-value ratio for collateral asset $$i$$
* $$V\_{ci}=$$ the collateral value of collateral asset $$i$$
* $$|L|=$$ the number of outstanding loans held by the account
* $$V\_{li}=$$ the liability value of loaned asset $$i$$

Liquidation factors are assigned to supported assets by the protocol, and they govern the point at which an account's positions can be liquidated.

## How can I increase my health factor?

A user can increase their health factor by depositing more [collateral](/user-docs/lending-borrowing#what-is-collateral) or decreasing their liability value (e.g. repaying their loans).


# Liquidations

## What is a liquidation?

If a borrower's loan becomes undercollateralized (their [health factor](/user-docs/lending-borrowing#whats-a-health-factor) falls below 1.00), another protocol user can repay a portion of the borrower's debt in exchange for a portion of their collateral. This is known as [liquidation](/technical-docs/math#maximum-liquidation-amount).

## When would a borrower be liquidated?

Borrowers can be liquidated if their account's health factor falls below 1.00. The [health factor](/user-docs/lending-borrowing#whats-a-health-factor) is a measure of an account's collateralization levels.

## How do YieldBlox liquidations protect borrowers?

Being liquidated is never fun. YieldBlox protects borrowers [by only allowing liquidators to liquidate the borrower's position to the point where their health factor reaches 1.02](/technical-docs/math#maximum-liquidation-amount). This minimizes liquidation amounts ensuring that the borrower loses the smallest amount of collateral possible.

## Who liquidates the borrowers?

Any other protocol user may liquidate borrowers. The borrower can only be [liquidated to the point where their health factor reaches 1.02](/technical-docs/math#maximum-liquidation-amount). Because of this, borrowers are unlikely to have their positions fully liquidated.

## What incentivizes liquidators to liquidate undercollateralized borrowers?

To incentivize liquidations of undercollateralized accounts, liquidators receive a discount on the assets they withdraw from the borrower's collateral based on the collateralized asset's liquidation incentive. For example, if a liquidator repays 100 USD of a borrower's position, and the borrower's collateral has a liquidation incentive of 1.05, the liquidator is permitted to withdraw 105 USD worth of the collateralized asset. The [governance system](/user-docs/governance) sets the liquidation incentive for each asset supported by YieldBlox.

## Can liquidators liquidate positions using the borrower's collateral?

Yes, YieldBlox allows liquidators to use borrower's collateral to repay their debts by burning the collateralized pool tokens and trading the underlying collateral assets for the necessary assets for repayments on the DEX. In this case, the liquidator will withdraw the borrower's collateral as the collateralized pool token's underlying asset rather than as pool tokens.

## What if the liquidated borrower does not have sufficient collateral to support the liquidation incentive?

In cases of extreme volatility, it is possible for the liquidation incentive to be impossible to pay out under normal market conditions. This could happen if the value of the user's liability increased drastically in a very short amount of time, or the value of the user's collateral fell rapidly. To ensure the undercollateralized loan is still liquidated, YieldBlox uses the [default protection](/user-docs/lending-borrowing/default-protection) system.


# Default Protection

The YBX Default Protection program is used to eliminate counterparty risk from the YieldBlox protocol. It enables the protocol to take on user debt to ensure that liquidations are profitable.

## How does YBX Default Protection remove counterparty risk?

In the case a [liquidation](/user-docs/lending-borrowing/liquidations#what-is-liquidation) would be unprofitable for the liquidator, the lending pool will assume a portion of the liquidated user's debt to reduce the amount the liquidator must repay. This ensures liquidations are always carried out no matter how underwater a position is. The pool will slowly pay off its debt using fees it would normally distribute to YBX escrowers.

## How much debt will the pool take on during a default protection scenario

When a liquidator attempts a liquidation the pool calculates the average liquidation incentive of the collateral held by the user being liquidated. If the value of the user's liabilities exceeds the value of the user's collateral value divided by one plus the user's liquidation incentive, the pool will assume debt equal to the difference. See the equation [here](https://github.com/script3/yieldblox-docs/blob/master/math.md#Yieldblox-Default-Protection-Amount).


# Escrowing

![](/files/-MfiVrR53RbmGAETxAXA)

## What is escrowing?

Escrowing is locking [YBX tokens](/user-docs/ybx-tokens) for a period of time in exchange for voting escrowed YBX tokens, veYBX.

## Why would I escrow?

YieldBlox users escrow their [YBX tokens](/user-docs/ybx-tokens) in exchange veYBX, a non-transferrable asset which is used to vote on YieldBlox [governance proposals](/user-docs/governance). Governance proposals can determine key protocol functionalities like upgrades, asset supports, YBX issuance allocations, and more! YBX issuance can even be allocated to YBX escrows. Basically, users can earn YBX tokens passively and control protocol development -- just for having YBX.

## How does escrowing work on YieldBlox?

[YBX token](/user-docs/ybx-tokens) holders can escrow their YBX in exchange for veYBX. Their YBX is locked for a 3 month, 6 month, or 12 month time period in the YBX escrow pool. After the escrow lockup ends, the user reclaims their locked YBX and exchanges their veYBX for a portion of the YBX earned by YBX escrows.

The protocol also allows users to unlock any escrowed YBX before the time period is up. However, all veYBX associated with the escrow will be burned and the user will receive no YBX for it. Further, there is a small penalty applied to avoid potential voting exploits. This penalty will be initially set at 10%.

![](/files/1hK0hwiuVU0PVPhn7EBP)

## How do I escrow on YieldBlox?

If a user holds any [YBX tokens](/user-docs/ybx-tokens), they can escrow them using the YieldBlox protocol.

Currently, you can escrow YBX for three different lock periods. Each of these lock periods correlates to a different amount of veYBX you will be issued per YBX locked.

| Lock Period |   veYBX Issuance   |
| :---------: | :----------------: |
|   3 months  | 0.25 veYBX per YBX |
|   6 months  | 1.00 veYBX per YBX |
|  12 months  | 4.00 veYBX per YBX |

Consider the example where a user whishes to escrow lock 100 YBX for 3 months. Once they escrow-lock the YBX through the YieldBlox protocol, their YBX is locked in a claimable balance only the protocol can claim. They also receive 25 veYBX in their account they can now use to vote in [governance proposals](/user-docs/governance).

## How do I unlock escrowed YBX on YieldBlox?

A user can unlock any escrowed YBX they have through the YieldBlox protocol.

If the escrowed position has completed the Lock Period associated with it, unlocking returns the full amount of YBX to the user *plus* any fees or emissions earned by escrow locked YBX. These fees are captured by converting the veYBX issued by the escrowed position into YBX!

If the escrowed position has NOT completed the Lock Period associate with it, unlocking works a bit differently. They receive the original escrow amount, minus an early unlock penalty set by [YieldBlox Governance](/user-docs/governance), and do not receive any YBX for their burned veYBX.

## How much YBX will I receive for my veYBX upon unlock?

YBX escrows may receive a portion of YBX issuance if the governance system votes to allocate a portion of issuance to escrows through an [allocation proposal](/user-docs/governance). Additionally, YBX escrows may receive a portion of interest fees if the governance system passes a governance proposal to increase YBX escrow fee allocation, it is currently set at 0. Fees allocated to escrows are converted into YBX.

When a user's escrow is unlocked and their veYBX is exchanged for YBX the amount of YBX they receive is equal to the total YBX earned by escrows divided by total veYBX outstanding times the amount of veYBX exchanges, the equation is shown [here](/technical-docs/math#veYBX-Unlock-Value). This means they receive a proportion of ALL YBX earned by escrows, not just the YBX earned while they were escrowing. This means their veYBX value will fluctuate as other users lock and unlock escrows. This formula favors user's who continually compound their escrow position by re-escrowing all YBX earned from the veYBX exchange.


# Governance

![](/files/-MeX6ZQopG_dfvm0p6-w)

## How does governance work on YieldBlox?

The YieldBlox protocol is updated and maintained using a DAO governance token model. Users receive [YBX tokens](/user-docs/ybx-tokens) for [lending or borrowing](/user-docs/lending-borrowing), and these tokens can be escrowed for veYBX. veYBX tokens have governance power that can be used to make and vote on protocol updates and changes.

While veYBX holders have the real governance power, there is also a YieldBlox security council that holds gYBX tokens. These tokens carry voting power like veYBX tokens do. In addition, they can be used to create and vote on signer swap and freeze contract proposals. These proposals are limited in their functionality, they exist to provide an additional security layer that protects YieldBlox from smart contract bugs or malicious signers. More details on these proposal types can be found in the Governance Proposals section.

## How does the protocol change?

The YieldBlox protocol is controlled by [YBX token](/user-docs/ybx-tokens) escrows, who hold veYBX tokens and makeup the YieldBlox DAO. Holders of veYBX tokens can propose, vote on, and implement changes to the protocol. Proposals can modify existing protocol parameters or add entirely new functionalities to the protocol. To create a proposal, a user must control at least 0.001% of total outstanding voting power (the sum of veYBX and gYBX outstanding).

Once a user submits a proposal to change the protocol, users have three days to vote on whether to implement or reject the proposal. If the proposal is accepted for implementation, it is queued with a 2-day time delay before being implemented.

![](/files/64U69cEUoTxPTAKeXvF2)

## How does voting work?

Users have three days to vote on proposals. They vote 'YES' or 'NO' on proposed protocol updates or changes using the VOTE smart contract function. The number of votes each user has is equal to the amount of veYBX they hold.

If the vote passes (60% of votes are YES at the end of the voting period), the proposal status data entry is changed to *approved*. If it does not pass, the proposal account is deleted. A proposal vote must reach a quorum of at least 5% of outstanding voting power to pass. The proposal has 5 days to reach quorum. If it does not reach it in that time period it is deleted. This quorum percentage can be adjusted through a governance proposal.

## Who can vote?

Anyone who [escrows YBX tokens](/user-docs/escrowing) can vote.

## How are governance proposals created?

Governance proposals are created using the [governance functions](/technical-docs/protocol/governance-contract) of the YieldBlox smart contract.

## Who can create a proposal?

Governance proposals can be created by any user account with more than 0.001% of the total voting power. This percentage can be adjusted through a governance proposal.

## What is the YieldBlox security council?

It takes 5 days at minimum to implement a standard governance proposal. This is slow by design to combat malicious proposals. However, this means that YieldBlox governance is unable to quickly respond to turret failures or uncovered smart contract vulnerabilities. Therefore, the YieldBlox governance system also includes a security council that can quickly submit Swap Signer or Freeze Contract proposals. Members of this council receive gYBX which can vote on these two unique proposal types in addition to normal governance proposals.

The YieldBlox security council should be elected every six months using a standard governance proposal, their membership can also be revoked at any point using a standard governance proposal.

## Governance Proposals

### Standard

Standard governance proposals are the basic proposals used to modify protocol parameters or functionality. Proposer's submit XDR's that carry out all proposed changes, if the proposal is accepted the XDRs are approved for submission. Any user with more than 0.001% of total outstanding voting power can submit a proposal, they must also deposit 1000 XLM into the account that stores the proposal to cover transaction fees. Once the proposal is submitted or rejected they will be able to delete the proposal account and reclaim the XLM.

Standard proposals follow the voting procedure described above.

### YBX Issuance Allocations

YBX issuance allocations are set by governance proposals. These proposals are initiated using a `incentiveAllocation` operation in the governance smart contract. These governance proposals differ from standard governance proposals in that instead of voting `YES` or `NO` they vote on allocating incentives for lending or borrowing a certain asset. For example, if a user wants more incentives to be allocated to XLM lenders, they will use their veYBX to submit `LENDING_XLM` votes. At the end of the voting period, the governance proposal shifts incentive allocation to match the distribution of votes. For example, say USDC and XLM are the only assets supported by the protocol and at the end of the voting period there are 600 votes for `LENDING_XLM` 400 votes for `BORROWING_XLM` 500 votes for `LENDING_USDC` and 500 votes for `BORROWING_USDC`. 30% of YBX incentives will be allocated to XLM lenders, 20% will be allocated to XLM borrowers, 25% will be allocated to USDC lenders, and 25% will be allocated USDC borrowers. This creates a strong incentive for users to vote for whatever assets they are currently lending or borrowing so make sure you vote on these proposals! Any user may submit an allocation proposal regardless of how much voting power they have.

Incentive allocation proposals differ in that the voting period for these proposals is 7 days to give every veYBX holder a chance to vote and there is no queue period. After voting ends the proposal is immediately implemented! Furthermore, only one of these proposals can exist at a time and a new one can be created as soon as the old one is concluded.

### Swap Signer

One risk of the [Stellar Turrets](https://tss.stellar.org) protocol is bad turrets popping up. One way YieldBlox mitigates against this risk is with swap signer proposals. In emergencies, this can be used to remove one turret's signing key and replace it with a different turret's key. These proposals can only be submitted and voted on by gYBX holders (members of the YieldBlox security council).

Unlike custom proposals, signer swap proposals do not have voting or queue periods. As soon as the proposal account reaches 70% of gYBX tokens voting YES, the proposal will be implemented. Signer swap proposals can only be submitted once per day to prevent abuse.

### Freeze Contract

Another main risk of the YieldBlox protocol is a bug in the YieldBlox smart contracts. While our team has thoroughly tested our smart contracts and is having them audited, it is still possible a bug slips through the cracks. To protect against this possibility, gYBX holders can create and vote on freeze contract proposals. This freezes a specified smart contract operations and prevents it from being ran. This contract gives users the ability to quickly freeze a smart contract if a bug is found in it to minimize damage.

Like signer swap proposals, this proposal does not have a voting or queue period. As soon as the proposal account reaches 70% of gYBX tokens voting YES, the proposal will be implemented. This operation can be reversed using either a governance function or a freeze protocol operation. To prevent a rouge security council from perpetually freezing the protocol, freeze contract proposals are unable to freeze governance smart contract functions.


# YBX Tokens

![](/files/-MeS7FoaDDWFspPoQG4G)

## What are YBX tokens?

YBX tokens are the YieldBlox protocol's utility tokens. They are used to govern the protocol, to direct issuance, and as collateral.

## What is the YBX issuer address?

YBX issuer address is

[**GBUYYBXWCLT2MOSSHRFCKMEDFOVSCAXNIEW424GLN666OEXHAAWBDYMX**](https://stellar.expert/explorer/public/asset/YBX-GBUYYBXWCLT2MOSSHRFCKMEDFOVSCAXNIEW424GLN666OEXHAAWBDYMX)

## How many YBX tokens are there?

There are a total of 1,500,000,000 YBX tokens to be issued.

## How do I get YBX tokens?

Users receive YBX tokens just for using the YieldBlox Protocol. They must claim them to receive their issued YBX.

## How do I claim my issued YBX tokens?

If a protocol user has been issued YBX tokens, they can claim them by calling the YieldBlox Protocol claim contract. It is recommend to claim issued YBX weekly.

## Can I buy YBX tokens?

Yes. The main way to receive YBX tokens is to [lend or borrow](/user-docs/lending-borrowing) on YieldBlox, but YBX tokens are Stellar tokens, so anyone can trade them on the [Stellar DEX](https://www.stellar.org/tools?locale=en#trade-on-the-stellar-dex).

## What can I do with YBX tokens?

Users can escrow YBX tokens in exchange for veYBX. veYBX allows users to earn a portion of YBX issuance (which may be directed to escrows), as well as [vote](/user-docs/governance#how-does-voting-work) on and create governance [proposals](/user-docs/governance#how-are-protocol-change-proposals-created), there is also a mechanism by which veYBX accrues protocol fees.

## How are YBX tokens distributed?

YBX tokens are distributed daily to users for [lending](/user-docs/lending-borrowing), [borrowing](/user-docs/lending-borrowing#how-does-borrowing-work-on-yieldblox), or [escrowing](/user-docs/escrowing) on the YieldBlox Protocol. **Only lenders who collateralize the lent asset are eligible for YBX issuance.**

![](/files/4W9tGfuVsup1AdN0ui0O)

The YBX issuance equation is used to calculate the number of YBX tokens to distribute. Once this equation finds this distribution number, each lender, borrower, or escrower will be allocated a percentage of YBX tokens based on the issuance allocation percentage for an asset. Each asset's issuance allocation percentage is a set constant controlled by YBX token holders. After the protocol knows an assets lending and borrowing allocation percentage, lenders or borrowers of that asset can claim YBX tokens proportionally based on the percent of all lending or borrowing they contribute for that asset. It should be noted that YBX issuance to escrows is sent directly to the escrow pool where it is claimed after the user unlocks their YBX escrow. See the Technical Documentation on [YBX Issuance](/technical-docs/ybx-issuance) for more information on how this process functions.

***Example visualized:***

A user lent or borrowed on YieldBlox the week prior to *date x*. The issuance equation finds that 100,000 YBX tokens are to be issued on *date x*.

![](/files/uC6Y0Vnez6jo7w9xENZr)

Now there are 100,000 YBX tokens to be allocated. Let's say there are four assets being lent in YieldBlox on *date x*, and they all have equal allocation percentages (25%) (in this example we assume no issuance is directed to escrows or borrowers). The user is lending and collateralizing *Asset 1*, and they contributed 5% of the total amount of Asset *1* lent and collateralized. Then the total number of YBX tokens the user would be eligible to claim is:

(YBX-issued) \* (Lending Asset 1's allocation percentage) \* (User percentage contributed to the lent and collateralized amount of Asset 1)

\= (100,000) \* (25%) \* (5%)

\= 1,250 YBX tokens

![](/files/vUZdFvAM5KjyeWDfcKGQ)

The user in this example would receive 1,250 YBX tokens on the distribution date of *date x*. These numbers are for explanatory purposes and may or may not reflect real YBX token issuance.

## What is the issuance equation?

The issuance equation is used to calculate the total tokens (YBX) to be issued for a given period. This equation is a negative inverse proportion function.

The number of tokens issued decreases as the number of outstanding tokens increases. The curve also adjusts for any additional issuance or burning of YBX tokens. Though, additional issuance can only occur through a governance proposal. See the issuance equation below:

$$
I=(T-O) \* R
$$

Where:\
$$I=$$ the YBX issuance of the current period\
$$T=$$ the total number of YBX tokens to be issued; 1,500,000,000\
$$O=$$ the number of YBX tokens outstanding\
$$R=$$ the YBX issuance rate; initially 0.0075

## Is there an initial YBX token distribution?

Yes, there will be an initial distribution of YBX tokens. The distribution will be a total of 69,000,000 YBX tokens. It will be distributed to the YieldBlox DAO, early contributors to the YieldBlox protocol, a bug bounty, marketing efforts, and Stellar ecosystem members! The initial investor token allocation will be locked for a year, and the initial team allocation will be locked for 4 years following a linear unlock schedule with a one year cliff. The YieldBlox DAO Treasury allocation is directly controlled by the YieldBlox [governance system](/user-docs/governance).

After the initial distribution, the remaining 810,000,000 YBX tokens will be distributed to protocol lenders and borrowers. So overall, 92% of all YBX tokens will be distributed directly to the community!

![](/files/-Mj7f7W82pyov49k06jL)

## How much YBX will be in circulation?

Below is a visual of circulating YBX for the first five years. It includes YieldBlox Protocol issuance, initial investor issuance, team issuance, and the YBX airdrop. While not included, the YieldBlox DAO Treasury, bug bounty, and partnership treasury allocations account for 37.33% of total YBX.

**Please Note:** This is a "pessimistic" estimate as it assumes no YBX issuance will be paid to YBX escrows. Which likely will not be the case.

![](/files/aBoktk83gvjHwpvFn4mP)

## Was there a YBX airdrop?

Yes. The initial distribution allocated to ecosystem user marketing was partially distributed through an airdrop. The rest will be distributed through various giveaways.


# YBX Tokenomics

YBX's tokenomics were designed with the goal of creating a productive platform asset which enables its holders to benefit from every part of the YieldBlox Protocol.

## The Five Levels of YBX Productivity:

YBX's tokenomics model has five levels of asset productivity protocol participants can engage in to get the most value out of their YBX tokens.

### Level 1: YBX issuance distributes governance power for lending and borrowing on YieldBlox.

The foundation of YBX tokenomics is the [YBX distribution mechanism](/user-docs/ybx-tokens#how-do-i-get-ybx-tokens) which awards lenders and borrowers YBX for lending and borrowing using the YieldBlox Protocol. This on-ramps new users into the governance system and ensures that the majority of governance control will be distributed to YieldBlox's most committed users. YBX incentives decrease logarithmically over time.

![](/files/vUZdFvAM5KjyeWDfcKGQ)

### Level 2: Users can escrow YBX to participate in governance.

YBX holders can [escrow](/user-docs/escrowing) their YBX for veYBX to begin participating in protocol governance. YBX issuance may also be allocated to YBX escrows and, in the future, it's possible that governance decides to allocate a portion of interest fees to YBX escrows by using a portion of interest to repurchase and distribute YBX.

![](https://lh4.googleusercontent.com/B7dihereU-pc6_BK4AdUiwcw7JqjGL4cXC3KoPwdXGF5t3qmfEL0gGmt6aVmdD0Az_063N4FN5Y2SPl1Xu5HBxY4yyjMUZ0qJmF4f73SCqEf0-v-kVmVzKuT4j1g_MhltuuJFcvgPa8)

### Level 3: Users can escrow YBX:USDC or YBX:XLM AMM shares to earn AMM fees.

Using AMMs on the Stellar Network, YBX holders are able to escrow YBX:USDC or YBX:XLM AMM shares to receive veYBX at the same rate as locking just YBX. Not only will they get the typical benefits of escrowing, they will also earn trading fees from the AMM shares. This benefits both the protocol and the user, as the YieldBlox Protocol regularly trades YBX through normal protocol operations. This feature is not yet implemented, but it is one we hope is added by protocol governance down the line.

### Level 4: Users can use their escrowed YBX or YBX AMM shares as collateral to borrow in the YieldBlox protocol.

Users are permitted to use escrowed YBX as collateral and borrow against it. This allows them to gain liquidity on their escrowed YBX and receive [YBX issuance](/user-docs/ybx-tokens#how-are-ybx-tokens-distributed) for borrowing.

### Level 5: Users can use veYBX to vote on the allocation of YBX issuance to different lending pools.

Users who escrow YBX receive veYBX, which can be used to vote on [incentive allocation governance proposals](/user-docs/governance#ybx-incentive-allocations). These proposals are used to determine how YBX issuance is divided between the lenders and borrowers of assets supported by the YieldBlox Protocol. Users can vote to increase incentives to certain assets to reward lending or borrowing.

This is valuable for [anchors](/user-docs/why-stellar#what-are-anchors) that want to distribute governance power to users who lend their anchored asset. A fintech platform anchoring their native platform asset could use veYBX to vote to increase issuance for lenders of their platform asset. This would expand the benefits their platform offers users. Normal users can vote to increase the incentives allocated to the assets they are currently lending or borrowing.

![](/files/mua2MqPpzkubRLddl0hy)


# Game Theory of YBX

High-level rational decision making with YBX tokens and the YieldBlox protocol.

## When is the YieldBlox Protocol most efficient?

A user can take do five actions with YBX tokens to maximize both the value they receive from the protocol and the value they add to the protocol. The more participation within YieldBlox, the better it is for all parties involved. These actions are highlighted in the [Five Levels of YieldBlox Productivity](/user-docs/ybx-tokens/ybx-tokenomics#the-five-levels-of-ybx-productivity), the effects these actions have on the protocol and the benefits they have can be illustrated with game theory.

The five actions a user can do with YBX (simplified):

* Sell (-)
* Hold (+)
* Escrow (++)
* Escrow + [Vote](/user-docs/ybx-tokens/ybx-tokenomics#level-4-users-can-use-sybx-to-vote-on-the-allocation-of-ybx-incentives-to-different-lending-pools) + Borrow (+++)
* Escrow + Vote + Borrow + [AMM](/user-docs/ybx-tokens/ybx-tokenomics#level-4-users-can-use-sybx-to-vote-on-the-allocation-of-ybx-incentives-to-different-lending-pools) (+++++)

In the above list, anything from "Hold" and below is seen as a positive outcome (increasing in benefit as one goes down the list), and "Sell" is a negative outcome. The positivity of these actions takes the following goals into mind: users want to profit, the protocol wants high liquidity to repurchase and sell YBX easily through its escrow fee and [default protection](https://github.com/script3/yieldblox-docs/blob/master/user-docs/ybx-tokens/ybx-backstop.md#how-does-ybx-default-protection-remove-counterparty-risk) functions, and the protocol and users want to minimize YBX selling pressure to ensure the default protection system is effective. Each user wants the most positive outcome for them and the protocol.

Let's say there are two users who both have YBX. Their matched action strategies are described here:

If they both claim YBX and do nothing with it (hold), it is seen as a positive outcome (1,1). The protocol still functions as it is supposed to, and users still get their YBX for lending or borrowing. Therefore, the protocol would see the base positive outcome of (1,1) (1 +1 = 2).

If both users escrow their claimed YBX, a more positive outcome (over just holding YBX) occurs (2,2). This has the same benefits of holding, but escrows gain more benefits. Users escrowing their YBX for veYBX may earn interest for escrowing since they could receive YBX issuance and possibly a portion of protocol fees. These actions result in the second positive outcome of (2,2) (2 + 2 = 4).

If both users escrow their claimed YBX and [vote](/user-docs/governance) on YieldBlox governance proposals, the third positive outcome occurs (3,3). Both users still receive the rewards of escrowing YBX for veYBX, and the protocol is now guided by their decisions, allowing them to increase their control and [allocate YBX incentives](/user-docs/governance#ybx-incentive-allocations) where they see fit. This results in a even more positive outcome for the users, (3,3) (3 +3 = 6).

Now let's say both users escrow and vote, but they also utilize automated market makers to escrow [AMM shares](/user-docs/ybx-tokens/ybx-tokenomics) on YieldBlox. This is the maximum positive outcome for all parties (5,5). Not only do the users gain their share of protocol revenue, but they also get to claim trading fees from the AMM shares. This is also beneficial for the protocol, as it provides the maximum possible liquidity for any protocol YBX repurchase operations. The most positive outcome occurs if both users use this strategy, (5,5) (5 + 5 = 10).

When both users sell, the most-negative outcome occurs (-5,-5). This is detrimental to the protocol and users. The protocol's repurchase and governance mechanisms do not function as well, and users will not be able to claim the benefits of escrowing YBX, vote on governance proposals, or receive AMM trading fees. If this outcome occurs, the total benefit score is -10.


# Why Stellar?

![](/files/-MeVtovq5MQseDeeEV11)

## Stellar & YieldBlox

YieldBlox uses [Stellar's decentralized ledger](https://developers.stellar.org/docs/glossary/ledger/) to support the protocol, and it is the ideal platform for YieldBlox.

In Stellar's words:

> Fundamentally, Stellar is a system for tracking ownership. It uses an accounting ledger, shared across a network of independent computers, to store two important things for every account holder: what they own (their account balances) and what they want to do with what they own (operations on those balances, like buy or sell offers). The computers that run Stellar and publish the ledger are called nodes. They systematically validate the ledger’s contents so it’s always consistent across the network. For example, when you send someone a dollar on a Stellar-built app, the nodes check that the correct balances were debited and credited, and each node makes sure every other node sees and agrees to the transaction.

Stellar's open network allows anyone to submit a transaction to change the ledger. However, the transaction only changes the ledger after the nodes agree it is valid.

In YieldBlox’s case, before a loan is taken out or repaid, the local network of nodes agree upon the transaction's validity. This prevents parties with ill intentions from engaging in illicit behavior on the network. Therefore, Stellar provides a secure financial network with one source of truth and can be instantly accessed and modified by anyone in the world.

## Why the YieldBlox Protocol is built on Stellar

The Stellar network has some key characteristics which YieldBlox takes advantage of:<br>

* [**Stellar's Consensus Protocol**](https://developers.stellar.org/docs/glossary/scp/)\
  The SCP enables the Stellar Blockchain to offer extremely low fees and settlement times. In addition, it follows a federated byzantine agreement model, which allows the network to remain decentralized and antifragile without requiring a large validator set or economic incentives.<br>
* **Focus on Finance**\
  The Stellar Network is meant to be used almost exclusively for facilitating financial services. This reduces network bloat and ensures high-performance for the financial infrastructure using the network.<br>
* **High Capital Efficiency**\
  Stellar uses an on-chain DEX that prevents liquidity fragmentation within the ecosystem. With AMMs, trades execute against both AMMs and the DEX to preserve capital efficiency. This interleaved execution improves liquidity and reduces in-network arbitrage opportunities, resulting in efficient trading.<br>
* **Established Ecosystem Standards**\
  Building fintech apps with Stellar is extremely easy due to the strength of Stellar’s ecosystem standards. Multiple cohesive SDKs make it easy to interface an app with Stellar. Additionally, Stellar has excellent specifications for on and off-ramping fiat currencies and handling KYC, making it easy for fintech apps to onboard non-blockchain-native users.<br>
* [**Anchors**](https://developers.stellar.org/docs/anchoring-assets/)\
  Stellar has a multi-asset functionality called anchoring which enables users to create custom assets on its ledger tied to real-world assets. This means YieldBlox can support the lending of any asset.<br>
* [**Stellar Turrets**<br>](https://tss.stellar.org/)Turrets are a decentralized network of servers that hold uploaded smart contracts that can then be tied to private keys. Transactions are signed with these private keys if the transactions meet the requirements of the smart contracts. The YieldBlox Protocol uses this tool to manage some of the Turing complete logic surrounding loan processing.

## Stellar's Security Features

![](/files/-MgIa29EXf52-003i6aX)

YieldBlox uses Stellar's security features to ensure loans and collateral accounts associated with the protocol are safe from risks.

* [**Stellar Turrets Protocol**<br>](https://github.com/tyvdh/turing-signing-server)The Turrets protocol provides YieldBlox with a method of adding Turing complete smart contract logic to transactions without requiring a third party to control the accounts involved in the transactions. This decentralizes YieldBlox without reducing efficiency.<br>
* [**Multi-Sig**<br>](https://developers.stellar.org/docs/glossary/multisig/)YieldBlox margin account users must store borrowed assets in accounts partially controlled by the YieldBlox protocol. This is to ensure they cannot transfer the assets outside of the protocol ecosystem. Stellar’s multi-sig capability allows YieldBlox to add all necessary Turret signers to the margin account and modify account thresholds so that the user does not have complete control over the account. Thus preventing the account from submitting transactions without using Turret functions. This security measure locks borrowed assets in the margin account until margin repayment or liquidation.<br>
* [**Claimable Balances**](https://developers.stellar.org/docs/glossary/claimable-balance/)\
  YieldBlox uses claimable balances to manage user collateral balances. Borrowers must lock their collateral in claimable balances until they repay any loans. The balances are only claimable by the YieldBlox pool account, so the user cannot withdraw collateral without protocol approval.<br>
* [**Path Payments**](https://developers.stellar.org/docs/start/list-of-operations/#path-payment-strict-send)\
  Stellar path payments enable users to atomically repay borrows and perform liquidations with collateral deposits. The transaction attempts to trade collateral assets for the necessary assets to repay the borrow. This allows the transaction to dynamically adjust the amount of assets sold to make the most efficient trade possible. Furthermore, if the trade is not possible, the transaction will revert without causing any harm.<br>
* [**Asset Controls**](https://developers.stellar.org/docs/issuing-assets/control-asset-access/)\
  YieldBlox FX forwards use a credit model that tokenizes each leg of the forward. Users are not allowed to send these assets to other accounts or trade them for non-credit assets. With Stellar's asset controls, YieldBlox can require users to request trade approval for trades from YieldBlox smart contracts before they can be submitted. This enables the protocol to ensure the tokens are only being traded for other tokenized FX forward credits.<br>
* [**Stellar's Consensus Protocol**<br>](https://developers.stellar.org/docs/glossary/scp/)The consensus protocol rejects transactions when they do not align with the correct ledger state. For example, a user could not fill a sell offer if their account lacked the necessary funds to complete the trade.

## What are Anchors?

![](/files/-MgIbAiFiR2gMs7iyh84)

[Anchors](https://developers.stellar.org/docs/anchoring-assets/) are on/off ramps to the Stellar network with fiat currencies.

For YieldBlox to ease equitable access globally, anchors need to be readily available within the Stellar ecosystem. To lend or borrow a non-native asset, a third party must already be anchoring that asset.

Here are some non-native assets reputable third parties currently anchor:

* **USDC**\
  US dollar anchor provided by [Centre](https://www.centre.io/)<br>
* **CNY**\
  Chinese yuan anchor provided by [RippleFox](https://ripplefox.com/)<br>
* **EURT**\
  Euro anchor provided by [Tempo](https://tempo.eu.com/home)<br>
* **NGNT** \
  Nigerian naira anchor provided by [Cowrie](https://www.cowrie.exchange/)<br>
* **BRL**\
  Brazilian real anchor provided by [ntokens](https://www.ntokens.com/)<br>
* **ARST**\
  Argentine pes anchor provided by [Stablex](https://stablex.org/)<br>
* **GOLD**\
  Gold anchor provided by [StellarMetals](https://stellarmetals.org/)<br>
* **BTC**\
  Bitcoin anchor provided by [Papaya](https://apay.io/in)<br>
* **ETH**\
  Ethereum anchor provided by [Interstellar](https://interstellar.exchange/)<br>
* **DSTOQ**\
  Equities anchor provided by [DSTOQ](https://www.dstoq.com/)

More anchors can be viewed on [Stellar Expert](https://stellar.expert/explorer/public/).

### More Information on Stellar

{% embed url="<https://www.stellar.org/>" %}


# YieldBlox Protocol Assets

Yieldblox uses a variety of custom protocol assets to track protocol information. These assets are all issued by the YieldBlox pool account and represent specific underlying assets. They are all clawback enabled so the pool can manipulate claimable balances containing them. The tokens follow the following naming convention

`{Token Key}{Underlying Asset Issuer Key}{Underlying Asset Overlap Key}{First 9 characters of underlying asset}`

Where:

* Token Key: Character that identifies protocol asset
  * y = Pool Token
  * l = Liability Token
  * i = Accrued Interest Tracker Token
  * a = Pool Issuance Ratio Tracker Token
  * b = Pool Issuance Shift Tracker Token
  * c = Liability Issuance Ratio Tracker Token
  * d = Liability Issuance Shift Tracker Token
* Underlying Asset Issuer Key: base 64 character that identifies the issuer of the underlying asset associated with the protocol token. It corresponds to a pool data entry that holds the issuer account id.
* Underlying Asset Overlap Key: base 64 character that identifies the last 3 characters in an asset code. It corresponds to a pool data entry that holds the last 3 characters of the asset code

### Pool Tokens

Pool tokens are used to track user deposits in the YieldBlox Protocol. They represent proportional ownership of a YieldBlox lending pool. Their value is calculated using the Pool Token Value equation ([see math section](/technical-docs/math#pool-token-value)). Users receive them when they deposit assets into a lending pool and burn them when they withdraw assets from a lending pool.

Sample Asset Code for an XLM pool token: `y00XLM`

***

### **Liability Tokens**

Liability Tokens are used to track user borrowing liabilities. One Liability Token corresponds to one of the underlying asset. When a user borrows from the pool, the protocol creates a claimable balance of liability tokens that tracks the loan. As interest accrues, more liability tokens are added to the claimable balance. When the loan is repaid, the claimable balance is deleted.

Sample Asset Code for an XLM liability token: `l00XLM`

### Accrued Interest Tracker Tokens

Accrued interest tracker tokens are used to track the interest accrued to outstanding underlying asset liabilities over time. This is done by paying them to accrued interest tracker accounts in the process outlined in the [Accrued Interest Tracking section](/technical-docs/accrued-interest-tracking).

Sample Asset Code for an XLM utilization tracker token: `i00XLM`

#### Pool Issuance Ratio Tracker Tokens

Pool Issuance Ratio Tokens track YBX Incentive payouts for collateralized pool tokens by trading the mantissa amount of the [issuance ratio](/technical-docs/math#Issuance-Ratio) for a given pool token for a given period for an amount of Pool Issuance Shift Tracker Tokens equal to the exponential associated with that mantissa. So if there are 100 pool tokens collateralized and 50 YBX tokens are being issued, the issuance ratio will be 0.5 and the amount of Pool Issuance Ration Tokens sold will be 5.

Sample Asset Code for an XLM pool issuance ratio token: `a00XLM`

#### Pool Issuance Shift Tracker Tokens

Pool Issuance Ratio Tokens track YBX Incentive payouts for collateralized pool tokens by trading the exponential associated with the mantissa of the [issuance ratio](/technical-docs/math#Issuance-Ratio) for a given pool token for a given period for an amount of Pool Issuance Ratio Tracker Tokens equal to the mantissa. To avoid negative numbers the exponential is added to 15. So if there are 100 pool tokens collateralized and 50 YBX tokens are being issued, the issuance ratio will be 0.5 and the amount of Pool Issuance Shift Tokens sold will be 16.

Sample Asset Code for an XLM pool issuance ratio token: `b00XLM`

#### Liability Issuance Ratio Tracker Tokens

Liability Issuance Ratio Tokens track YBX Incentive payouts for liability tokens by trading the mantissa amount of the [issuance ratio](/technical-docs/math#Issuance-Ratio) for a given liability token for a given period for an amount of Liability Issuance Shift Tracker Tokens equal to the exponential associated with that mantissa. So if there are 100 liability tokens and 50 YBX tokens are being issued, the issuance ratio will be 0.5 and the amount of Liability Issuance Ration Tokens sold will be 5.

Sample Asset Code for an XLM liability issuance ratio token: `c00XLM`

#### Liability Issuance Shift Tracker Tokens

Liability Issuance Ratio Tokens track YBX Incentive payouts for liability tokens by trading the exponential associated with the mantissa of the [issuance ratio](/technical-docs/math#Issuance-Ratio) for a given liability token for a given period for an amount of Liability Issuance Ratio Tracker Tokens equal to the mantissa. To avoid negative numbers the exponential is added to 15. So if there 100 liability tokens and 50 YBX tokens are being issued, the issuance ratio will be 0.5 and the amount of Liability Issuance Shift Tokens sold will be 16.

Sample Asset Code for an XLM pool issuance ratio token: `d00XLM`

### vYBX

vYBX is issued to veYBX escrows to allow them to vote on governance proposals. Their maximum vYBX allowance is the amount of veYBX they hold. veYBX is non-transferable by the user.

### gYBX

gYBX is issued to the initial contributors of the YieldBlox Protocol instead of veYBX. gYBX has voting power but, it does not receive YBX issuance to escrows like veYBX does.


# User Positions

YieldBlox user positions are stored on-chain using [claimable balances](https://developers.stellar.org/docs/glossary/claimable-balance/) that encode information about user positions in claimable balance claimants. To manipulate these balances the pool uses clawback claimable balance operations as both pool and liability tokens are clawback enabled.

### Collateral Claimable Balances

User collateral deposits are stored as claimable balances of pool tokens. Users normally sponsor these claimable balances, but the claimable balance is sponsored by the escrow pool instead if they get liquidated.

Claimants:

* Distribution Account or User - Predicate Never: By default the distribution account is a claimant, however, if a user is liquidated they become the claimant so the protocol knows the collateral belongs to them.

### Liability Claimable Balances

User borrows are stored as claimable balances of liability tokens. Users normally sponsor these claimable balances, but the claimable balance is sponsored by the escrow pool instead if they get liquidated.

Claimants:

* Distribution Account - Predicate Before Absolute Time: This claimant tracks the principal amount of the liability. So the amount that was originally borrowed.
* User - Predicate Never: If the liability balance was liquidated the user is added as a claimant so the protocol knows the liability belongs to them.

### Escrow YBX Claimable Balances

User YBX escrows are stored as claimable balances of YBX. The user typically sponsors these claimable balances. If they are liquidated, the escrow pool will sponsor them instead.

* Claimants:
  * Distribution Account - Predicate Not Before Absolute Time: The distribution account claimant predicate tracks the user's escrow period start date
  * Pool Account or Escrow Account - Predicate Not Before Absolute Time: This claimant tracks the user's escrow unlock date. If the pool account is the claimant the escrow is used as a collateral, if the escrow account is the claimant the escrow is not collateralized.
  * User - Predicate Never: If the escrow is liquidated the user is added as a claimant track that it belongs to them.
  * Issuing Account - Predicate Never: If the escrow is not allowed to be unlocked early the issuance account is added as a claimant to track unlocking early is not permitted.

###

***


# Interest Rates

YieldBlox interest rates are calculates using four different slopes that step up as different utilization rates are hit. This is designed to improve capital efficiency, allowing the rate to move reflexively with demand and support higher utilization levels while also preventing liquidity crunches in the protocol. As you can see by the graph below, in the final slope interest rates begin moving up extremely fast. This is to prevent a liquidity crunch by either forcing borrowers to quickly repay or enticing lenders to quickly deposit.

### Interest Rate Curve Graphs:

![Note: these numbers may change](/files/7VOv1pou9Vvg0RxcspVf)

![Note: these numbers may change](/files/vQMqib5kjXnHGalMnlUF)

### Sample Interest Rate Calculation:

***Please Note all Numbers are Examples and not indicative of real Protocol Variables***

Utilization Rate: .95

Interest Rate Thresholds:

* Threshold 1: .7
* Threshold 2: .9
* Threshold 3: .97

Base Interest Rate: .05

Interest Rate Slopes"

* Slope 0: .2
* Slope 1: 1.5
* Slope 2: 7.5
* Slope 3: 350

In this case the interest rate would be 86.5%

.05+ .7\*.2+1.5\*(.9-.7)+7.5\*(.95-.9) = .865


# Underlying Asset Data

Each underlying asset supported by YieldBlox has a set of protocol-specific data stored in the pool accounts data entries.

## Data Entries:

### Interest Accrual Tracker Account

Address of the account that tracks interest accrual for the underlying account.

**Date Entry Key:** `{Underlying Asset Issuer Key}{Underlying Asset Overlap Key}{First 9 characters of underlying asset}_Tracker`

**Data Entry Value:** `{Interest Accrual Tracker Account Public Key}`

### Interest Data

Variables used in asset [interest rate equations](#math.md#Interest-Rate-Calculations).

**Date Entry Key:** `{Underlying Asset Issuer Key}{Underlying Asset Overlap Key}{First 9 characters of underlying asset}_Interest`

**Data Entry Value:** `{Base Interest Rate}_{Interest Rate Slope 0}_{Interest Rate Slope 1}_{Interest Rate Slope 2}_{Interest Rate Slope 3}_{Interest Rate Threshold 1}_{Interest Rate Threshold 2}_{Interest Rate Threshold 3}`

**Where:**

* Base Interest Rate: Base interest rate constant in the interest rate equation (see math). Multiplied by 100 before being encoded.
* Interest Rate Slope 0: Interest rate slope when below the first interest rate threshold. Multiplied by 10 before being encoded.
* Interest Rate Slope 1: Interest rate slope when above the first interest rate threshold. Multiplied by 10 before being encoded.
* Interest Rate Slope 2: Interest rate slope when above the second interest rate threshold. Multiplied by 10 before being encoded.
* Interest Rate Slope 3: Interest rate slope when above the third interest rate threshold. Multiplied by 10 before being encoded.
* Interest Rate Threshold 1: If the utilization rate is above this threshold Interest Rate Slope 1 kicks in. Multiplied by 100 before being encoded.
* Interest Rate Threshold 2: If the utilization rate is above this threshold Interest Rate Slope 2 kicks in. Multiplied by 100 before being encoded.
* Interest Rate Threshold 3: If the utilization rate is above this threshold Interest Rate Slope 3 kicks in. Multiplied by 100 before being encoded.

### Asset Loan-to-Value Ratio

Loan to value ratio for the underlying asset, used to calculate (health factors)\[../user-docs/lending-borrowing/health-factors.md].

**Date Entry Key:** `{Underlying Asset Issuer Key}{Underlying Asset Overlap Key}{First 9 characters of underlying asset}_LTV`

**Data Entry Value:** `{Underlying Asset Loan-to-Value Ratio}`

**Where:**

* Loan to Value: Used in the health factor equation, loan to value ratio for the underlying asset. Multiplied by 100 before being encoded.

### Fee Data

Data pertaining to fees related to the underlying asset.

**Date Entry Key:** `{Underlying Asset Issuer Key}{Underlying Asset Overlap Key}{First 9 characters of underlying asset}_Fee`

**Data Entry Value:** `{Liquidation Incentive}_{Liquidation Fee}_{YBX Fee Allocation}_{Withdrawal Fee}`

**Where:**

* Liquidation Incentive: Used in liquidations. This is the 'discount' the liquidator receives on the collateral they withdraw when they repay a loan. Multiplied by 100 before being encoded.
* Liquidation Fee: Used in liquidations. This is the portion of the liquidation incentive that is paid to the escrow pool. Multiplied by 100 before being encoded.
* YBX Fee Allocation: Percent of interest rate fees that are used to repurchase YBX. Multiplied by 100 before being encoded.
* Withdrawal Fee: Fee for withdrawing from the protocol. Multiplied by 100 before being encoded.

### Allocation Data

Data pertaining to the ybx issuance allocation for assets

**Date Entry Key:** `{Underlying Asset Issuer Key}{Underlying Asset Overlap Key}{First 9 characters of underlying asset}_Allocation`

**Data Entry Value:** `{Collateral Incentive Allocation}_{Liability Incentive Allocation}`

**Where:**

* Collateral Incentive Allocation: Percent of YBX incentive issuance that is allocated to users who collateralize this asset. Multiplied by 100 before being encoded.
* Liability Incentive Allocation: Percent of YBX incentive issuance that is allocated to users who borrow this asset. Multiplied by 100 before being encoded.

### Price Feed Data

Data pertaining to the price feeds used to track the price of underlying assets

**Date Entry Key:** `{Underlying Asset Issuer Key}{Underlying Asset Overlap Key}{First 9 characters of underlying asset}_Exchange`

**Data Entry Value:** `{Exchange Primary}_{Binance}_{Coinbase}_{FTX}_{Asset Ticker}`

**Where:**

* Exchange Primary: Denotes whether the preferred price for the asset is centralized exchange prices or the Stellar DEX. 1 for exchange primary, 0 for DEX primary.
* Binance: Denotes whether Binance is used as an oracle price source for this asset. 1 for yes 0 for no.
* Coinbase: Denotes whether Coinbase is used as an oracle price source for this asset. 1 for yes 0 for no.
* FTX: Denotes whether FTX is used as an oracle price source for this asset. 1 for yes 0 for no.
* Underlying asset ticker: The ticker used in price feed API calls.


# Accrued Interest Tracking

In order to track accrued interest on floating rate loans, we must accrue interest to a user's liability every time their borrowing interest rate changes. We accomplish this by tracking users' liabilities with liability tokens that increase in value over time, accruing interest to all outstanding loans.

### Accrued Interest Tracker Overview

Tracking accrued interest for underlying assets is done using an accrued interest tracker account that starts with a balance of 1000 interest tracking tokens and receives interest accrual payments every time the utilization ratio of the asset it's tracking changes. Effectively, this means the account is tracking the liability value of a loan taken out at protocol origination. When a user borrows from the protocol we store their borrowed amount divided by the interest tracker balance, then at all points in the future we can multiply that quotient by the current interest tracker balance divided by the starting interest tracker balance to get the current value of a user's liabilities.

### Accrued Interest Tracker Payments

Every time the utilization ratio of an underlying asset changes, the pool makes an accrued interest payment to the accrued interest tracker account. The payment amount is equal to the per-block interest accrued on the balance of the accrued interest tracker account times the number of blocks between the second to last and last utilization modifying transactions. This means that accrued interest tracking lags one period. The indicator must lag because turret smart contracts do not have an accurate view of the current ledger, so they need to look at past ledger state to ensure truthfulness. See Math for the equation.

To provide an example, we'll outline the utilization delta payment of a sample transaction (transaction 100):

* **Transaction 98 - block 1000 - depositing XLM**
  * Protocol state pre-transaction 98
    * Pool Balance: 90 XLM&#x20;
    * XLM Liabilities: 100 XLM&#x20;
    * XLM Utilization Ratio: .526
    * Accrued interest tracker balance: 100
  * Transaction 98 Action:&#x20;
    * Deposits 10 XLM into lending pool
  * Protocol state post-transaction 98
    * Pool Balance: 100 XLM&#x20;
    * XLM Liabilities: 100 XLM&#x20;
    * XLM Utilization Ratio: .5
* **Transaction 99: Block 1100 - Borrowing XLM**
  * Details irrelevant
* **Transaction 100: Block irrelevant - Borrowing XLM**&#x20;
  * Details irrelevant
  * Accrued Interest Payment

    * Makes accrued interest payment of 50 interest tracker assets to the accrued interest tracker account
      * 100\*(.05+.526\*0.2)/(6,307,200)\*(1100-1000) = 0.0002461

    It should be noted that transactions 98 and 99 would also have made accrued interest payments; they just weren't the focus of this example.

### Accrued Interest Corrections

In addition to accrued interest payments, the accruet interest tracker sysrem also makes accrued interest correction clawbacks and payments. These take place in the same transaction as accrued interest payments. This is necessary because the accrued interest tracker can apply an incorrect payment if its ledger view is incorrect and missing the most recent transaction (this commonly occurs when two users interact with the protocol simultaneously).&#x20;

#### Accrued Interest Correction Process

When an accrued interest payment is calculated, the smart contract also checks the last utilization delta payment to see if it was correct. If it was not correct, the tracker calculates what the correction should be (undoing the bad delta and adding the correct one), then repeats the process, checking the next payment back. Once the smart contract finds the total correction, it is applied in either a payment or clawback operation depending on whether the correction was positive or negative.  It should be noted that since there is a 5 minute timebounds on protocol transactions, the utilization tracker assumes that any accrued interest payment 5 minutes newer than the previous one was correct.

To provide an example, we'll outline the accrued interest correction payment of a sample transaction (transaction 100):

* **Transaction 97 - Block 900 - Deposit XLM**
  * Protocol state pre-transaction 97
    * Pool Balance: 60 XLM
    * &#x20;XLM Liabilities: 100 XLM
    * Utilization Ratio: .625
    * Accrued interest tracker balance: 1000
  * Transaction 97 Action
    * Deposit 20 XLM
    * Accrued interest tracker payment of .01
  * Protocol state post-transaction 97
    * Pool Balance: 80 XLM
    * &#x20;XLM Liabilities: 100 XLM
    * Utilizaiton Ratio: .5555556
    * Accrued interest tracker balance: 1000.01
* **Transaction 98- Block 1000 - Deposits XLM**
  * Protocol state pre-transaction 98
    * Pool Balance: 80 XLM
    * &#x20;XLM Liabilities: 100 XLM
    * Utilization Ratio: .5555556
    * Accrued interest tracker balance: 1000.01
  * Transaction 98 action
    * Deposit 20 XLM
    * Accrued interest tracker payment: .01
  * Protocol state post-transaction 98
    * Pool Balance: 100 XLM&#x20;
    * XLM Liabilities: 100 XLM&#x20;
    * Utilization Ratio: .5
    * Accrued interest tracker balance: 1000.02
* **Transaction 99 - Block 1010 - Borrows XLM**&#x20;
  * Protocol state pre-transaction 99
    * Pool Balance: 100 XLM
    * &#x20;XLM Liabilities: 100 XLM
    * Utilization Ratio: .5
    * Accrued interest tracker balance: 1000.02
  * Transaction 99 action
    * Borrows 100 XLM
    * Makes an accrued interest tracker payment of .002
      * This is incorrect, correct payment is .002774
        * (0.05+0.625\*0.2)/(6,307,200)(1000-900)\*1000 = .002774
  * Protocol state post-transaction 99
    * Pool Balance: 100 XLM&#x20;
    * XLM Liabilities: 100 XLM&#x20;
    * Utilization Ratio: .5
    * Accrued interest tracker balance: 1000.022
* **Transaction 100 - Borrows XLM** &#x20;
  * Protocol state pre-transaction 100
    * Accrued interest tracker balance: 1000.022
    * Other information irrelevant
  * Protocol actions
    * Borrow XLM
    * Make a accrued interest correction payment of .000774
      * .002774 - .002 = .000774
    * Make an accrued interest tracker payment of .0002554
      * (0.05+0.555556\*0.2)/(6,307,200)(1010-1000)\*1000 = .0002554
* Protocol state pre-transaction 100
  * Accrued interest tracker balance: 1000.02303
  * Other information irrelevant

#### Using the Accrued Interest Tracker to find the value of a user liability.

To find the value of a users liability the protocol multiplies the number of liability tokens associated with that liability times the accrued interest tracker balance plus the expected next accrued interest tracker payment divided by the starting tracker balance.

For Example:

* User's liability claimable balance contains 99.8 l00XLM tokens
* 00XLM's accrued interest tracker account has 1005.2 i00XLM
  * Next expected payment is .2 i00XLM
* User's liability is 100.33892 XLM
  * (1005.2+.2)/1000 \* 99.8 = 100.33892


# YBX Issuance

YBX issuance is the process by which platform YBX incentives are paid out to protocol lenders (only lenders with collateralized deposits receive YBX incentives), borrowers, and escrowers. Issuance is paid out daily and tracked and distributed with 2 different processes, Issuance Tracking and YBX Claims.

### Issuance Tracking

Issuance tracking tracks the amount of YBX that should be distributed to each user on a given issuance period(day). To do so, the protocol uses issuance tracker trades made by the UPDATE operation in the Claim contract. The issuance tracker trades track a pool or liability tokens [issuance ratio](/technical-docs/math#Issuance-Ratio), or the amount of YBX issued per pool or liability token of that type for the given issuance period. These trades exchange an assets [issuance ratio tracker token](/technical-docs/yieldblox-protocol-assets#Pool-Issuance-Ratio-Tracker-Token) for its [issuance shift tracker token](/technical-docs/yieldblox-protocol-assets#Pool-Issuance-Shift-Tracker-Token). The trades track the issuance ratio floating point style, the amount of ratio tokens sold is equal to the mantissa of the issuance ratio, and the amount of shift tokens sold is equal to that mantissa's exponential. The exponential amount is added to 15 to avoid numbers less than 0.

For example, if a pool tokens issuance ratio for a period is 12.1, the issuance trade will exchange 1.21 ratio tracker tokens for 14 shift tracker tokens.

### YBX Claims

Users claim YBX accrued to a given position whenever they modify the position or run the CLAIM operation in the Claim contract. To calculate accrued YBX, the protocol uses the following process

1. Check the last block the claimable balance for the position was modified.
2. Pull every trade involving the ratio and shift assets associated with the protocol token representing that position made after the block found in step 1.
3. Calculate the amount of YBX accrued by taking the sum of the following:
   1. The position size multiplied by the most recent issuance trade ratio times the percent of the current period that has elapsed
   2. The sum of each trade ratio in the set except the most recent one times the position size
   3. The farthest back issuance trade ratio multiplied by the position size times the percent of the period that elapsed between when the position was modified and when the farthest back trade occurred.

We'll provide an example below:

Position: 100,000 l00XLM liability Position - last updated on 12/12/2021 - 12:00 UTC - Event timestamp is 12/15/2021 - 18:00 UTC

Set of YBX issuance trades for l00XLM

1. ratio: 0.5 - 12/13/2021 - 00:00 UTC
2. ratio: 1.5 - 12/14/2021 - 00:00 UTC
3. ratio: 2 - 12/15/2021 - 00:00 UTC

YBX issuance for the position equals:

(((18/24)\*100,000\*2+100,000\*1.5+100,000\*0.5+(12/24)\*100,000\*.5 = 375,000

Astute observers will have noticed this can result in users missing out on a small amount of issuance if they modify a position many times during one issuance period. This is an unfortunate side effect of us being unable to overload the Claim contract with API calls.


# Protocol Accounts

YieldBlox uses a variety of protocol accounts in its operations.

### Pool Account

Public Key: `GCPFDAQGO3QZ6PUCXCPDHV4UEKJVLPKJEYY4BQHZBEJGHDVU6FPIF2VR`

The YieldBlox lending pool holds assets lent using the YieldBlox protocol. It also issues pool and liability tokens and controls collateral and loan claimable balances. Finally, it stores most protocol asset parameters in its data entries. The smart contracts fetch this information from the pool data entries when they require it.

#### Data Entries

Data entry format

* `Data Entry Key:Data Entry Value`

**Underlying Asset Related Data Entries**

Data entries for each asset supported by the protocol

* Underlying Asset Data - see [underlying asset data](/technical-docs/underlying-asset-data) section.
* `{Underlying Asset Issuer Key}{Underlying Asset Overlap Key}{First 9 characters of underlying asset}_Underlying:{Issuer Account Public Key}_{Last 3 characters of underlying asset}`
  * Stores the underlying asset issuer and remaining characters from the underlying asset code so that the protocol can reconstruct the associated underlying asset from a protocol asset.

### Issuing Account:

Public Key: `GBUYYBXWCLT2MOSSHRFCKMEDFOVSCAXNIEW424GLN666OEXHAAWBDYMX`

The YBX Issuing account is controlled by the YieldBlox smart contracts. It issues YBX during YBX issuance and default protection events (if necessary)

### Distribution Account:

Public Key:`GCZIXLOVS6CCBSIORWL5Y3HYZJRUQ65UEHF3SNIZZH6OPN54YXH4AJGX`

The YBX distribution account receives issued YBX from the YBX issuing account and pays it out to users when they run the CLAIM smart contract.

#### Data Entries

Data entry format

* `Data Entry Key:Data Entry Value`

**Turret Related Data Entries**

For each turret that is a signer on protocol accounts

* `T_{Turret Signer Public Key}:{Turret Sponsor Public Key}`
  * Tracks the owners of the turret signers in control of the protocol
* `YieldBlox Contract Hash:{Contract Hash}`
  * The hash of the YieldBlox Contract uploaded to its signing turrets. Allows users to verify that the contract is the expected one

**YBX Issuance Related Data Entries**

* `YBX_Issuance_Rate:{daily issuance rate}`
  * The amount of remaining YBX to issue that is issued every day
* `YBX_Total_Supply:{total ybx supply}`
  * The total supply of YBX (currently 1.5 billion)

**Governance Proposal Related Data Entries**

* `Proposal_Creation_Threshold:{Threshold}`
  * Threshold of voting power needed to create a governance proposal
* `Custom_Quorum_Threshold:{Threshold}`
  * Governance proposal voting quorum needed to pass a custom governance proposal
* `Council_Quorum_Threshold:{Threshold}`
  * Governance proposal voting quorum needed to pass a council governance proposal
* `Locked_Contracts:{Locked Contract}_{Locked Contract}_`
  * List of all contracts currently locked by the governance smart contract

For every custom proposal outstanding

* `P_{Proposal Account Public Key}:{Proposal number}`
  * Tracks every custom proposal currently outstanding. The value is the custom proposal number, so if there are 2 proposals outstanding, 1 will have the number 0 and the other will have the number 1.
* `P_Allocation:{Allocation Proposal Account Public Key}`
  * Tracks the public key of the currently outstanding allocation proposal.
* `P_Council_Lock:{Lock Proposal Account Public Key}`
  * Tracks the public key of the currently outstanding council lock proposal if there is one.
* `P_Council_Swap:{Swap Proposal Account Public Key}`
  * Tracks the public key of the currently outstanding council swap proposal if there is one.
* `LAST_SIGNER_SWAP:{Last signer swap execution timestamp}`
  * Tracks the last time a signer swap was executed

### Escrow Pool:

Public Key: `GBU2XXS7XGQ34OSJ4QI3DRFIGXI53ROLA77IXPSVXJ4KSWV5VYUJG2PA`

The YBX escrow pool holds YBX rewards that are paid out to YBX escrows and used in the default protection events. It also issues veYBX and vYBX.

### Interest Accrual Tracker Accounts

(Public keys TBD)

Interest Accrual Tracker Accounts receive interest accrual payments from the pool account. Their balance is used to calculate aggregated utilization ratios for user positions.


# Smart Contracts/Architecture

This section will cover all the smart contracts that YieldBlox uses. These contracts are all sub-contracts in the same master smart contract. But they are each handled independently and entered with a global event handler.

### Global Request Fields

The following fields are shared between all smart contract requests.

* userPublicKey: user public key
* timestamp: current timestamp, if it is not from the last 5 minutes the smart contract will reject the request.
* type: Protocol function the user is requesting, stored as the following enum:

```
ProtocolEventTypes {
    TX_BURN = 0,
    TX_CLAIM = 1,
    TX_ESCROW = 2,
    TX_LIQUIDATE = 3,
    TX_MINT = 4,
    TX_PROPOSAL_CREATE = 5,
    TX_PROPOSAL_UPDATE = 6,
    TX_REPAY = 7,
    TX_VOTE = 8
}
```

### Other general contract information

#### Balance Line Objects

The BalanceLine object is often used to represent an asset (using an [assetId](#AssetId-Entries)) and an amount of that asset. It is the following object:

```
BalanceLine {
    assetId: string,
    amount: string
}
```

#### Repay Path Objects

The RepayPath object is used in repayments and liquidations to represent a path payment that should be taken to liquidate user collateral during a liquidation with collateral. The [assetId](#AssetId-Entries) fields in the object should represent underlying assets. The asset is as follows:

```
RepayPath {
  sendAssetId: string; // Expects underlying asset Id
  sendAmount: string;
  destAssetId: string;
  destAmount: string;
  path: string[];
}
```

NOTE: The object in the smart contract uses BigNumber objects for the amounts represented in the object. However, users should still input strings in their requests. The contract will handle transforming the object when it ingests the request.

#### AssetId Entries

assetId entries are strings that represent asset objects. They are structured as {assetCode}:{assetIssuer}.

#### PathPayment Handling

Whenever a `pathPayment` operation is used the contract first finds the most efficient path first and passes it into the operation.


# Mint Contract

Lending, collateralizations, and borrowing take place through the Mint contract. Users can deposit assets and collateralize them in the same transaction.

**Request**

```
{
   userPublicKey: string,
   timestamp: number,
   type: ProtocolEventTypes,
   targetPool: string,
   collateralizations: BalanceLine[]
   deposit?: BalanceLine,
   borrow?: BalanceLine,
}
```

**Fields:**

* targetPool: Id of the pool associated with the assets being repaid.
* collateralizations: Array of [BalanceLine](/technical-docs/protocol#Balance-Line-Objects)'s representing the pool tokens and the amount of the pool tokens the user would like to collateralize. If the user does not wish to add additional collateral they can submit an empty array.
* Deposit (Optional): [BalanceLine](/technical-docs/protocol#Balance-Line-Objects) representing the asset and amount of the asset the user would like to deposit into the lending pool. Expects an underlying [assetId](/technical-docs/protocol#AssetId-entries).
* Borrow (Optional): [BalanceLine](/technical-docs/protocol#Balance-Line-Objects) representing the asset and the amount of the asset the user would like to borrow. Expects an underlying [assetId](/technical-docs/protocol#AssetId-entries).
  * Note: If the user attempts to borrow an amount that would put their health factor below 1.1, their request is rejected.

### High-Level Contract Process Flow (MAY BE OUT OF DATE)

1. User enters the contract through an event handler which transforms their request.
2. Contract prerequisite data from horizon.
   1. Pool Account Data
   2. User Account Data
   3. User Position Data
3. Contract builds a transaction builder object.
   1. This is the object operations will be added to throughout the rest of the contract process flow.
4. If the user is depositing the contract handles deposits.
   1. The contract adds a `payment` operation to the transaction builder where the user pays the pool their deposit and a `payment` operation where the pool pays the user pool tokens.
      1. If the user is missing a poolToken trustline the contract first adds a `changeTrust` operation where the user creates one.
5. If the user is collateralizing the contract handles collateralizations
   1. Contract checks if the user currently has collateral balances of the assets they are attempting to collateralize. If they do the contract adds `claimClaimableBalance` operations where the pool claims the balances so they can be consolidated with the new collateralizations.
      1. The contract will also calculate any unclaimed YBX the user has accrued to these positions.
   2. Contract adds `createClaimableBalance` operations where the user creates collateral deposit claimable balances.
6. If the user is borrowing the contract handles the borrow.
   1. Contract adds a `payment` operation where the pool pays the user the borrowed asset.
   2. If the user already has a liability balance associated with the asset the user is borrowing the contract adds a `claimClaimableBalance` operation where the pool claims the liability balance so it can be consolidated with the additional borrowed assets.
      1. The contract will also record all interest accrued by this liability balance and add it to the user's total liability for the asset.
      2. The contract will also calculate any unclaimed YBX the user has accrued to this position.
   3. Contract adds a `createClaimableBalance` operation where the pool creates liability claimable balance to record the users total liabilty for the borrowed asset.
      1. The user sponsors this claimable balance.
7. Contract checks the users new health factor. If it is below 1.1 the contract throws a rejection.
8. If the user has any unclaimed YBX associated with the refreshed balances the contract adds a `payment` operation where the distribution account sends the total unclaimed YBX to the user.
9. The contract performs all necessary utilization delta payments and corrections. See Average Utilization Ratios section.
10. Turret builds transaction builder into an XDR and returns it along with a signature.

### Diagram

![Diagram may be out of date](/files/vnMKr6X9k4KReRaactCU)

**Lender A:** Lends 50,000 XLM to the pool and receives 50,000 y00XLM in exchange. Lender A can burn these tokens later when the pool has accumulated fees and receive their proportion of the pool back.

**Borrower B:** Deposits 30,000 XLM to the pool and collateralizes the received pool tokens to take out a 10,800 USDC loan. Also, deposits pool tokens from a previous uncollateralized deposit as collateral for a 1,800 XLM loan.


# Burn Contract

The burn contract is used to exchange pool tokens for the underlying assets they represent. The calculations used here will find the proportional amount of pool tokens burned in respect to pool tokens outstanding. The request consists of an Amount and the Pool Token Code of the pool token to be burned. Users will receive the respective proportion of the underlying asset after burning pool tokens.

**Request**

```
{
    userPublicKey: string,
    timestamp: number,
    fee: string,
    type: ProtocolEventTypes,
    withdrawal?: BalanceLine,
    burn?: BalanceLine
}
```

#### Fields:

* withdrawal (OPTIONAL): [BalanceLine](/technical-docs/protocol#Balance-Line-Objects) representing the pool token being uncollateralized and the amount of the pool token being uncollateralized.
* burn (OPTIONAL): [BalanceLine](/technical-docs/protocol#Balance-Line-Objects) representing the pool token being burned and the amount of the pool token being burned.

### High-Level Contract Process Flow (MAY BE OUT OF DATE)

1. User enters the contract through an event handler which transforms their request.
2. Contract prerequisite data from horizon
   1. Pool Account Data
   2. User Account Data
   3. User Position Data
3. Contract builds a transaction builder object
   1. This is the object operations will be added to throughout the rest of the contract process flow.
4. Contract calculates the value of the poolToken, subtracting withdrawal fees.
5. Contract adds a `payment` operation where the pool sends withdrawal fees to the DAO treasury.
6. Contract adds a `payment` operation where the user pays the poolTokens they are burning to the pool (deleting them).
7. Contract adds a `payment` operation where the pool pays the value of the burned pool tokens in underlying to the user.
8. Contract adds operations to handle Utilization Updates and Corrections. See Average Utilization Ratios section.
9. Turret builds, signs, and returns transaction XDR.

### Diagram

![Diagram may be out of daye](/files/gntSh1UdQK6RjOlh27fK)

**Account A:** Lends 2,000 XLM and receives 2,000 y00XLM. Pool takes in 3,000 XLM in fees over the course of time. Account A now decides to withdraw and burn pool tokens in return for the underlying asset. The proportion of the liquidity provided is returned as well as a proportion of interest.


# Repay Contract

User repayments are handled using the Repay contract. Users also can repay a loan using collateral instead of the borrowed asset. The user's health factor must have been improved by the request or it will be rejected.

**Request**

```
{
   userPublicKey: string,
   timestamp: number,
   type: string,
   repayments: BalanceLine,
   targetPool: string,
   collateralRepayments?: RepayPath[]
}
```

\
**Fields:**

* repayments:[BalanceLine](/technical-docs/protocol#Balance-Line-Objects) that represents the assets and amounts being repaid. [assetId](/technical-docs/protocol#AssetId-entries)'s are expected to be liability tokens.
* targetPool: Id of the pool associated with the assets being repaid.
* collateralRepayments (OPTIONAL): Array of [RepayPath](/technical-docs/protocol#Repay-Path-Objects)'s describing how to structure the pathPayments that will be used to liquidate collateral withdrawn. These are only input if the user is partially or fully repaying with collateral.

### High-Level Contract Process Flow (MAY BE OUT OF DATE)

1. User enters the contract through an event handler which transforms their request.
2. Contract prerequisite data from horizon.
   1. Pool Account Data
   2. User Account Data
   3. User Position Data
3. Contract builds a transaction builder object.
   1. This is the object operations will be added to throughout the rest of the contract process flow.
4. If user is withdrawing the contract handle withdrawals.
   1. Contract adds `claimClaimableBalance` operations where the pool claims the withdrawn collateral balances.
      1. Contract calculates all unclaimed YBX issuance associated with these collateral balances.
   2. If the user is not fully withdrawing the contract adds a `createClaimableBalance` operation where the user recreates the collateral position with the remaining collateral.
   3. If the user is not repaying with collateral the contract adds `payment` operations where the pool pays all withdrawn pool tokens to the user.
   4. If the user is repaying with collateral the contract burns all withdrawn pool tokens.
      1. It first calculates the pool tokens' value including the withdrawal fee .
         1. Contract adds `payment` operations which pathPayments the withdrawal fees from the pool to the escrow account (the destination asset is YBX).
      2. Contract adds `payment` operations which send the value of the pool token from the pool to the user.
5. If the user is repaying the contract handles repayments.
   1. Contract adds `payment` operations where the user pays the repayment to the pool.
      1. If the user is repaying with collateral the contract instead adds `pathPaymentStrictReceives` that pay the withdrawn assets to the pool (destination asset is the asset being repaid).
   2. Contract adds a `claimClaimableBalance` operation where the pool claims the associated liability balance.
      1. Contract accrues interest to the relevant liability balance.
      2. Contract also calculates all unclaimed YBX issuance associated with these collateral balances.
      3. If the liability was not fully repaid the contract adds a `createClaimableBalance` operation where the pool creates a liabilty claimable balance representing the remaining asset liability.
         1. The user sponsors this claimable balance.
      4. Contract calculates the YBX repurchases associated with the interest paid in the repayments and adds `pathPaymentStrictSend` operations that have the user purchase and send YBX to the escrow account with a portion of their interest payment.
6. Contract checks user health factor after withdrawals and repayments. If it has decreased and is below 1.1 the contract rejects.
7. Contract adds a `payment` option where the distribution account pays any unclaimed YBX from the previous calculations to the user.
8. Contract adds all necessary Utilization Tracker operations. See Average Utiization Ratios section.
9. Turret builds transaction builder into an XDR and returns it along with a signature.

### Diagram

![](/files/HMJKjIA2O2bhWJlXLiqY)

#### In the base repayment scenario (no repay with collateral)

**User Account:** pays the pool 100 USDC and withdraws 345 yXLM from their collateral claimable balance (the pool claims it and pays it to the user). The pool deletes the user's liability claimable balance to reflect the repayment.

#### In the repay with collateral liquidation scenario <a href="#in-the-repay-with-collateral-liquidation-scenario-1" id="in-the-repay-with-collateral-liquidation-scenario-1"></a>

**User Account:** withdraws 345 yXLM from their collateral claimable balance (the pool claims it and pays it to the user); this is then converted to XLM and sold for 102 USDC, which is paid to the pool. The pool deletes a portion of the liquidated user's liability claimable balance to reflect the repayment. The liquidated user's new liability balance will be 263.58 USDC, and their new collateral balance will be 901.635 y00XLM.


# Liquidate Contract

Users use the liquidate contract to liquidate underwater accounts where the health factor has dropped below 1. Users will be able to liquidate loans by selling the liquidated users collateral or by repaying the borrowed asset normally.

**Request**

```
{
   userPublicKey: string,
   timestamp: number,
   type: ProtocolEventTypes,
   liquidateeId: string,
   repayments: BalanceLine[],
   withdrawals: BalanceLine[],
   targetPool: string,
   backstopOrder: string[],
   collateralRepayments?: RepayPath[]
}
```

\
**Fields:**

* liquidateeId: public key of the account being liquidated
* repayments: array of [BalanceLine](/technical-docs/protocol#Balance-Line-Objects)'s that represent the assets and amounts being repaid. [assetId](/technical-docs/protocol#AssetId-entries)'s are expected to be liability tokens.
* withdrawals: array of [BalanceLine](/technical-docs/protocol#Balance-Line-Objects)'s that represent the assets and amounts being repaid. [assetId](/technical-docs/protocol#AssetId-entries)'s are expected to be pool tokens.
* targetPool: Id of the pool associated with the assets being repaid.
* backstopOrder: Array of [assetId](/technical-docs/protocol#AssetId-entries)'s.
* collateralRepayments (OPTIONAL): Array of [RepayPath](/technical-docs/protocol#Repay-Path-Objects)'s describing how to structure the pathPayments that will be used to liquidate collateral withdrawn. These are only input if the liquidator is partially or fully liquidating with collateral.

### High-Level Contract Process Flow (MAY BE OUT OF DATE)

1. User enters the contract through an event handler which transforms their request.
2. Contract prerequisite data from horizon.
   1. Pool Account Data
   2. User Account Data
   3. User Position Data
3. Contract builds a transaction builder object.
   1. This is the object operations will be added to throughout the rest of the contract process flow.
4. Contract populates all withdrawals and repayments for the liquidation based on the maxLiquidation calculations and the users repayment and withdrawal inputs. It also calculates whether or not a backstop repayment is necessary.
5. Contract handle withdrawals.
   1. Contract adds `claimClaimableBalance` operations where the pool claims the withdrawn collateral balances.
      1. Contract also calculates all unclaimed YBX issuance associated with these collateral balances.
   2. If the user is not fully withdrawing the contract adds a `createClaimableBalance` operation where the user recreates the collateral position with the remaining collateral.
      1. Escrow account sponsors these. The contract also adds `payment` operations where the user pays XLM to the escrow account so they have the funds to sponsor the claimable balances.
   3. If the user is not repaying with collateral the contract adds `payment` operations where the pool pays all withdrawn pool tokens to the user.
   4. If the user is repaying with collateral the contract burns all withdrawn pool tokens.
      1. It first calculates the pool tokens' value including the withdrawal fee.
         1. Contract adds `pathPayment` operations where the pool uses the withdrawal fees to repurchase YBX and sends it to the escrow account.
      2. Contract adds `payment` operations where the pool sends the value of the pool token from the pool to the user.
6. The contract handles repayments.
   1. Contract adds `payment` operations where the user pays the repayment to the pool.
      1. If the user is repaying with collateral the contract instead adds `pathPaymentStrictReceives` where the user uses the withdrawn assets to repurchase the repayment asset and sends it to the pool.
   2. Contract adds a `claimClaimableBalance` operation where the pool claims the associated liability balance.
      1. Contract adds accrued interest to the relevant liability balance.
      2. Contract also calculates all unclaimed YBX issuance associated with these collateral balances.
      3. If the liability was not fully repaid the contract adds a `createClaimableBalance` operation where the pool creates a liabilty claimable balance representing the remaining asset liability.
         1. Escrow account sponsors these. The contract also adds `payment` operations where the user pays XLM to the escrow account so they have the funds to sponsor the claimable balances.
      4. Contract calculates the YBX repurchases associated with the interest paid in the repayments and adds `pathPaymentStrictSend` operations that have the user purchase and send YBX to the escrow account with a portion of their interest payment.
7. If backstop repayments are necessary contract creates `pathPaymentStrictReceive` operations where the escrow account and issuing account sell YBX for the repayment asset and send it to the pool account.
8. Contract adds a `payment` option where the distribution account pays any unclaimed YBX from the previous calculations to the liquidated user.
9. Contract adds all necessary Utilization Tracker operations. See Average Utiization Ratios section.
10. Turret builds transaction builder into an XDR and returns it along with a signature.

### Diagram

![](/files/0gv0WogRHabkcOrgGnki)

#### In the base liquidation scenario (no repay with collateral)

**Liquidator Account:** pays the pool 236.42 USDC and withdraws 716.015 yXLM from the liquidatee's collateral claimable balance (the pool claims it and pays it to the user, then remakes the claimable balance). The pool deletes a portion of the liquidated user's liability claimable balance to reflect the repayment. The liquidated user's new liability balance will be 263.58 USDC, and their new collateral balance will be 901.635 y00XLM.

#### In the repay with collateral liquidation scenario

**Liquidator Account:** withdraws 716.015 yXLM from the liquidatee's collateral claimable balance (the pool claims it and pays it to the user, then remakes the claimable balance). This is then converted to XLM and sold for 236.42 USDC, which is paid to the pool. The pool deletes a portion of the liquidated user's liability claimable balance to reflect the repayment. The liquidated user's new liability balance will be 263.58 USDC, and their new collateral balance will be 901.635 y00XLM.


# Rate Contract

Loan rate rebalancing and rate swaps are done through the Rate contract. Users lending will use this contract to ensure that they get the correct interest accrued on the funds being lent out. Rebalancing can only occur when the stable interest rate is below the current floating rate. Users who are borrowing will use this contract to swap from stable or floating rates on their loans.

**Request**

```
{
    userPublicKey: string,
    timestamp: number,
    type: string,
    claimableBalanceId: string,
    targetRate: string,
}
```

\
***Fields:***

* Claimable Balance Id: ID of the claimable balance representing the loan that needs to have its interest rate swapped.
* Target Rate: Target interest rate for the loan (fixed or floating)

### High-Level Contract Process Flow

1. User enters the contract through an event handler which transforms their request.
2. Contract prerequisite data from horizon.
   1. Pool Account Data
   2. User Account Data
   3. User Position Data
3. Contract builds a transaction builder object.
   1. This is the object operations will be added to throughout the rest of the contract process flow.
4. If the user is not the owner of the liability balance the contract verifies that the balance is fixed rate and that its interest rate is lower than the current floating interest rate. If either of these things are not the case the contract rejects.
5. Contract adds a `claimClaimableBalance` operation where the pool claims the specified liabiliity balance.
   1. The contract calculates accrued interest and adds it to the liability balance.
   2. The contact calculates all unclaimed YBX issuance associated with this liability balance.
6. Contract adds a `createClaimableBalace` operation where the pool creates a liability balance with the target interest rate.
   1. If the user is the owner they sponsor the liability balance. If they are not the owner the escrow account sponsors the liability balance.
      1. The rebalancer must pay the escrow account the necessary minimum reserve for sponsoring the liability balance.
7. Contract creates a `payment` operation where the distribution account pays any unclaimed YBX to the user.
8. Contract adds all necessary Utilization Tracker operations.
9. Turret builds transaction builder into an XDR and returns it along with a signature.

### Diagram

![](/files/6ejAfhu0yA9Sh4lBdB7A)

**User Account:** The pool claims the liability claimable balance and recreates it with a floating interest rate.


# Claim Contract

Users will claim their governance rewards using this contract. Any time a claimable balance is touched, Claim will be invoked in order to keep proper track of issuance. This contract also handles updating YBX issuance amounts for each daily period. Any other contracts that manipulate claimable balances will have the Claim contract invoked to keep proper track of issued pool incentives.

**Request**

```
{
    userPublicKey: string,
    timestamp: number,
    fee: string,
    type: ProtocolEventTypes,
    operation: 'UPDATE' | 'CLAIM',
}
```

\
***Fields:***

* operation: UPDATE or CLAIM, update sends issuance tracker payments for a period. Claim claims YBX for users.

### High-Level Contract Process Flow (MAY BE OUT OF DATE)

1. User enters the contract through an event handler which transforms their request.
2. Contract prerequisite data from horizon.
   1. Pool Account Data
   2. User Account Data
   3. User Position Data
3. Contract builds a transaction builder object.
   1. This is the object operations will be added to throughout the rest of the contract process flow.
4. If the contract is performing a UPDATE operation.
   1. Contract checks if UPDATE has been ran today. If it has been it rejects the request.
   2. Contract calculates the YBX issuance ratio for each asset. See YBX Issuance section.
   3. Contract send YBX issuance ratio payments to all YBX issuance trackers.
   4. Contract adds a `payment` operation where the issuance account pays all YBX to be distributed this period to the distribution account.
   5. Contract adds a `payment` operation where the distribution account pays all YBX allocated to YBX escrowers to the escrow pool.
5. If the contract is performing a CLAIM operation.
   1. Contract identifies all user positions that have unclaimed YBX issuance accrued to them.
   2. Contract creates `claimClaimableBalance` operations where the pool claims all user positions that have YBX to claim.
      1. Contract calculates the YBX to be issued for each of these positions.
         1. See YBX Issuance section.
      2. Contract calculates accrued interest for all liability positions.
   3. Contract adds `createClaimableBalance` operations where the pool recreates all user positions.
      1. The user sponsors these claimable balances.
   4. Contract adds a `payment` operation where the distribution account pays all earned YBX to the user.
   5. Contract adds Utilization Tracker operations. See Average Utilization Ratios section.
6. Turret builds transaction builder into an XDR and returns it along with a signature.

###


# Escrow Contract

### Escrows

Users will lock and unlock escrows through this contract. Escrowing periods are 3 month periods, 6 month periods, or 12 month periods. Users who escrow YBX will receive veYBX, which accrues escrowing fees and has voting power.

**Request**

```
{
    userPublicKey: string,
    timestamp: number,
    fee: string
    type: ProtocolEventTypes,
    unlocks?: {escrowId: string, amount: string}[],
    earlyUnlocks?: {escrowId: string, amount: string}[],
    lockAmount?: string,
    period?: number,
}
```

**Fields:**

* unlocks (OPTIONAL): Array of claimable balance ids tied to unlocked escrows and the amount from each of these escrows that the user would like to unlock.
  * Note: Users cannot unlock an amount that would bring your health factor below 1.1 or leave them with more votes than they have voting power.
* earlyUnlocks (OPTIONAL): Array of claimable balance ids tied to locked escrows and the amount from each of these escrows that the user would like to unlock.
  * Note: You cannot unlock an amount that would bring your health factor below 1.1.
* Lock Amount (OPTIONAL): Amount of YBX being locked
* Period (OPTIONAL): 3, 6 or 9 month period to lock YBX
* Unlock Early Amount (OPTIONAL): amount of YBX being unlocked prior to the defined unlock period
  * Note: You cannot unlock an amount that would bring your health factor below 1.1

### High-Level Contract Process Flow

The escrow contract changed after these docs were written. A revised contract process flow is coming soon!


# Governance Contract

Governance Proposals are submitted and managed using the Governance Contracts. There are two governance contracts, the Proposal Create contract and the Proposal Update contract.

### Proposal Create

Handles governance proposal creation.

**Request**

```
{
    userPublicKey: string,
    timestamp: number,
    type: ProtocolEventTypes,
    fee: string,
    proposalAccountId: string,
    proposalType: ProposalType
    params: CouncilLockParams | CouncilSwapParams | undefined

}
```

***Fields:***

* proposalAccountId: The public key of the account being created as the proposal account.
* proposalType: Represents the governance proposal type using the following enum

  ```
  ProposalType {
   ALLOCATION = 0,
   CUSTOM = 1,
   COUNCIL_SWAP_SIGNER = 2,
   COUNCIL_LOCK_CONTRACT = 3
  }
  ```
* params: undefined if the proposal is custom or an allocation proposal, otherwise related to council lock or swap proposals.

  ```
  CouncilLockParams: {
     lockedContracts: ProtocolEventTypes[]
     }
  ```

  * lockedContracts: array of enums that represent the different protocol event types (Mint, Burn, etc...)

  ```
  CouncilSwapParams: {
     addTurret: string;
     addSigner: string;
     removeSigner: string;
     }
  ```

  * addTurret: Public key of the turret sponsor account being added
  * addSigner: Public key of the turret signer account being added
  * removeSigner: Public key of the signer being removed

#### High-Level Contract Process Flow

This contract has been modified recently, an updated Contract Flow will be added shortly

### Proposal Update

Handles updating proposals by tallying their votes, submitting them, or deleting them.

**Request**

```
{
    userPublicKey: string,
    timestamp: number,
    fee: string,
    type: ProtocolEventTypes,
    proposalAccountId: string,
    proposalType: ProposalType
}
```

**Fields:**

* proposalAccountId: The public key of the account being created as the proposal account.
* proposalType: Represents the governance proposal type using the following enum

  ```
  ProposalType {
   ALLOCATION = 0,
   CUSTOM = 1,
   COUNCIL_SWAP_SIGNER = 2,
   COUNCIL_LOCK_CONTRACT = 3
  }
  ```

#### High-Level Contract Process Flow (MAY BE OUT OF DATE)

This contract has been modified recently, an updated Contract Flow will be added shortly


# Vote Contract

### Vote

Users vote on governance proposals through this contract.

**Request**

```
{
    userPublicKey: string,
    timestamp: number,
    type: ProtocolEventTypes,
    fee: string,
    proposalAccountId: string,
    votes: BalanceLine[],
    proposalType: ProposalType
}
```

***Fields:***

* proposalAccountId: The public key of the account being created as the proposal account.
* proposalType: Represents the governance proposal type using the following enum

  ```
  ProposalType {
   ALLOCATION = 0,
   CUSTOM = 1,
   COUNCIL_SWAP_SIGNER = 2,
   COUNCIL_LOCK_CONTRACT = 3
  }
  ```
* votes: array of user votes represented by [BalanceLine](/technical-docs/protocol#Balance-Line-Objects)'s
  * If user is voting on a non-allocation update the assetCode will be YES or NO
  * If user is voting on an allocation update the assetCode will be a liability token code, pool token code, or YBX
  * amount is the number of votes the user wishes to cast

### High-Level Contract Process Flow (MAY BE OUTDATED)

1. User enters the contract through an event handler which transforms their request.
2. Contract prerequisite data from horizon.
   1. Pool Account Data
   2. User Account Data
   3. User Position Data
3. Contract builds a transaction builder object.
   1. This is the object operations will be added to throughout the rest of the contract process flow.
4. Contract checks that the user has sufficient voting power for the total amount of votes they entered by looking at their veYBX holdings. If they do not the proposal rejects.
5. Contract adds a `allowTrust` operation where the escrow account authorizes the user to hold vYBX.
6. Contract checks how much vYBX the user currently has.
   1. If the user does not have sufficient vYBX to cast their votes the contract adds a `payment` operation where the escrow account pays the necessary vYBX to the user.
   2. If the user has too much vYBX the contract adds a `payment` operation that pays the excess vYBX to the escrow account.
7. Contract adds `manageSellOffer` operations where the user offers to sell vYBX for their input vote assets. Vote assets are assets with the input asset code with the proposal account as the issuer.
8. Contract adds a `allowTrust` operation where the escrow account authorizes the user to maintain vYBX liabilities.
9. Turret builds, signs, and returns the XDR.


# Math

Calculations used in the YieldBlox protocol.

## Utilization Ratio Calculations

### Utilization Ratio

Used to calculate the current utilization ratio for an asset.

$$
U=\frac {L} {L+B}
$$

Where:\
$$U=$$the Utilization ratio\
$$L=$$liabilities outstanding ([see](#liabilities-outstanding))\
$$B=$$the total balance of the pool\\

### Originating Utilization Ratio

Used to calculate the originating utilization for an asset.

$$
U\_o = \frac {U\_{d+2}} {b\_{o+1} - b\_o}
$$

Where:\
$$U\_o=$$the originating utilization ratio\
$$U\_{d+2}=$$the utilization delta payment 2 utilization-modifying transactions after loan origination\
$$b\_{o+1}=$$the block of the next utilization-modifying transaction\
$$b\_o=$$the loan origination block

### Utilization Tracker Delta \*depreciated\*

Used to calculate the utilization tracker delta of a transaction. This allows the protocol to measure an asset's average utilization ratio over a period of time.

$$
U\_d = \frac {L\_{i-1}} {B\_{i-1} + L\_{i-1}} \*(b\_{i} - b\_{i-1})
$$

Where:\
$$U\_d=$$the utilization tracker delta\
$$L\_{i-1}=$$the total number of liability tokens at the pre-transaction ledger state of the last utilization-modifying transaction\
$$B\_{i-1}=$$the total pool balance at the pre-transaction ledger state of the last utilization-modifying transaction\
$$b\_{i}=$$the block of the last utilization-modifying transaction\
$$b\_{i-1}=$$the block of the second-to-last utilization-modifying transaction

### Utilization Adjustment \*depreciated\*

Used to calculate the necessary utilization ratio delta adjustment.

$$
U\_a =\sum^{U\_{\Delta w}}*{i=U*{\Delta l}} \frac {L\_{i-2}} {B\_{i-2} + L\_{i-2}} \*(b\_{i-1} - b\_{i-2}) -U\_{di} - U\_{ai}
$$

Where:\
$$U\_a=$$the utilization adjustment\
$$U\_{\Delta w} =$$the place of the furthest back incorrect utilization delta payment\
$$U\_{\Delta l} =$$the place of the utilization delta payment of the last utilization-modifying transaction\
$$L\_{i-2} =$$the total number of liability tokens at the pre-transaction ledger state of the utilization-modifying transaction 2 utilization-modifying transactions ago\
$$B\_{i-2} =$$the total pool balance at the pre-transaction ledger state of the utilization-modifying transaction 2 utilization-modifying transactions ago\
$$b\_{i-1} =$$the block of second-to-last utilization-modifying transaction\
$$b\_{i-2} =$$the block of the third-to-last utilization-modifying transaction\
$$U\_{di} =$$the utilization delta payment of the last utilization-modifying transaction\
$$U\_{ai} =$$the utilization adjustment payment of the last utilization-modifying transaction

### Average Utilization Ratio \*depreciated\*

Used to calculate the average utilization ratio for a loan.

$$
U\_A = \frac {B\_c - B\_o + U\_{d+1} + U\_a} {b\_i - b\_o} + \frac {U} {b\_c - b\_i}
$$

Where:\
$$U\_A =$$the average utilization ratio\
$$B\_c =$$the current utilization tracker balance\
$$B\_o =$$the utilization tracker balance at the time of loan origination\
$$U\_{d+1} =$$The utilization delta payment of the next utilization tracker transaction (this will be applied in the next utilization modifying transaction, but it needs applied now to get an accurate average utilization)\
$$U\_a =$$the utilization ratio adjustment\
$$b\_i =$$the block of the last utilization delta payment\
$$b\_o =$$the block at loan origination\
$$U =$$the current utilization ratio\
$$b\_c =$$the current block

## Accrued Interest Tracker Updates

Used to calculate accrued interest tracker updates

$$
I\_u = (b\_i-b\_{i-1})(\frac{I(U)}{b\_y}B)
$$

$$I\_u=$$ Accrued interest tracker update amount

$$b\_i=$$The block the last accrued interest tracker update occured on

$$b\_{i-1}=$$The block the accrued interest tracker update before last occured on

$$I(U)=$$Interest Rate (see [equation](#interest-rate-calculations))

$$b\_y=$$Average blocks per year. Hardcoded variable. Assumed to be 6,307,200 (5-sec ledger close time).

$$B=$$Accrued interest tracker balance

## Liability Token Calculations

Equations used to calculate the value of liability tokens and user liabilities.

### Liability Tokens Issued

The number of liability tokens issued to a user when they borrow from the pool.

$$
L = \frac{B}{I\_b+I\_u}
$$

$$L=$$ liability tokens issued

$$B=$$ Borrow amount

$$I\_b=$$ Accrued Interest tracker balance for the asset being borrowed

$$I\_u=$$ Estimated next accrued interest tracker balance

### Liability Token Value

The value of a single liability token. Used when calculating the value of a user's liability.

$$
V = I\_b+I\_u
$$

$$V=$$ The value of a liability token

$$I\_b=$$ Accrued Interest tracker balance for the asset being borrowed

$$I\_u=$$ Estimated next accrued interest tracker balance

### Liabilities Outstanding

Liabilities Outstanding for a given asset

$$
L\_o = T\_o\*V
$$

$$L\_o =$$liabilities outstanding

$$T\_o =$$liability tokens outstanding

$$V =$$liability token value

## Interest Rate Calculations

Interest rates change based on the interest threshold and rates below.

$$T\_1 =$$threshold one; initially set to 0.75\
$$T\_2 =$$threshold two; initially set to 0.90\
$$T\_3 =$$threshold three; initially set to 0.95\
$$R\_0 =$$rate zero; initially set to 0.20\
$$R\_1 =$$rate one; initially set to 1.5\
$$R\_2 =$$rate two; initially set to 7.5\
$$R\_3 =$$rate three; initially set to 15

### Base Interest Rate

Used to calculate the current interest rate when the utilization rate is below $$T\_1$$.

$$
I\_0(U) = b + U \*R\_0
$$

Where:\
$$I\_0 =$$the base interest rate\
$$U =$$the utilization ratio\
$$b =$$the base rate constant (low $$U$$). It is set by a pool data entry and controls the base interest rate for an asset; initially set to 0.05

### Interest Rate - Threshold One

Used to calculate the current interest rate when the utilization rate is above $$T\_1$$.

$$
I\_1(U) = (U-T\_1) R\_1 +I\_0(T\_1)
$$

Where:\
$$I\_1 =$$interest rate one\
$$U =$$the utilization ratio\
$$I\_0 =$$the base interest rate

### Interest Rate - Threshold Two

Used to calculate the interest rate when the utilization rate is above $$T\_2$$.

$$
I\_2(U) = (U-T\_2)R\_2 +I\_1(T\_2)
$$

Where:\
$$I\_2 =$$interest rate two\
$$U =$$the utilization ratio\
$$I\_1 =$$interest rate one

### Interest Rate - Threshold Three

Used to calculate the interest rate when the utilization rate is above $$T\_3$$.

$$
I\_3(U) = (U - T\_3)R\_3 + I\_2(T\_3)
$$

Where:\
$$I\_3 =$$interest rate three\
$$U =$$the utilization ratio\
$$I\_2 =$$interest rate two

### Average Interest Rate

Calculated using the above interest rate equations, but $$U$$ becomes an aggregated utilization ratio.

### Originating Interest Rate

Calculated using the above interest rate equations, but $$U$$ becomes an originating utilization ratio.

### Stable Rate

Used to calculate the stable interest rate for a loan.

$$
I\_s = I\_o(1+(1.05-U\_o))
$$

Where:\
$$I\_s =$$the stable rate\
$$I\_o =$$the originating interest rate\
$$U\_o =$$the utilization ratio at the time the loan was originated

## Minimum Collateral Requirement

Used to calculate the minimum collateral required for a loan.

$$
V\_c = \frac {V\_l \* 1.02} {\bar{F}}
$$

Where:\
$$V\_c =$$the minimum collateral value requirement\
$$V\_l =$$the value of the loan\
$$\bar {F} =$$the average liquidation factor of the selected collateral types

## Pool Token Calculations

### Pool Token Issuance

Used to calculate the number of pool tokens issued to a user account.

$$
O\_i = \frac {B\_n \*O\_o} {B\_c + L - B\_n}
$$

Where:\
$$O\_i =$$the number of pool tokens to be issued to the user\
$$B\_n =$$the asset balance the user deposited\
$$O\_o =$$the current number of outstanding pool tokens\
$$B\_c =$$the current asset balance amount\
$$L =$$the current number of outstanding liability tokens

### Pool Token Value

Used to calculate the value of a pool token

$$
A = \frac {(B+L)} {T\_t}
$$

Where:\
$$V =$$the value of a pool token\
$$B =$$the asset balance in the pool\
$$L =$$the total number of liability tokens outstanding\
$$T\_t =$$the total number of pool tokens

## Maximum Liquidation Amount

Used to calculate the maximum amount of a loan's value the liquidator is allowed to liquidate in order to reach a health factor of 1.02.

$$
\Delta V\_l = \frac {\bar {F\_a} \* V\_c - 1.02 \*V\_l} {\bar{I} \* \bar{F\_w} - 1.02}
$$

Where:\
$$\Delta V\_l =$$the maximum allowable liquidation amount\
$$\bar{F\_a} =$$the average liquidation for the account's collateral balances\
$$V\_c =$$the collateral value\
$$V\_l =$$the liability value\
$$\bar{I} =$$the average liquidation incentive for the collateral assets being withdrawn\
$$\bar {F\_w} =$$the average liquidation factor for the collateral assets being withdrawn

## Health Factor

Used to calculate an account's health factor.

$$
H=\frac {\sum^{|C|}*{i=1}Fi\*V*{ci}} {\sum^{|L|}*{i=1}V*{li}}
$$

Where:\
$$H =$$the account's health factor\
$$|C| =$$the number of collateral assets\
$$F\_i =$$the liquidation factor for asset $$i$$\
$$V\_{ci} =$$the collateral value of collateral asset $$i$$\
$$|L| =$$the number of outstanding loans\
$$V\_{li} =$$the liability value of loaned asset $$i$$

## Maximum Liability

Used to calculate the maximum liability an account can hold at one time.

$$
V\_l = \frac {\sum^{|C|}*{i=1} F\_i V*{ci}} {1.02}
$$

Where:\
$$V\_l =$$the maximum liability value for an account\
$$|C| =$$the number of collateral assets\
$$F\_i =$$the liquidation factor for asset $$i$$\
$$V\_{ci} =$$the collateral value of collateral asset $$i$$

## YBX Issuance

Used to calculate how much YBX to issue.

$$
I =(T-O)R
$$

Where:\
$$I =$$the number of YBX issued\
$$T =$$the total number of YBX tokens to be issued; 1,500,000,000\
$$O =$$the total number of YBX tokens outstanding\
$$R =$$the total YBX issuance rate; initially 0.0075

## Issuance Ratio

Used to calculate how much YBX to issue per liability or pool token

$$
R =\frac{A\*T}{O}
$$

Where:

$$R=$$the issuance ratio for a given liability or pool token\
$$A=$$the issuance allocation for the given liability or pool token\
$$T =$$the total number of YBX tokens to be issued for the period\
$$O =$$the total number of the given liability or pool token in claimable balances

## Pessimistic Block-Weighted Average Position Size

Used to calculate the pessimistic block-average position size for a given collateral or liability position. Used to calculate YBX issuance for a position

$$
S =\frac{S\_1\*(b\_2-b\_1)+S\_0\*(b\_1-b\_0)}{(b\_2-b\_0)}
$$

Where:

$$S=$$the positions pessimistic block-weighted average size\
$$S\_1=$$the most recent position size\
$$S\_0 =$$the previous position size\
$$b\_2 =$$the block of the most recent issuance update payment\
$$b\_1 =$$the block the position was last modified on\
$$b\_0 =$$the greater of the block of the last issuance update payment prior to the position being modified and the block the position was last modified on before the most recent modification.

## YieldBlox Default Protection Amount

Used to calculate how much of the user's liability should be taken on as pool debt as part of the Default Protection Program.

$$
R =V\_l - \frac {V\_c} {\bar {I\_a}}
$$

$$R =$$the YieldBlox Default Protection amount\
$$V\_l =$$the liability value\
$$V\_c =$$the collateral value\
$$\bar {I\_a} =$$the average liquidation incentive for the account's collateral balances


# YieldBlox Turrets

Coming Soon!


# Technical Resources

### Smart Contracts

These are still under development! A link to a public GitHub will be posted once the smart contracts are ready to share with the community!

### Audits

YieldBlox's original contributors are currently seeking third-party audits to ensure the security of the protocol.

If any parties are interested in auditing the YieldBlox Protocol, please email <support@script3.io> or reach out on social media.

### Stellar Documentation

<https://developers.stellar.org/docs>

### Stellar Turret Documentation

<https://turrets.stellar.org/>

### Bug Bounty

Bug bounty submissions will become available the once smart contracts are public.


# Community Resources

### Website

[yieldblox.finance](https://www.yieldblox.finance/)

### Discussions

[Discord](https://discord.gg/XQ6YS5usCe)

[Keybase](https://keybase.io/team/script3)


# Protocol Assets

You must use these assets in the form in which they are made available below. To avoid confusion, you may not alter the color, font, proportions, or any other aspect of these logos and design marks.

You must also set a logo or design mark off from the other content appearing in your use, and must not place it in such close proximity to other content that it is indistinguishable from that other content.

### **YieldBlox and YBX Icons**

{% file src="/files/-MgmI\_ykkxhn6ZHNImcf" %}
Logo
{% endfile %}

{% file src="/files/-MgmIemR\_qXx51uK5-WK" %}
Logo - black text
{% endfile %}

{% file src="/files/-MgmIhuCiVB1YMPe0k3U" %}
Logo - white text
{% endfile %}

[**Colors**](https://colorpeek.com/#37b04a,231f20)

### Sprout Block Emotes

{% file src="/files/-MgmIsfNaYOiuIw0UJhW" %}
Happy
{% endfile %}

{% file src="/files/-MgmIxh-6pHN8JoD6ZN0" %}
Sad
{% endfile %}

{% file src="/files/-MgmJ08hFdmO\_kClTF2K" %}
Confused
{% endfile %}

{% file src="/files/-MgmJ4nGK8-7LGl8NsbO" %}
Sleepy
{% endfile %}

{% file src="/files/-MgmJ9KQdpLvJgAAs1h6" %}
Love
{% endfile %}

{% file src="/files/-MgmJE6L0\_4gsYVMM3bI" %}
Angry
{% endfile %}

{% file src="/files/-MgmJHcw2wey9Ca8oA0R" %}
Stressed
{% endfile %}

{% file src="/files/-MgmJLCvBaL6-RHBrBmw" %}
Scooter
{% endfile %}


