GitBook: [main] 20 pages and 10 assets modified

This commit is contained in:
Alex Daddy
2021-08-07 02:27:18 +00:00
committed by gitbook-bot
parent dcfaeb3461
commit 0523e253a0
30 changed files with 2358 additions and 1 deletions

BIN
.gitbook/assets/0floor.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

BIN
.gitbook/assets/cecjing.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

BIN
.gitbook/assets/image.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

View File

@@ -1 +1,20 @@
# alex-v1-docs
# What is ALEX?
## ALEX is an open-source DeFi protocol built on [Stacks Blockchain](https://www.stacks.co) and modelled on the worlds financial markets.
To start, at ALEX you can
* Lend your BTC and earn fixed or variable interest
* Borrow BTC without risk of liquidation
* Mitigate risk with BTC short positions
* Maximize upside with BTC leveraged long positions
## Think of us as [Compound](https://compound.finance) / [AAVE](https://aave.com) with underlying technology like [Uniswap](https://www.uniswap.org) / [Balancer](https://balancer.finance), and the user experience of [Robinhood](https://www.robinhood.com).
Our initial focus \(v1\) is
* Build DeFi primitives targeting developers looking to build ecosystem on Stacks, and
* Simplify the user experience going from\(to\) CeFi to\(from\) DeFi to attract non-developers, broadening the Stacks user base.
alex-v1 implements a number of Clarity smart contracts on the core concept of Yield Tokens \("ayTokens"\). Yield Tokens allow term lending with fixed APY.

31
SUMMARY.md Normal file
View File

@@ -0,0 +1,31 @@
# Table of contents
* [What is ALEX?](README.md)
* [Lending and Borrowing at fixed yield with no risk of liquidation](lending-protocol-with-fixed-yield-and-no-risk-of-liquidation.md)
* [FAQ](faq.md)
## Protocol
* [Overview](protocol/platform-architecture-that-supports-ecosystem-development.md)
* [Collateral Rebalancing Pool](protocol/collateral-rebalancing-pool.md)
* [Yield Token Pool](protocol/automated-market-making-designed-for-lending-protocols.md)
* [Liquidity Bootstrapping Pool](protocol/liquidity-bootstrapping-pool.md)
* [Vault](protocol/vault.md)
* [Yield Farming on ALEX](protocol/yield-farming-on-alex.md)
## Developers
* [Smart Contracts](developers/smart-contracts/README.md)
* [APIs](developers/smart-contracts/apis/README.md)
* [Vault](developers/smart-contracts/apis/vault.md)
* [Equations](developers/smart-contracts/apis/equations.md)
* [Pools](developers/smart-contracts/apis/pools.md)
* [UML Diagrams](developers/smart-contracts/diagrams/README.md)
* [Use Case](developers/smart-contracts/diagrams/protocol-use-case.md)
* [Class Diagram](developers/smart-contracts/diagrams/class-diagram.md)
* [Error Codes](developers/smart-contracts/error-codes.md)
## Whitepaper
* [Automated Market Making of Yield Token Pool](whitepaper/automated-market-making-of-alex.md)

View File

@@ -0,0 +1,2 @@
# Smart Contracts

View File

@@ -0,0 +1,6 @@
---
description: Functional APIs for development reference
---
# APIs

View File

@@ -0,0 +1,111 @@
---
description: >-
Equations are smart contracts which handles rebalancing of the Pool. It is the
integral component of maintaining pool. It allows creation of any rebalancing
strategies to be deployed as a pool.
---
# Equations
## Weighted Equation
Weighted Equation is an implementation of pool maintaining logic, which balances the ration between two tokens one each pool with unique logic of ALEX. It is a basically fork of Balancer, which mainly uses constant product AMM but for ALEX, weight follows [Black & Scholes delta](https://en.wikipedia.org/wiki/BlackScholes_model). Details can be found on our whitepaper and [here](https://docs.alexgo.io/protocol/platform-architecture-that-supports-ecosystem-development#weighted-equation). Developers can use `(contract-call?)` for using this weighted equation anywhere in the smart contract.
### **get-y-given-x**
**Prototype:**
`(define-read-only (get-y-given-x (balance-x) (balance-y) (weight-x) (weight-y) (dy))`
**Input:** `uint uint uint uint uint`
**Output:** `bool | uint`
Get the appropriate value of dy from given dx which maintains the balance of given pool.
```
$ Usage
```
### **get-x-given-y**
**Prototype:**
`(define-read-only (get-x-given-y (balance-x) (balance-y) (weight-x) (weight-y) (dx))`
**Input:** `uint uint uint uint uint`
**Output:** `bool | uint`
Get the appropriate value of dx from given dy which maintains the balance of given pool.
```
$ Usage
```
### **get-**x-given-price
**Prototype:**
`(define-read-only (get-x-given-price (balance-x) (balance-y) (weight-x) (weight-y) (price))`
**Input:** `uint uint uint uint uint`
**Output:** `bool | uint`
Get the appropriate value of dx from given price which maintains the balance of given pool.
```
$ Usage
```
### **get-**token-given-position
**Prototype:**
`(define-read-only (get-token-given-position (balance-x) (balance-y) (weight-x) (weight-y) (total-supply) (dx) (dy))`
**Input:** `uint uint uint uint uint uint uint`
**Output:** `bool | uint`
Get the appropriate value of token from given parameters which maintains the balance of given pool.
```
$ Usage
```
### **get-**position-given-mint
**Prototype:**
`(define-read-only (get-position-given-mint (balance-x) (balance-y) (weight-x) (weight-y) (total-supply) (token))`
**Input:** `uint uint uint uint uint`
**Output:** `bool | uint`
Get the appropriate position value \(dx and dy\) from given parameters such as minted amount and total supply which maintains the balance of given pool.
```
$ Usage
```
### **get-**position-given-burn
**Prototype:**
`(define-read-only (get-position-given-burn (balance-x) (balance-y) (weight-x) (weight-y) (total-supply) (token))`
**Input:** `uint uint uint uint uint`
**Output:** `bool | uint`
Identical to `get-position-given-mint` since it is reverse of calculation.
```
$ Usage
```

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,61 @@
---
description: >-
Vault is smart contract that holds and manages the assets of all pools. It
keeps assets managed by other external contracts such as pool. Also, users can
trigger flash loan from vault.
---
# Vault
## ALEX-Vault
Vault is responsible for managing assets of all ALEX pools. Transaction in all the existing pools can be found in [Vault Protocol](https://docs.alexgo.io/protocol/vault).
### **get-balance**
**Prototype:**
`(define-read-only (get-balance (token)))`
**Input:** `principal`
**Output:** `bool | uint`
Get the balance of `tx-sender` of given token from vault. parameter "token'' should be an implemented token, which returns balance internally using `ft-get-balance`
```
$ Usage
```
### **get-balances**
**Prototype:**
`(define-read-only (get-balances)`
**Input:** `void`
**Output:** `bool | uint`
Get the all the list of \(token, value\) object of `tx-sender`
```
$ Usage
```
### **flash-loan**
**Prototype:**
`(define-public (flash-loan (flash-loan-user) (token1) (token2) (token3)) (amount1) (amount2) (amount3)) | (flash-loan (flash-loan-user) (token1) (token2) (amount1) (amount2))`
**Input:** `<ft-trait>, <ft-trait>, <ft-trait>, uint, uint, uint | <ft-trait>, <ft-trait>, uint, uint`
**Output:** `bool | uint`
Executes flash loan up to 3 tokens of amounts specified. User can only make 2 token inputs if executing in single pool, while can also make 3 token inputs for executing flash loan two different pools. It first transfers each tokens to user, then execute flash loan by triggering `execute` function. Validating the exact amount of returned loan is followed by execution. For the detailed use cases, check [Flash Loan Protocol](https://docs.alexgo.io/protocol/vault#flash-loan).
```
$ Usage
```

View File

@@ -0,0 +1,2 @@
# UML Diagrams

View File

@@ -0,0 +1,4 @@
# Class Diagram
![](https://yuml.me/alexgo/alex-v1-class.svg)

View File

@@ -0,0 +1,30 @@
# Use Case
## Lender
![](https://raw.githubusercontent.com/alexgo-io/alex-v1/main/diagrams/use-case-lender.svg)
## Borrower creating a loan
![](https://raw.githubusercontent.com/alexgo-io/alex-v1/main/diagrams/use-case-borrower.svg)
## Borrower repaying a loan
![](https://raw.githubusercontent.com/alexgo-io/alex-v1/main/diagrams/use-case-borrower-repay.svg)
## Liquidity Provider
![](https://raw.githubusercontent.com/alexgo-io/alex-v1/main/diagrams/use-case-lp.svg)
## Arbitrageur
![](https://raw.githubusercontent.com/alexgo-io/alex-v1/main/diagrams/use-case-arbitrageur.svg)
## Fee Collector
![](https://raw.githubusercontent.com/alexgo-io/alex-v1/main/diagrams/use-case-fee.svg)
## Putting them all together
![](https://raw.githubusercontent.com/alexgo-io/alex-v1/main/diagrams/use-case-back-end.svg)

View File

@@ -0,0 +1,100 @@
# Error Codes
## General Error
General error starts with 1000.
| Error | Code | Description |
| :--- | :---: | :---: |
| authorisation-err | 1000 | Unauthorised access |
| internal-function-call-err | 1001 | function call error in the same contract |
## Pool Error
Pool errors starts with 2000.
| Error | Code | Description |
| :--- | :---: | :---: |
| pool-already-exists-err | 2000 | Pool Already Existing |
| invalid-pool-err | 2001 | Accesing invalid Pool |
| no-liquidity-err | 2002 | Liquidity insufficient |
| invalid-liquidity-err | 2003 | Accesing Invalid Liquidity feature |
| too-many-pools-err | 2004 | Exceeded maximum number of pool |
| no-fee-x-err | 2005 | Insufficient fee for Token-X |
| no-fee-y-err | 2006 | Insufficient fee for Token-Y |
| invalid-token-err | 2007 | Accesing invalid Token |
| invalid-balance-err | 2008 | Accesing invalid balance |
| invalid-expiry-err | 2009 | expiry &gt; max-expiry |
| already-expiry-err | 2010 | current block-height &gt; expiry |
| internal-get-weight-err | 2012 | get-weight fail on pool logic |
| get-expiry-fail-err | 2013 | get-expiry fail on pool logic |
| yield-token-equation-call-err | 2014 | yield token equation calling error |
| get-price-fail-err | 2015 | get-price error |
## Vault Error
Vault errors starts with 3000.
| Error | Code | Description |
| :--- | :---: | :---: |
| transfer-failed-err | 3000 | General transfer failed |
| transfer-x-failed-err | 3001 | Transfer of Token-X failed |
| transfer-y-failed-err | 3002 | Transfer of Token-Y failed |
| insufficient-flash-loan-balance-err | 3003 | Insufficient Flash Loan balance |
| invalid-post-loan-balance-err | 3004 | Invalid Post loan balance |
| user-execute-err | 3005 | User execution error of Flashloan |
| transfer-one-by-one-err | 3006 | Error on Transfer flash loan |
| none-token-err | 3007 | Flash loan none token error |
| get-token-fail | 3008 | Token acquiring fail in flash loan |
## Equation Error
Equation error starts with 4000.
| Error | Code | Description |
| :--- | :---: | :---: |
| weight-sum-err | 4000 | Sum of weight should be always 1 |
| max-in-ratio-err | 4001 | In ratio Error |
| max-out-ratio-err | 4002 | Out ration Error |
| math-call-err | 4003 | Error while calling math functions on library |
## Math Error
Math error starts with 5000.
| Error | Code | Description |
| :--- | :---: | :---: |
| percent-greater-than-one | 5000 | percent value exceeded 1 |
| SCALE\_UP\_OVERFLOW | 5001 | scale up overflow error |
| SCALE\_DOWN\_OVERFLOW | 5002 | scale down overflow error |
| ADD\_OVERFLOW | 5003 | addition overflow |
| SUB\_OVERFLOW | 5004 | subtraction overflow |
| MUL\_OVERFLOW | 5005 | multiplication overflow |
| DIV\_OVERFLOW | 5006 | division overflow |
| POW\_OVERFLOW | 5007 | power operation overflow |
| MAX\_POW\_RELATIVE\_ERROR | 5008 | max pow relative error |
| X\_OUT\_OF\_BOUNDS | 5009 | parameter x out of bounds |
| Y\_OUT\_OF\_BOUNDS | 5010 | parameter y out of bounds |
| PRODUCT\_OUT\_OF\_BOUNDS | 5011 | product of x and y out of bounds |
| INVALID\_EXPONENT | 5012 | exponential error |
| OUT\_OF\_BOUNDS | 5013 | general out of bounds error |
| fixed-point-err | 5014 | catch-all for math-fixed-point errors |
| | | |
## Token Error
Token error starts with 6000.
| Error | Code | Description |
| :--- | :---: | :---: |
| get-symbol-fail-err | 6000 | get-symbol failed |
## Oracle Error
Token error starts with 7000.
| Error | Code | Description |
| :--- | :---: | :---: |
| get-oracle-price-fail-err | 7000 | get-price failed |
| err-token-not-in-oracle | 7001 | Token cannot be found on given oracle source |

81
faq.md Normal file
View File

@@ -0,0 +1,81 @@
# FAQ
## Why Stacks?
Stacks makes Bitcoin programmable, enabling decentralized apps and smart contracts that inherit all of Bitcoins powers. Back-of-envelope calculation tells us that the DeFi market on Bitcoin could be as big as $300bn. ALEX will be part of it. We are one of the first DeFi projects on Stacks. And we are building the DeFi primitives essential to more sophisticated DeFi projects.
For example, with ALEX on Stacks, Bitcoin holders will be able to lend and borrow Bitcoin with better user experience at a more competitive rate. Bitcoin traders can build sophisticated services and strategies on ALEX to provide liquidity and participate in yield farming across multiple pools available at ALEX. Start-ups can issue tokens and raise Bitcoin on ALEX to build better community-owned projects with low capital requirements from the team.
## How does Stacks allow much better DeFi user experience for Bitcoin holders?
Currently for a Bitcoin holders to use DeFi on Ethereum, he/she needs to “wrap” his/her Bitcoin.
This means:
1. The Bitcoin holder needs to find a WBTC merchant,
2. Opens an account subject to KYC/AML,
3. Transfer BTC to the merchant,
4. The merchant then goes to a WBTC custodian,
5. Transfers BTC to the custodian,
6. The custodian mints/transfers WBTC to the custodian,
7. The custodian transfers WBTC to the holder,
8. Now the holder can use WBTC to use DeFi on Ethereum.
On Stacks, the same Bitcoin holder would do the following:
1. The Bitcoin holder uses his/her BTC to use DeFi on Stacks.
2. \(and thats it!\)
The key technical difference between Stacks and Ethereum, that allows Stacks to do the above, is that Stacks has a read access to Bitcoin blockchain state \(something not possible on Ethereum\).
So smart contracts written on Stacks can see BTC being locked and issue “wrapped” BTC, which can then be used freely on Stacks.
Such a “wrapping” of BTC on Stacks, however, is done by a smart contract and does not affect the holders user experience \(i.e. that process is invisible to him/her\).
So from the user experience perspective, you are almost natively accessing Bitcoin on Stacks.
Compared to using WBTC on ETH, a Bitcoin holder, therefore, is not subject to:
* Intermediary risk \(of WBTC merchant and custodian\),
* KYC/AML process \(duplicate/redundant for many, if not most, existing BTC holders\), and
* Costs \(which can be expensive\) to convert from BTC to WBTC and vice versa.
## What tokens can and will ALEX support?
ALEX will support all native/SIP10-compatible tokens on Stacks.
## Who are the key actors on ALEX?
There are five actors on ALEX:
* **Lender**: Go to Yield Token Pool =&gt; Sell Token / Buy ayToken
* **Borrower**: Go to Collateral Rebalancing Pool =&gt; Deposit Collateral =&gt; Mint ayToken =&gt; Go to Yield Token Pool =&gt; Sell ayToken / Buy Token
* **Liquidity Provider**: Go to Yield Token Pool =&gt; Deposit ayToken & Token =&gt; Mint Yield Token Pool Token
* **Arbitrageur / Flash Loan User**: Go to Vault =&gt; Create Flash Loan =&gt; Trade at Pools
See[ Use Case](https://docs.alexgo.io/developers/smart-contracts/diagrams/protocol-use-case).
## What Collateralization Ratio \(or Loan-to-Value\) can we expect on ALEX?
While details are being finalized, we can expect, for example, a collateralization ratio of 1.25x \(i.e. 80% LTV\) for a BTC loan against USD stablecoin collateral.
Further, lending and borrowing on ALEX will not be subject to liquidation risk.
All of this is made possible by our [Collateral Rebalancing Pool](protocol/collateral-rebalancing-pool.md), which dynamically rebalances between borrowed token and collateral to manage the default risk.
## What kind of transaction fee and speed do you require?
The design of our [Collateral Rebalancing Pool ](https://docs.alexgo.io/protocol/collateral-rebalancing-pool)requires low transaction fee. The transaction fee on Stacks at the moment is negligible.
The Bitcoin block time is too slow to support decentralized apps like ALEX. To work around Bitcoin's limited speed, Stacks uses microblocks that result in near-instant confirmation on the Stacks blockchain. At the rate of the Bitcoin block time, these blocks will settle from Stacks to Bitcoin to provide the finality and security of Bitcoin.
Scaling independently of Bitcoin ensures that Stacks transactions are fast enough for ALEX, while still benefiting from Bitcoins security and settlement.
## Will you provide cross chain capability?
Yes, we will develop cross chain capability in the future. Our [core architecture](https://docs.alexgo.io/protocol/platform-architecture-that-supports-ecosystem-development) is not tied to Stacks.
## Whats your borrowing rate right now?
Our lending and borrowing rates are [market driven](https://docs.alexgo.io/protocol/automated-market-making-designed-for-lending-protocols).

View File

@@ -0,0 +1,32 @@
# Lending and Borrowing at fixed yield with no risk of liquidation
## Lending at fixed yield for a fixed term
Buying of ayToken \(against Token\) equates to lending of Token at the rate implied by the price of ayToken until T. Holding ayToken until T allows the holder to accrue, with certainty, at a fixed rate \(as implied by the price at which holder bought ayToken\). Selling of ayToken before T could result in a profit or loss, depending on the prevailing price of ayToken.
![](https://raw.githubusercontent.com/alexgo-io/alex-v1/main/diagrams/use-case-lender.svg)
ALEX provides a fixed schedule of maturities for each Token to allow liquidity aggregation. On a regular basis, a new ayToken is launched, whose liquidity is bootstrapped using Liquidity Bootstrapping Pool.
## Borrowing at fixed yield for a fixed term with no risk of liquidation
Minting of ayToken by adding eligible collateral to a collateral pool and selling of ayToken against Token equates to the borrowing of Token at the rate implied by the price at which ayToken was sold.
### Creating a loan
![](https://raw.githubusercontent.com/alexgo-io/alex-v1/main/diagrams/use-case-borrower.svg)
### Repaying a loan
![](https://raw.githubusercontent.com/alexgo-io/alex-v1/main/diagrams/use-case-borrower-repay.svg)
The collateral pool will dynamically rebalance between Token and eligible collateral to ensure the solvency of ayToken. The dynamic rebalancing of collateral is akin to a real-time margining of the loan, minimising counterparty risk.
For example, ayBTC / USD pool \(i.e. borrow BTC against USD\) will implement a dynamic hedging strategy against BTC upside \(i.e. sell USD and buy BTC as BTC spot goes up, and vice versa\). The resulting rebalancing between USD and BTC will be then executed by arbitrageurs participating in the pool pricing curve. See some illustration [here](https://docs.google.com/spreadsheets/d/1nSg6L30iedpk_rLhq3E7Zv8ct3Myb_D8oWmgJzwtwtw/edit?usp=sharing). The borrower effectively is an LP \(and receives ayBTC as the PoolToken\) and the USD collateral provided will be automatically converted into a basket of USD and BTC.
The main benefit of such dynamic rebalancing is that we can be \(much\) more aggressive in LTV and remove liquidation entirely \(with appropriate LTV and reserve fund\). This also allows aggregation of all ayToken into a single pool \(rather than separate pool for each borrower\).
The main drawback is that the collateral received at the time of repayment will not be same in USD value as the original value \(due to rebalancing\).
To those interested in understanding the mathematics behind it, please refer to [Collateral Rebalancing Pool](https://docs.alexgo.io/protocol/collateral-rebalancing-pool).

View File

@@ -0,0 +1,56 @@
# Yield Token Pool
Please refer to our [white paper](https://docs.alexgo.io/whitepaper/automated-market-making-of-alex) for a more rigorous treatment on the subject.
## Lending and Borrowing Process
ALEX's core product is essentially a zero coupon bond in conventional finance. A key benefit is reduced uncertainty about a loan's interest rate, resulting in better financial planning. Specifically, prior to entering a loan contract, borrowers and lenders secure the loan's interest rate and tenor on ALEX.
Here is a concrete example. Rachel has 100 USD. She wants to increase her 100 USD. She chooses to lend her assets out. She's ok with lending out her 100 USD for a fixed term of three months. She goes to ALEX's interface. There, Rachel can see that "three month ayUSD" is currently priced at 0.9 vs USD. Put simply, 1 ayUSD gets her 0.9 USD. She takes her 100 USD and exchanges it for ayUSD. Given the current exchange rate, she gets about 110 ayUSD. Now she waits. Three months pass. Now, Rachel can exchange her 110 ayUSD for USD again. The rate is 1 ayUSD to 1 USD. So Rachel gets 110 USD. That's a gain of 10 USD over 3 months. Pretty nice!
Here is the general story. Borrowers and lenders enter a loan contract. Specifically, they swap a forward contract based token called "ayToken" with "Token". "Token" is the underlying asset. For example, they swap ayUSD with USD. More generally, the lender lends out "Tokens" and obtains "ayToken" in return. The price of "Token" is lower than its par value. The contract starts when a lender deposits "Token" in an ALEX pool. Then, upon expiration, the lender redeems the underlying asset, "Token", at par value. Because the lender lent out their "Token" at discounted price some time ago, and now redeems "Token" for par value, there is a profit. Pretty nice!
In mathematical terms, the interest rate r is calculated as $$p_{t}=\frac{1}{e^{rt}}$$, where $$p_{t}$$ is the spot price of ayToken and the interest rate is assumed to compound. The formula utilises one of the most fundamental principles in asset pricing: an asset's present value is the asset's discounted future value. Thus, in our simplified example, $$t$$= 1 and $$r=\log\frac{1}{0.9}\approx10\%$$.
## Automated Market Making \(AMM\) Protocol
When designing the AMM protocol, ALEX believes the following:
1. AMMs are mathematically neat and reflect economic demand and supply. For example, price should increase when demand is high or supply is low;
2. AMMs are a type of mean, which remains constant during trading activities. This approach is also adopted by popular platforms such as _Uniswap,_ which employ algorithmic means; and
3. AMMs can be interpreted through the lens of modern finance theory. Doing so enables ALEX to grow and draw comparisons with conventional finance.
After extensive research, our beliefs led us to an AMM first proposed by _YieldSpace_. While we appreciate the mathematical beauty of their derivation, we adapt it in several ways with _ALEX_. For example, we replace a simple interest rate with a compounding interest rate. This change is in line with standard uses in financial pricing and modelling since Black and Scholes. We also develop a new capital efficiency scheme, as explained below.
In mathematical terms, our AMM can be expressed as:
$$
x^{1-t}+y^{1-t}=L
$$
where $$x$$, $$y$$, $$t$$ and $$L$$ are, respectively, the balance of "Token", balance of "ayToken", time to maturity and a constant term when $$t$$ is fixed. The interest rate $$r$$ is defined as $$r=\log\left(\frac{y}{x}\right)$$, i.e. the natural logarithm of the ratio of balance between "ayToken" and "Token", while the price of "ayToken" with respect to "Token" is $$\left(\frac{y}{x}\right)^{t}$$.
Our design depicts an AMM in the of a form of a generalised mean. It makes economic sense because the shape of the curve is decreasing and convex. It incorporates time to maturity $$t$$, which is explicitly built-in to derive ayToken's spot price. We refer readers to our [white paper](https://docs.alexgo.io/whitepaper/automated-market-making-of-alex) for detail.
## Liquidity Providers \(LP\) and Capital Efficiency
LPs deposit both ayToken and Token in a pool to facilitate trading activities. LPs are typically ready to market-make on all possible scenarios of interest rate movements ranging from $$-\infty$$ to $$+\infty$$. However, part of the interest rates curve or movements will never be considered by market participants. On example is the part where the interest rate is negative. Although negative rates can be introduced in the fiat world by central bankers as monetary policy tool, yield farmers in the crypto world are still longing everything to be positive. In ALEX, positive rate refers to spot price of ayToken not exceeding 1 and ayToken reserve is larger than Token.
Inspired by _Uniswap v3_, ALEX employs virtual tokens - part of the assets that will never be touched, hence is not required to be held by LP.
![Figure 1](../.gitbook/assets/cecjing.png)
Figure 1 illustrates an example of adopting virtual tokens in the event of positive interest rate. The blue line is the standard AMM. The blue dot marks an equal balance of Token and ayToken of $$y_{v}$$, meaning there is no, or a 0%, interest rate. $$y_{v}$$ is the boundary amount, as any amount lower than it will never be touched by LP to avoid negative rate, which is represented by blue dashed line. Thus, $$y_{v}$$ is virtual token reserve. Effectively, LP is market-making on the red line, which shifts the blue line lower by $$y_{v}$$. When ayToken is depleted as shown by red dashed line, trading activities are suspended.
A numerical example provided in Table 1 shows capital efficiency with respect to various interest rate, assuming $$t$$= 0.5 and $$L$$= 20 for illustration's sake. When the current interest rate$$r$$= 10%, LPs are required to deposit 95 token and 105 ayToken according to standard AMM. However, if the interest rate is floored at 0%, LP only needs to contribute 5 ayToken, as the rest 100 ayToken would be virtual. This is a decent saving more than 90%.
![Table 1: Capital Efficiency when Interest Rate is Floored at 0](../.gitbook/assets/cectable3.png)
## Yield Curve and Yield Farming
By expressing the interest rate as $$p_{t}=\frac{1}{e^{rt}}$$, i.e. $$r=-\frac{1}{t}\log p_{t}$$, we can obtain a series of interest rates from trading pool prices with respect to various maturities, based on which we are able to build a yield curve. The Yield curve is the benchmark tool for modelling risk-free rates in conventional finance. The shape of the curve dictates expectations about future interest rate path, which helps market participants understand market behaviours and trends. Currently we might be able to build a Bitcoin yield curve from Bitcoin futures listed on the Chicago Mercantile Exchange \(CME\). However, not only is the exchange heavily regulated, its trading volume is skewed to the very short dated front end contracts lasting several months only. ALEX aims to offer future contracts up to 1y when the platform goes live. Should markets mature, ALEX may extend to longer tenors.
Yield farmers can benefit from understanding the yield curve by purchasing ayToken whose tenor corresponds to high interest rates and selling ayToken whose tenor associates with low interest rates. This is a typical “carry" strategy.
Last but not least, based on the development of the yield curve and solid design work of our AMM, ALEX will be able to provide more products. Specifically, ALEX will be able to offer derivatives, including options and structured products, building on and extending a large amount of literatures and applications in conventional finance.

View File

@@ -0,0 +1,24 @@
# Collateral Rebalancing Pool
Collateral Rebalancing Pool \("CRP"\) uses [Weighted Equation](https://docs.alexgo.io/protocol/platform-architecture-that-supports-ecosystem-development) and dynamically rebalances between Token and Collateral.
CRP dynamically rebalances collateral to ensure the ayToken minted \(i.e. the loan\) remain solvent especially in an adverse market environment \(i.e. the value of the loan does not exceed the value of collateral\). This dynamic rebalancing, together with a careful choice of the key parameters \(including LTV and volatilty assumption\) allows ALEX to eliminate the needs for liquidation. Any residual gap risk \(which CRP cannot address entirely\) is addressed through maintaining a strong reserve fund.
For example, ayBTC / USD pool \(i.e. borrow BTC against USD\) will implement a dynamic hedging strategy against BTC upside \(i.e. sell USD and buy BTC as BTC spot goes up, and vice versa\). The resulting rebalancing between USD and BTC will be then executed by arbitrageurs participating in the pool pricing curve. See some illustration [here](https://docs.google.com/spreadsheets/d/1nSg6L30iedpk_rLhq3E7Zv8ct3Myb_D8oWmgJzwtwtw/edit?usp=sharing). The borrower effectively is an LP \(and receives ayBTC as the Pool Token\) and the USD collateral provided will be automatically converted into a basket of USD and BTC.
The main benefit of such collateral rebalancing is that we can be \(much\) more aggressive in LTV and remove liquidation entirely \(with appropriate LTV and reserve fund\). This also allows aggregation of all ayToken into a single pool \(rather than separate pool for each borrower\).
The main drawback is that the collateral received at the time of repayment will not be same in USD value as the original value \(due to rebalancing\).
When a Borrower mints ayToken by providing appropriate Collateral, the Collateral is converted into a basket of Collateral and Token, with the weights determined by CRP. CRP determines the weights based on the prevailing LTV and uses the following formula:
$$
\begin{split}
&w_{Token}=N\left(d_{1}\right)\\
&w_{Collateral}=\left(1-w_{Token}\right)\\
&d_{1}= \frac{1}{\sigma\sqrt{t}}\left[\ln\left(\frac{LTV_{t}}{LTV_{0}}\right) + t\times\left(APY_{Token}-APY_{Collateral} + \frac{\sigma^2}{2}\right)\right]
\end{split}
$$
Some readers may note the similarity of the above formula to the [Black & Scholes delta](https://en.wikipedia.org/wiki/BlackScholes_model), because it is. CRP essentially implements a delta replicating strategy of a call option on Token / Collateral, buying more Token when LTV moves higher and vice versa.

View File

@@ -0,0 +1,14 @@
# Liquidity Bootstrapping Pool
Liquidity Bootstrapping Pool \("LBP"\) uses [Weighted Equation](https://docs.alexgo.io/protocol/platform-architecture-that-supports-ecosystem-development) and is designed to facilitate a capital efficient launch of a token \(the "Base Token"\) relative to another token \(the "Target Token"\).
LBP is used to initialise all Yield Token Pools \(with ayToken being the Base Token and Token being the Target Token\).
Initially, a bigger weight \(say 80%\) is assigned to Base Token, while the remaining \(say 20%\) is assigned to Target Token. The weights are gradually rebalanced to allow for the sale of Base Token and an efficient discovery of its price relative to the Target Token.
LBP was first offered by [Balancer](https://docs.balancer.fi/v/v1/guides/smart-pool-templates-gui/liquidity-bootstrapping-pool) in 2020 and can be an interesting alternative to ICOs, IDOs or IEOs to bootstrap liquidity with little initial investment from the team.
ALEX brings LBP to Stacks, allowing Stacks projects to build deep liquidity and find its price efficiently with low capital requirements.
LBPs can result in a significantly better-funded project whose governance tokens are more evenly distributed among the community. This means the tokens remain in the hands of those that are invested in the project in the long term, instead of speculators looking for quick profits.

View File

@@ -0,0 +1,54 @@
# Overview
ALEX allows for implementation of arbitrary trading strategies and borrows from [Balancer V2](https://docs.balancer.fi).
Equation abstracts rebalancing and market making logic, while Pool encapsulates the value of a strategy. Pool abstraction allows aggregation of the assets of all ALEX pools into a single vault, bringing many advantages over traditional DEX architecture.
## Equation
Equation triggers Pool rebalancing. This allows creation of any arbitrary rebalancing strategies to be deployed as a pool.
### Weighted Equation
Weighted Equation \("WE"\) is the most basic Equation of all and is a fork of [Balancer](https://balancer.fi/whitepaper.pdf), which generalised the constant product AMM popularised by Uniswap. We implement the following formula:
$$
V=\prod_{i}B_{i}^{w_{i}}
$$
Where $$V$$is a constant, $$B_{i}$$ is the balance of token i and $$w_{i}$$ is the weight of token i in the pool.
As the price of each token changes, arbitrageurs rebalance the pool by making trades. This maintains the desired weighting of the value held by each token whilst collecting trading fees from the traders.
### Yield Token Equation
Yield Token Equation \("YTE"\) drives [Yield Token Pool](https://docs.alexgo.io/protocol/automated-market-making-designed-for-lending-protocols). It follows [Yield Space](https://yield.is/YieldSpace.pdf) and is designed specifically to facilitate efficient trading between ayToken and Token. Our main contribution is to extend the model to allow for capital efficiency from liquidity provision perspective \(inspired by [Uniswap V3](https://uniswap.org/whitepaper-v3.pdf)\).
For example, if a pool is configured to trade between 0% and 10% APY, the capital efficiency can improve to 40x compared to when the yield can trade between $$-\infty$$ and $$+\infty$$.
## Pool
Pools handle the logic of dynamic trading strategies, whose token rebalancing are then handled by Vault. Rebalancing logic is driven by Equation. Pool issues Pool Token to liquidity providers. The number of Pool Tokens are determined based on a liquidity provider's relative contribution to the Pool. Pool Tokens thus represent proportional ownership of that Pool, or assets in that Pool.
### Fixed Weight Pool
Fixed Weight Pool \("FWP"\) is a fork of [Balancer Weighted Pool](https://docs.balancer.fi/core-concepts/protocol/pools#weighted-pools).
### Collateral Rebalancing Pool
Collateral Rebalancing Pool \("CRP"\) uses Weighted Equation and dynamically rebalances between Token and Collateral. CRP dynamically rebalances collateral to ensure the ayToken minted \(i.e. the loan\) remains solvent especially in an adverse market environment \(i.e. the value of the loan does not exceed the value of collateral\).
### Yield Token Pool
Yield Token Pool \("YTP"\) uses Yield Token Equation and is designed specifically to facilitate efficient trading between ayToken and Token.
### Liquidity Bootstrapping Pool
Liquidity Bootstrapping Pool \("LBP"\) uses Weighted Equation and is designed to facilitate a capital efficient launch of a token \(the "Base Token"\) relative to another token \(the "Target Token"\).
LBP is used to initialise all Yield Token Pools \(with ayToken being the Base Token and Token being the Target Token\).
## Vault
Vault holds and manages the assets of all ALEX pools. The separation of pool and vault has many benefits including, among others, cheaper transaction costs for users and quicker learning curve for developers when building custom pools on ALEX.

14
protocol/vault.md Normal file
View File

@@ -0,0 +1,14 @@
# Vault
Vault holds and manages the assets of all ALEX pools. The separation of pool and vault has many benefits including, among others, cheaper transaction costs for users and quicker learning curve for developers when building custom pools on ALEX.
## Flash Loan
Aggregating the assets of all ALEX pools into a single vault allows for the offering of Flash Loan, [popularized by AAVE](https://aave.com/flash-loans/).
Flash Loans are uncollateralized loans that must be repaid \(plus interest\) in the same transaction as it is borrowed. Since everything done with the loan must be completed in a single transaction, there are codified guarantees that make it impossible for borrowers to run away with the tokens.
Flash Loan allows arbitrageurs to take advantages of any price discrepancies in two or more pools without the needs for holding any input tokens.
![](https://raw.githubusercontent.com/alexgo-io/alex-v1/main/diagrams/use-case-arbitrageur.svg)

View File

@@ -0,0 +1,16 @@
# Yield Farming on ALEX
A high LTV \(even on a static collateral\) can be offered between ayTokens of different maturities. For example, ayToken-1y as collateral may achieve 90% LTV to mint ayToken-O/N \(similar to borrowing overnight to buy long-term asset\). This allows "yield farming" whereby you repeat the process of buying ayToken-1y, use it as collateral to mint and sell ayToken-O/N for Token \(to buy ayToken-1y\) to achieve a high APY \(assuming ayToken-1y APY &gt; ayToken-O/N APY\).
![Yield Farming Use Case](https://raw.githubusercontent.com/alexgo-io/alex-v1/main/diagrams/use-case-yield-farming.svg)
For example, Rachel spends 100 BTC and buys ayBTC-1y. She uses it as collateral to borrow ayBTC-O/N at 90% LTV. She then sells the borrowed ayBTC-O/N and buys more ayBTC-1y. She uses it as collateral to borrow ayBTC-O/N at 90% LTV. She repeats this process.
If 1y APY is 10% and O/N APY is 5%, the above "yield farming" results in APY approaching 55%.
Mathematically,
$$r=\frac{1+r{1y}}{1-LTV}-\left(1+\frac{r{1d}}{365}\right)^{365}\left(\frac{LTV}{1-LTV}\right)-1$$
An illustration is available [here](https://docs.google.com/spreadsheets/d/1L-52KHFl7O_h22Fg4gpZKczdPEXuAt5yAh2gX3BQP58/edit?usp=sharing).

View File

@@ -0,0 +1,414 @@
# Automated Market Making of Yield Token Pool
## Abstract
ALEX aims to provide a fixed rate borrowing and lending service with pre-determined maturity in the world of decentralised finance \(DeFi\). We include forward contracts in our trading pool, with Automated Market Making \(AMM\) engine in association with generalised mean. While we formalise the trading practise swapping forward contracts with underlying asset, we incorporate the latest innovation in the industry - concentrated liquidity. Consequently, liquidity provider of ALEX can save decent amount of capital by making markets on a selected range of interest rate.
## Introduction
ALEX stands for **A**utomated **L**iquidity **EX**change. It is a hybrid of automated market making and on-chain loanable fund built on Stacks blockchain network. While lenders and borrowers can minimise uncertainty by securing the loan with fixed rate and tenor, liquidity providers are able to take advantage of our capital efficiency mechanism by imposing cap and floor on the interest rate. This allows liquidity to be offered on parts of the curve that contains majority of trading activities and leads to efficient capital management.
On ALEX, lending and borrowing activities are facilitated by a forward contract based token “ayToken”. It is similar to an OTC bilateral forward contract in the conventional financial market, which specifies underlying asset “Token” and expiry date. This paper assumes ayToken is minted and ready to be exchanged. Lenders purchase ayToken at a discount to the spot Token price when the contract is initiated and reclaim underlying asset upon expiration when forward price converges to spot price. Borrowers sell ayToken in return for Token on day one and return Token upon expiration. Implied interest rate depends on how much discount that the forward price is to the spot price at the time of transaction, which is executed on AMM.
Last but not least, ALEX hopes to bridge the gap between Defi and conventional finance by applying an AMM protocol derived from one of the basic instruments in fixed income market - zero coupon bond firstly proposed by [Yield Space](https://yield.is/YieldSpace.pdf). This empowers ALEX to learn from the fiat world and offer more decentralised financial products in the future.
This paper focuses on technical aspects of AMM and is the first of a series of ALEX papers unveiling all exciting features and applications of ALEX development.
## AMM and Invariant Function
ALEX AMM is built on three beliefs: \(i\) it is mathematically neat and reflect economic demand and supply; \(ii\) it is a type of mean, like other AMMs; and \(iii\) it is derived and can be interpreted in terms of yield and is somehow related to conventional finance, where research has been conducted for decades.
We will firstly review some desirable features of AMM that ALEX hopes to exhibit.
### Properties of AMM
AMM protocol, which provides liquidity algorithmically, is the core engine of Defi. In the liquidity pool, two or more assets are deposited and subsequently swapped resulting in both reserve and price movement. The protocol follows an invariant function $$f(X)=L$$, where $$X=\left(x_1,x_2,\dots,x_d\right)$$ is $$d$$ dimension representing $$d$$ assets and $$L$$ is constant. When $$d=2$$, which is the common practise by a range of protocols, AMM $$f(x_1,x_2)=L$$ can be expressed as $$x_2=g(x_1)$$. Although it is not always true, $$g$$ tends to be twice differentiable and satisfies the following
* monotonically decreasing, i.e. $$\frac{dg(x_1)}{dx_1}<0$$. This is because price is often defined as $$-\frac{dg(x_1)}{dx_1}$$. A decreasing function ensures price to be positive.
* convex, i.e. $$\frac{d^2g(x_1)}{dx_1^2} \geq 0$$. This is equivalent to say that $$-\frac{dg(x_1)}{dx_1}$$ is a non-increasing function of $$x_1$$. It is within the expectation of economic theory of demand and supply, as more reserve of $$x_1$$ means declining price.
Meanwhile, $$f$$ can usually be interpreted as a form of mean, for example, [mStable](https://docs.mstable.org) relates to arithmetic mean, where $$x_1+x_2=L$$ \(constant sum formula\); one of the most popular platforms [Uniswap](https://uniswap.org/whitepaper-v3.pdf) relates to geometric mean, where $$x_1 x_2=L$$ \(constant product formula\); [Balancer](https://balancer.fi/whitepaper.pdf), which our collateral rebalancing pool employs, applies weighted geometric mean. Its AMM is $$x_1^{w_1} x_2^{w_2}=L$$ where $$w_1$$ and $$w_2$$ are fixed weights. However, none of these three protocols consider time to maturity, which is essential in modern interest rate theory.
### ALEX AMM
After extensive research, we consider it possible for ALEX AMM to be connected to generalised mean defined as
$$
\left( \frac{1}{d} \sum _{i=1}^{d} x_i^p \right)^{\frac{1}{p}}
$$
where $$0 \leq p \leq 1$$. The expression might remind readers of $$p$$-norm when $$x_i \geq 0$$. It is however not true when $$p<1$$ as triangle inequality doesn't hold.
When $$d=2$$ and $$p$$ is fixed, the core component of generalised mean is assumed constant as below.
$$
x_1^p+x_2^p=L
$$
This equation is regarded reasonable as AMM, because \(i\) function $$g$$ where $$x_2=g(x_1)$$ is monotonically decreasing and convex; and \(ii\) The boundary value of $$p=1$$ and $$p=0$$ corresponds to constant sum and constant product formula respectively. When $$p$$ increases from 0 to 1, price $$-\frac{dg(x_1)}{x_1}$$ gradually converges to 1. This is what ALEX hopes to achieve when forward becomes spot. This also means that $$p$$ is somehow related to time to maturity. Please refer to [Appendix 1](automated-market-making-of-alex.md#appendix-1-generalised-mean-when-d-2) for a detailed discussion.
In the benchmark research piece by [Yield Space](https://yield.is/YieldSpace.pdf), the invariant function above is formalised from the perspective of zero coupon bond. $$p$$ is replaced by $$1-t$$ where $$t$$ is time to maturity and $$L$$ is a function of $$t$$, so that
$$
x_1^{1-t}+x_2^{1-t}=L\left(t\right)
$$
This is derived by solving the following differential equation when $$t \neq 1$$
$$
-\frac{dx_2}{dx_1}=\left(\frac{x_2}{x_1} \right)^t
$$
In the rest of the paper, to be consistent with [Yield Space](https://yield.is/YieldSpace.pdf), we employ notations below
* $$x$$ : balance of the underlying Token
* $$y$$ : balance of ayToken
* $$r$$ : implied interest rate, defined as the natural logarithm of balance of ayToken and Token
$$
r=log \left( \frac{y}{x} \right)
$$
* $$p$$ : price of Token in terms of ayToken. The commonly quoted ayToken price is the inverse, i.e. $$\frac{1}{p}$$
$$
p=\left(\frac{y}{x} \right)^t=e^{rt}
$$
ALEX's implied interest rate is compound. Not only does the compound rate allow us to derive mathematical formulas throughout the paper, we can also conduct further research and offer more products by referring to vast amount of literatures and applications in conventional finance, which is largely built on Black-Scholes model with compound rate employed as the discounting factor.
Using notations above, the invariant function is rewritten as $$x^{1-t}+y^{1-t}=L$$ with the differential equation $$-\frac{dy}{dx}=\left(\frac{y}{x} \right)^t$$. Unless specified, we assume $$L$$ constant and call it invariant constant. This means that $$t$$ is fixed and there is no minting or burning coins. In practise, liquidity providers can add or reduce liquidity, and $$L$$ needs to be recalibrated daily when $$t$$ changes.
Though purely theoretical at this stage, [Appendix 2](automated-market-making-of-alex.md#appendix-2-liquidity-mapping-to-uniswap-v3) maps $$L$$ to the liquidity distribution of [Uniswap V3](https://uniswap.org/whitepaper-v3.pdf). This is motivated by an independent research from [Paradigm](https://www.paradigm.xyz/2021/06/uniswap-v3-the-universal-amm/).
## Trading Formulae
Market transaction, which involves exchange of Token and ayToken, satisfies the invariant function. While fee is deposited back to the liquidity pool in some protocols, such as _Uniswap V2_, resulting in slight increase of $$L$$ after each transaction, ALEX counts the fee separately. This is consistent with [Uniswap V3](https://uniswap.org/whitepaper-v3.pdf). Hence $$L$$ remains constant.
### Out-Given-In
In order to purchase $$\Delta y$$ amount of ayToken from the pool, the buyer needs to deposit $$\Delta x$$ amount of Token. $$\Delta x$$ and $$\Delta y$$ satisfy the following
$$
(x+\Delta x)^{1-t}+(y-\Delta y)^{1-t}=x^{1-t}+y^{1-t}
$$
After each transaction, balance is updated as below: $$x\rightarrow x+\Delta x$$ and $$y\rightarrow y-\Delta y$$. Balance of $$y$$ should not be less than that of $$x$$ to avoid negative interest rate, which will be discussed in detail later. Rearranging the formula results in
$$
\Delta y=y-\left[x^{1-t}+y^{1-t}-(x+\Delta x)^{1-t}\right]^{\frac{1}{1-t}}
$$
When transaction cost exists, the actual deposit to the pool is less than $$\Delta x$$. Assuming $$\lambda\Delta x$$ is the actual amount and $$(1-\lambda)\Delta x$$ is the fee, above can now be expressed as
$$
\begin{split}
&(x+\lambda\Delta x)^{1-t}+(y-\Delta y)^{1-t}=x^{1-t}+y^{1-t}\\
&\Delta y=y-\left[x^{1-t}+y^{1-t}-(x+\lambda\Delta x)^{1-t}\right]^{\frac{1}{1-t}}
\end{split}
$$
To keep $$L$$ constant, the updated balance is: $$x\rightarrow x+\lambda\Delta x$$ and $$y\rightarrow y-\Delta y$$.
### In-Given-Out
This is the opposite case to above. We are deriving $$\Delta x$$ from $$\Delta y$$.
$$
\Delta x=\frac{1}{\lambda}{\left[x^{1-t}+y^{1-t}-(y-\Delta y)^{1-t}\right]^{\frac{1}{1-t}}-x}
$$
### In-Given-Price / Yield
Sometimes, trader would like to adjust the price/yield, perhaps due to deviation of AMM price to the market value. Define $$p'$$ the AMM price after rebalancing the Token and ayToken in the pool
$$
p'=\left(\frac{y-\Delta y}{x+\lambda\Delta x}\right)^{t}
$$
Then, the added amount of $$\Delta x$$ can be calculated from the formula below
$$
\begin{split}
&(x+\lambda\Delta x)^{1-t}+(y-\Delta y)^{1-t}=x^{1-t}+y^{1-t}\\
&1+\left(\frac{y}{x}\right)^{1-t}=\left(1+\lambda\frac{\Delta x}{x}\right)^{1-t}+(\frac{y-\Delta y}{x})^{1-t}\\
&1+p^{\frac{1-t}{t}}=\left(1+\lambda\frac{\Delta x}{x}\right)^{1-t}+p'^{\frac{1-t}{t}}\left(1+\lambda\frac{\Delta x}{x}\right)^{1-t}\\
&\Delta x=\frac{x}{\lambda}\left[\left(\frac{1+p^{\frac{1-t}{t}}}{1+p'^{\frac{1-t}{t}}}\right)^{\frac{1}{1-t}}-1\right]\\
\end{split}
$$
Denote $$r$$ and $$r'$$ the current and trader's target interest rate respectively. Because $$p=e^{rt}$$ and $$p'=e^{r't}$$, the above equation can also be rewritten as
$$
\Delta x=\frac{x}{\lambda}\left[\left(\frac{1+e^{r(1-t)}}{1+e^{r'(1-t)}}\right)^{\frac{1}{1-t}}-1\right]
$$
### Transaction Cost on Notional and Yield
In the previous sections, fee is in proportion to the notional amount. This is consistent with AMM such as _Uniswap_. However, it could be hard to interpret in the yield space, as market participants tend to think of borrowing or lending activity in terms of rate.
The formula below expresses $$\lambda$$ regarding bid/offer imposed on interest rate $$r$$, so that conversion in between the two is possible. Denote $$r_m$$ as the mid rate calculated from AMM
$$
e^{r_m}=\frac{\Delta y}{\lambda\Delta x}
$$
However, trader deposits $$\Delta x$$ rather than $$\lambda\Delta x$$. Therefore, the bid rate $$r_b$$ when purchasing ayToken satisfies
$$
e^{r_b}=\frac{\Delta y}{\Delta x}
$$
$$\Delta r_b=r_m-r_b$$ is then the fee charged to the purchaser in the yield space,
$$
e^{\Delta r_b}=\frac{1}{\lambda}
$$
Hence, $$\lambda$$ can be expressed as a function of $$\Delta r_b$$
$$
\lambda=e^{-\Delta r_b}
$$
Actual fee is $$1- \lambda=1-e^{-\Delta r_b} \approx \Delta r_b$$ using Taylor expansion to the first order. Thus $$\lambda \approx 1-\Delta r_b$$ .
It can be shown that the above equality also holds when redeeming ayToken for Token, except $$\Delta r_b$$ replaced by $$\Delta r_o=r_o-r_m$$, where $$e^{r_m}=\frac{\lambda\Delta y}{\Delta x}$$ and $$e^{r_o}=\frac{\Delta y}{\Delta x}$$. Here, $$r_o$$ is the offer rate when selling ayToken and $$\Delta r_o$$ is the corresponding fee charged to the seller in the yield space.
## Concentrated Liquidity
In the current setting, liquidity provider can make market on any rate between $$-\infty$$ to $$+\infty$$. However, market participants might wish to impose certain constraint, for example no negative interest rate. One solution is to set up bounds on $$\frac{y}{x}$$, which are related to the rate. In the case of positive rate, this means balance of ayToken always larger than Token. Although it solves the problem, the amount of ayToken lower than Token would be excluded from trading activities in any means. We are proposing an alternative approach by introducing virtual tokens.
Virtual tokens constitute part of the trading pool reserve that would never be touched hence underutilised. Liquidity providers should not be required to maintain this part of the pool and we are therefore set them as virtual. For example, when rate is floored at 0%, $$t$$= 0.5 and $$L$$= 20, liquidity providers will never face the situation of ayToken balance falling below 100, which can then be regarded as virtual to save the actual capital cost.
The idea is inspired by concentrated liquidity in _Uniswap v3_.
### Pool with interest rate floored at zero
This section only allows liquidity on non-negative interest rate. Concentrated liquidity is achieved by introducing virtual token reserves $$y_v$$, which satisfies
$$
x^{1-t}+(y+y_{v})^{1-t}=L
$$
Figure 1 illustrates the example above of $$t$$= 0.5 and $$L$$= 20 by displaying two sets of curves: Invariant Function Curve \(IFC"\) satisfying $$x^{1-t}+y^{1-t}=L$$ and Capital Efficiency Curve \(CEC"\) satisfying $$x^{1-t}+(y+y_v)^{1-t}=L$$. Intuitively CEC is attained by lowering IFC by $$y_v$$= 100.
![Figure 1](../.gitbook/assets/cecjing.png)
#### Initialisation
Instead of contributing equal amount of Token and ayToken to initialise the pool with interest rate 0%, liquidity provider only needs to contribute x amount of Token. This is because virtual token $$y_v=x=\left(\frac{1}{2}L\right)^{\frac{1}{1-t}}$$.
#### Trading
Balance of Token and ayToken, including both actual and virtual, still satisfy the invariant function. However, once the actual ayToken is depleted and only Token is left in the pool, trading would be ceased until more ayToken is deposited.
#### Minting and Burning
Before liquidity expansion or reduction by minting or burning coins, assume that the old pool has Token $$x$$ and ayToken $$y$$ satisfying $$x^{1-t}+y^{1-t}=L$$, where $$y=y_a+y_v$$ and $$y_a$$ and $$y_v$$ are balance of actual and virtual ayToken respectively.
Minting and burning should not affect price and interest rate. This means that newly added or withdrawn coins would be in proportion to x and y. Denote new amount of Token and ayToken as $$x'=kx$$ and $$y'=ky$$ respectively. $$y'=y'_a+y'_v$$ where $$y'_a$$ is actual whereas $$y'_v$$ virtual. They satisfy the following
$$
\begin{split}
&y'_a+y'_v=ky\\
&2y'^{1-t}_v=k^{1-t}L
\end{split}
$$
Solution to the above equations is
$$
\begin{split}
&y'_{a}=ky-y'_{v}\\y'_{v}
&=\left(\frac{1}{2}L\right)^{\frac{1}{1-t}}k
\end{split}
$$
This means $$y'_v=ky_v$$ and $$y'_a=ky_a$$.
#### Example
Assume $$t$$= 0.5. Rachel initialises a liquidity pool of 0% interest rate with 100 Token on CEC. Although there is no actual ayToken, 0% rate implies 100 virtual tokens and $$L$$= 20 on IFC.
Suppose Rachel then sells 50 ayToken to the pool on the same day. On IFC, this means ayToken amount of 150 \(50 actual and 100 virtual\) and the amount of 60.10 Token remaining on IFC.
Now suppose Billy wants to mint 10% of the liquidity pool. This means that Billy needs to deposit 6.01 \(10% of 60.10\) Token. Virtual balance is updated to $$\left(\frac{1}{2}\times20\right)^{\frac{1}{0.5}}\times1.1=110$$. Billy needs to deposit 5 ayToken \($$1.1\times150-110-50$$\), so that the summation of actual and virtual ayToken is 165. Interest rate remains the same before and after Billy's participation. Note that both actual and virtual ayToken balance increase by 10%, which is the same proportion as the growth of liquidity pool.
### Range-bound Pool
The above section can be extended to any constraint pool with upper interest rate $$r_{u}$$ and lower interest rate $$r_{l}$$. If interest rate falls out of \[$$r_{l} $$,$$r_{u}$$\], swapping would be suspended as one of the tokens would have been depleted.
Denote $$x_{a}$$, $$x_{v}$$, $$y_{a}$$ and $$y_{v}$$ balance of actual Token, virtual Token, actual ayToken and virtual ayToken respectively. They satisfy invariant function on IFC, i.e. $$(x{a}+x{v})^{1-t}+(y{a}+y{v})^{1-t}=L$$.
The amount of Token an ayToken can be expressed as a function of L and current interest rate $$r_{c}=\frac{y_{a}+y_{v}}{x_{a}+x_{v}}$$.
$$
\begin{split}
&x_{a}+x_{v}&=\left[\frac{L}{1+e^{(1-t)r_{c}}}\right]^{\frac{1}{1-t}}\\
&y_{a}+y_{v}&=\left[\frac{L}{1+e^{-(1-t)r_{c}}}\right]^{\frac{1}{1-t}}
\end{split}
$$
Intuitively, when $$r_{c}=r_{l}$$, ayToken is depleted; Similarly, when $$r_{c}=r_{u}$$, Token is used up. Therefore,
$$
\begin{split}
&x_{v}=\left[\frac{L}{1+e^{(1-t)r_{u}}}\right]^{\frac{1}{1-t}}\\
&y_{v}=\left[\frac{L}{1+e^{-(1-t)r_{l}}}\right]^{\frac{1}{1-t}}
\end{split}
$$
See [Appendix 3](automated-market-making-of-alex.md#appendix-3-derivation-of-actual-and-virtual-token-reserve) for a detailed derivation of virtual, as well as actual token reserve.
Similar to the case of 0% floor, minting or burning coins would result in invariant constant changing from $$L$$ to $$k^{1-t}L$$. Meanwhile, both actual and virtual Token and ayToken would grow proportionally by $$k$$, as they are linear function of $$L^{\frac{1}{1-t}}$$.
#### Example
We aim to show here how virtual token is able to assist liquidity providers to efficiently manage capital.
![Figure 2](../.gitbook/assets/cectable2.png)
In Figure 2, assume lower bound is 0%, whereas upper bound is 50%. We also set $$t$$= 0.5 and $$L$$= 20. If interest rate is 0%, $$L$$= 20 means holding equal amount of Token and ayToken of 100 each $$\left(100^{0.5}+100^{0.5}=20\right)$$. The figure compares actual holding of Token and ayToken with and without cap and floor.
According to the figure, when current implied interest rate is 10%, without capital efficiency, liquidity provider is required to deposit 95.06 Token and 105.06 ayToken. This is in comparison with 18.39 Token and 5.06 ayToken after imposing cap and floor. In this example, the capital saving is at least 77%.
## Appendix 1: Generalised Mean when d=2
ALEX's invariant function is $$f(x_{1},x_{2};p)=x{_1}^{p}+x_{2}^{p}=L.$$ It can be rearranged as $$x{2}=g(x_{1})=(L-x_{1}^{p})^{\frac{1}{p}}$$. $$x_{1}$$ and $$x_{2}$$ should both be positive meaning the liquidity pool contains both tokens.
#### Theorem
When $$0<p<1$$, $$g\left(x_{1}\right)$$ is monotonically decreasing and convex.
#### Proof
This is equivalent to prove $$\frac{dg(x_{1})}{dx_{1}}<0$$ and $$\frac{d^{2}g(x_{1})}{dx_{1}^{2}}\geq0$$.
$$
\begin{split}
&\frac{dg(x_{1})}{dx_{1}}=\frac{1}{p}(L-x_{1}^{p})^{\frac{1}{p}-1}\left(-px_{1}^{p-1}\right)=-\left(\frac{L-x_{1}^{p}}{x_{1}^{p}}\right)^{\frac{1-p}{p}}<0\\
&\frac{d^{2}g(x_{1})}{dx_{1}^{2}}=-\frac{1-p}{p}\left(\frac{L-x_{1}^{p}}{x_{1}^{p}}\right)^{\frac{1-2p}{p}}\left[\frac{-px_{1}^{p-1}x_{1}^{p}-(L-x_{1}^{p})px^{p-1}}{x_{1}^{2}p}\right]\\
&=L(1-p)\left(\frac{x_{2}}{x_{1}}\right)^{1-2p}x_{1}^{-p-1}\geq0
\end{split}
$$
The last inequality holds because each component is positive.
When $$p$$= 1, it is straightward to see that the invariant function is constant sum. To show that the invariant function converges to constant product when $$p$$= 0, we will show and prove an established result in a generalised $$d$$ dimensional setting.
#### Theorem
$$
\lim_{p\rightarrow0}\left(\frac{1}{d}\sum_{i=1}^{d}x_{i}^{p}\right)^{\frac{1}{p}}=({\prod_{i=1}^{d}x_{i}})^{\frac{1}{d}}
$$
#### Proof
$$\left(\frac{1}{d}\sum{i=1}^{d}x_{i}^{p}\right)^{\frac{1}{p}}=\text{exp}\left[\frac{\text{log}\left(\frac{1}{d}\sum{i=1}^{d}x_{i}^{p}\right)}{p}\right]$$. Applying _L'Hospital_ rule to the exponent,which is 0 in both denominator and nominator when $$p\rightarrow0$$, we have
$$
\lim_{p\rightarrow0}\frac{\text{log}\left(\frac{1}{d}\sum_{i=1}^{d}x_{i}^{p}\right)}{p}=\lim_{p\rightarrow0}\sum_{i=1}^{d}\frac{\text{log}(x_{i})}{\sum_{j=1}^{d}\left(\frac{x_{j}}{x_{i}}\right)^{p}}=\frac{\sum_{i=1}^{d}\text{log}(x_{i})}{d}
$$
Therefore
$$
\lim_{p\rightarrow0}\left(\frac{1}{d}\sum_{i=1}^{d}x_{i}^{p}\right)^{\frac{1}{p}}=\lim_{p\rightarrow0}\text{exp}\frac{\sum_{i=1}^{d}\text{log}(x_{i})}{d}=({\prod_{i=1}^{d}x_{i}})^{\frac{1}{d}}
$$
#### Corollary
When d = 2,
$$
x_{1}x_{2}=\lim_{p\rightarrow0}\left[\frac{1}{2}(x_{1}^{p}+x_{2}^{p})\right]^{\frac{2}{p}}
$$
Proof of the corollary is trivial, as it is a direct application of the theorem. It shows that generalised mean AMM implies constant product AMM when $$p\rightarrow0$$.
## Appendix 2: Liquidity Mapping to Uniswap v3
As Uniswap v3 is able to simulate liquidity curve of any AMM, we are interested in exploring the connection between ALEX's AMM and that of _Uniswap_'s. Interesting questions include: what is the shape of the liquidity distribution? Which point\(s\) has the highest liquidity? We acknowledge that the section is more of a theoretical study for now.
_Uniswap V3_ AMM can be expressed as a function of invariant constant $$L$$ with respect to price $$p$$, $$L_{\text{Uniswap}}=\frac{dy}{d\sqrt{p}}$$. In terms of ALEX, as price p=e^{rt}, where $$r$$ is the implied interest rate, we have
$$
L_{\text{Uniswap}}=\frac{dy}{d\sqrt{p}}=\frac{2}{t}e^{-\frac{1}{2}rt}\frac{dy}{dr}
$$
In the previous sections, we express $$y$$ as
$$
y=\left[\frac{L}{1+e^{-(1-t)r}}\right]^{\frac{1}{1-t}}
$$
Therefore
$$
\begin{split}
&\frac{dy}{dr}=L^{\frac{1}{1-t}}\frac{e^{-(1-t)r}}{(1+e^{-(1-t)r})^{\frac{2-t}{1-t}}}\\
&L_{\text{Uniswap}}=\frac{2}{t}L^{\frac{1}{1-t}}\left(e^{\frac{r(1-t)}{2}}+e^{\frac{-r(1-t)}{2}}\right)^{\frac{-2+t}{1-t}}\\
&=\frac{2}{t}L^{\frac{1}{1-t}}\big\{2\cosh\left[\frac{r(1-t)}{2}\right]\big\}^{\frac{-2+t}{1-t}}
\end{split}
$$
![Figure 3](../.gitbook/assets/liquidity%20%282%29%20%282%29%20%282%29%20%282%29%20%282%29%20%282%29%20%282%29%20%282%29.png)
Figure 3 plots $$L_{\text{Uniswap}}$$ against interest rate $$r$$ regarding various levels of $$t$$. When $$0<t<1$$, $$L_{\text{Uniswap}}$$ is symmetric around 0% at which the maximum reaches . This is because
1. $$\cosh\left[(\frac{r(1-t)}{2})\right]$$ is symmetric around $$r$$= 0% with minimum at 0% and the minimum value 1;
2. $$x^z$$ is a decreasing function of $$x$$ when $$x$$ is positive and power $$z$$ is negative. In our case, we have $$z=-2+t1-t<-1$$. Therefore, it is the maximum rather than minimum that $$L_{\text{Uniswap}}$$ achieves at 0.
Furthermore, the higher the $$t$$, the flatter the liquidity distribution is. When $$t$$ approaches 1, i.e. AMM converges to the constant product formula, the liquidity distribution is close to a flat line. When $$t$$ approaches 0, the distribution concentrates around 0%. This makes sense, as forward price starts to converge to spot price upon expiration.
## Appendix 3: Derivation of Actual and Virtual Token Reserve
On CEC, there are two boundary points \($$x_{b}$$,0\) and \(0,$$y_{b}$$\) corresponding to the lower and upper bound of interest rate $$r_{l}$$ and $$r_{u}$$ respectively. We assume $$L$$ is pre-determined, as liquidity provider knows the pool size. We aim to find $$x_{b}$$, $$y_{b}$$, $$x_{v}$$ and $$y_{v}$$ which satisfy the following equations
$$
\begin{split}
&(x_{b}+x_{v})^{1-t}+y_{v}^{1-t}=L\\
&x_{v}^{1-t}+(y_{b}+y_{v})^{1-t}=L\\
&\frac{y_{v}}{x_{b}+x_{v}}=e^{r_{l}}\\
&\frac{y_{b}+y_{v}}{x_{v}}=e^{r_{u}}
\end{split}
$$
As there are four unknown variables with four equations, solutions can be expressed as below
$$
\begin{split}
&x_{v}=\left[\frac{L}{1+e^{(1-t)r_{u}}}\right]^{\frac{1}{1-t}}\\
&y_{v}=\left[\frac{L}{1+e^{-(1-t)r_{l}}}\right]^{\frac{1}{1-t}}\\
&x_{b}=y_{v}e^{-r_{l}}-x_{v}=\left[\frac{L}{1+e^{r_{l}(1-t)}}\right]^{\frac{1}{1-t}}-\left[\frac{L}{1+e^{r_{u}(1-t)}}\right]^{\frac{1}{1-t}}\\
&y_{b}=x_{v}e^{r_{u}}-y_{v}=\left[\frac{L}{1+e^{-r_{u}(1-t)}}\right]^{\frac{1}{1-t}}-\left[\frac{L}{1+e^{-r_{l}(1-t)}}\right]^{\frac{1}{1-t}}
\end{split}
$$
When $$r_{l}=0$$, the pool is floored at 0%. This means that $$x_{v}=0$$, $$y_{v}=\left(\frac{1}{2}L\right)^{\frac{1}{1-t}}$$, $$x_{b}=y_{v}$$.
When the current interest rate $$r_{c}$$ is known and $$r_{c}\in[r_{l},r_{u}]$$, we can calculate $$x_{a}$$ and $$y_{a}$$ satisfying the following equations. When $$r_{c} \notin[r_{l},r_{u}]$$, only one token exists and swapping activities are suspended.
$$
\begin{split}
&(x_{v}+x_{a})^{1-t}+(y_{v}+y_{a})^{1-t}=L\\
&\frac{y_{v}+y_{a}}{x_{v}+x_{a}}=e^{r_{c}}
\end{split}
$$
Solution to above is
$$
\begin{split}
&x_{a}=\left[\frac{L}{1+e^{r_{c}(1-t)}}\right]^{\frac{1}{1-t}}-x_{v}=\left[\frac{L}{1+e^{r_{c}(1-t)}}\right]^{\frac{1}{1-t}}-\left[\frac{L}{1+e^{r_{u}(1-t)}}\right]^{\frac{1}{1-t}}\\
&y_{a}=\left[\frac{L}{1+e^{-r_{c}(1-t)}}\right]^{\frac{1}{1-t}}-y_{v}=\left[\frac{L}{1+e^{-r_{c}(1-t)}}\right]^{\frac{1}{1-t}}-\left[\frac{L}{1+e^{-r_{l}(1-t)}}\right]^{\frac{1}{1-t}}
\end{split}
$$
At the boundary points, when $$r_{c}=r_{l}$$, $$x_{a}=x_{b}$$ and $$y_{a}=0$$; when $$r_{c}=r_{u}$$, $$x_{a}=0$$ and $$y_{a}=y_{b}$$.