---
# System prepended metadata

title: Math/Mechanics of 'stable income' - (still highly TBD)

---

## Our product differentiator
### demand side
#### incentives
* **stable, reliable income for open-source developers**

* ability to earn governance tokens (aka extra income than was agreed to with investor) and participate in  protocol evolvution. _governance tokens always have monetary value, ability to influence has value regardless of what any docs say_
* additional incentives could come as a form of bonuses (see in the honey pot 
section below)
### supply side
incentives
* to invest in work they want/need to have done. but rather than having to invest a big $$ amount of.

* capital, they can invest capital which they will always keep and earn a share of the interest -- compounding interest

* ability to earn governance tokens (aka extra income than was agreed to with investor) and participate in  protocol evolvution.

* possible idea: a way to hold the the interest paid to the developer in escrow until it's verifiably complete…?

* bounties and other things bring developers into the system for a short time. stable income provides stable devs, that work on the system for longer periods of time with the upside of moe productivity. not having to learn a new system. IOW, this reduces developer churn/turnover.

## Who are our users?
### supply side
* are they whales?
* are they retail investors?
* a mix of both?
* companies and projects with reliance on OSS?

#### what is the ‘role’ of the supply side users? are they donors or investors?

#### who are the whales?
Good comment by Nich: they tend to be more project agnostic

Maybe they take a fund them all and see what hits, sort of like an angel investor…?

#### who are the retail investors?
my thoughts: they tend to be more opinionated and have specific needs on certain projects being developed

### demand side
* oss devs 
* want a predictable income each month of X $ dollars
they have bills: houses, cars, families — they need a stable monthly income that they can count on

* want to work on what they love more than maximize income: market make stack overflow like survey
* this is a ETHGlobal Developer Survey which describes who these OSS devs are. specifically blockchain and defi devs. it differentiates them well from 'normal' devs:

https://medium.com/ethglobal/ethglobal-developer-survey-report-2020-f7bf4f7cf821
     
# Math/Mechanics of 'stable income' - (still highly TBD)

## Spreadsheets and Math Modelling
* https://docs.google.com/spreadsheets/d/1d5aDik7M7YarfulYrlfY9rfQwDHt6SpIRPJZnMmVEAk/edit?usp=sharing


## Notes
* NB: we didn't discuss accountability. it's an important issue. perhaps in the realm of governance and hopefully can be delay until post-MVP.  using escrow as a mechanism of accountability might work. but who/what would the arbiter be?*

* For easy math, numbers easily divisible by 12 have been chosen.

* mathematically there are 2 levers/gears involved to achieve stable income
  1. the actually variable APR % given by Aave for lending (generally speaking we have no control over this -- although technically we have some limited control over interest rates).
  2. our dynamic % share split. we take the APR interest received by aave, then we take that interest and determine which % of the interest we will send where.
    * % of interest going to supply side (investor)
      - interest staying in the investor staying in the investors's AAVE vault. Eg: the investor invests DAI in AAVE to receive aDai which continues to earn compound interest)
    * % of interest going to demand side (developer)
      - this interest going directly to dev in the form of DAI as payment. it's their paycheck. they can decided how to invest it later and not need to pay gas cost to move from aDAI to DAI.
    * % of interest going to reserve fund
      - this interest would be locked in our contract in the form as aDAI, so the reserve fund continues to earn compound interest
    * % of interest going to the honey pot (possibly out of scope for hackathon, but a good idea to capture for future development)
      - this interest would be locked in our contract in the form as aDAI, so the honey pot fund continues to earn compound interest


## Easy stable case
* Assume a stable APY on Aave of 18%
* Assume a single developer who wants $1000 USD / month

What is the monthly interest rate?

* NB: not accounting for compound interest yet for simplicity, but compound interest is very important not to ignore later*.

>18% / 12 months = 1.5% per month

* Assume a single investor who deposits $100,000 of Dai into an Aave vault

The developer receives from interest:

> $100,000 * 1% = $1000 USD / month

The investor receives in interest:

> $100,000 * 0.5% = $5 USD / month

The investor's principal is untouched.
## Worst bear case month
* Assume a variable APY on Aave and during a bad month the APY is 0%
* Assume a single developer who wants $1000 USD / month

What is the monthly interest rate?

> 0% for worst bear month


The developer receives from interest:

> $100,000 * 0% = $0 USD / month

The investor receives in interest:

> $100,000 * 0% = $0 USD / month

The investor's principal is untouched. The developer goes homeless, and can't afford and leaves the project.
## Bear case month
Assume a variable APY on Aave and during a bad month the APY drops from its original 18% to 6%


Assume a single developer who wants $1000 USD / month

What is the monthly interest rate?
> 6% / 12 months = 0.5%


The developer receives from interest:

> $100,000 * 0.5% = $500 USD / month

The investor receives in interest:

> $100,000 * 0% = $0 USD / month

The investor's principal is untouched. The developer can pay rent, but goes hungry and decides to leave the project.
## Bull case month (no Rainy Day or Honey Pot Funds)
Assume a stable APY on Aave of 18% goes up to 36%


Assume a single developer who wants $1000 USD / month

What is the monthly interest rate?

> 36% / 12 months = 3% per month

Assume a single investor who deposits $100,000 of Dai into an Aave vault

The developer receives from interest:

> $100,000 * 1% = $1000 USD / month

The investor receives in interest:

> $100,000 * 2% = $2000 USD / month

The investor's principal is untouched

Everyone is happy, but the future has not be protected via reserve funds.

## Bull case month with Rainy Day both Honey Pot Funds
Assume a stable APY on Aave of 18% goes up to 35%


Assume a single developer who wants $1000 USD / month

What is the monthly interest rate?

> 36% / 12 months = 3% per month

Assume a single investor who deposits $100,000 of Dai into an Aave vault

The developer receives from interest:

> $100,000 * 1% = $1000 USD / month

The investor receives in interest:

> $100,000 * 1% = $1000 USD / month

The investor's principal is untouched

$500 USD goes into Reserve Fund for the bear months

$500 USD goes into Honey Pot Fund for rewards and bonuses to developers for out-performing to paid at the discretion of governance.
## Reserve Rainy Day Fund
Any month where there is 'surplus' interest, a proportion of the surplus will be paid into a locked reserve vault (earning compound interest on its own) for the bad months when developers can't be paid their expected monthly income. The reserve fund will pay out to help the developer meet their monthly income.
## Honey Pot Fund
Any month where there is extra big 'surplus' interest, a proportion of the surplus will be paid into a locked honey pot vault (earning compound interest on its own). The honey pot vault can be used at the discretion of the governance (TBD) to award and further incentivize developers, via bonuses, etc…

# Meeting Notes

## 13/1/2021 Meeting Notes

* Problem for the demand side: how to generate predictable income for open source developers
* Definition of the supply side: who are they and what problem they solve
Problem of curation, who to fund/donate? QF?
* Need to differentiate ourselves from Spendless and Gitcoin Grants
    Continuous funding
* We need to agree on the scope of the MVP
1. We will definitely go with AAVE for V1

2. Agreed on depositor will get their principle back
3. Somehow adapt to guarantee the minimal amount of stable funding goals required
4. The surplus of the recipient’s earning goals will get redirected <tbd>
### How do we deal with APY shifts and balance it so that the earnings for beneficiary is stable
Ie. interest rate goes to zero
If we already paying the bills to the developer, what if hold the pool and hold interest in escrow
Some sort of health check function to ensure the rainy day funds are locked in
A lot of the complexity can be driven off chain.. How do we make this as simple as possible

## 16/1/2021 Meet Notes

Agenda: 
* supply side: who are they, how do we bring them in
- grants model: altruistic like Gitcoin QF
- investments like Metacartel DAO
* figure curation, how do we get projects
* naming is hard

Grants (altruistic, MetaCartel/Moloch Grants) vs Investment (buy economic stake, VentureDAO, The LAO)
Supply side can get updates and some say in the direction of the protocol?
Also factor in social signaling.


### Action Items

Figure out what the supply side is
Figure out the rainy day funds portion of the product.. How do we do this and what the tradeoffs are
Try out hardhat/ alchemy
Next meeting Afternoon on the 16th

Traditional avenues to fund open-source
- Github Sponsors
- Patreon
- Buy me coffee plug-in
- Straight up donations (Paypal, Crypto)

The unique proposition with DeFi is that donors don't have to dip into their wallets to contribute. Can do it with interest. Also they are able to vote with their dollars to signal the public goods that are most valuable tho the ecosystem

excalibra illustration for drawing illustration

Will focus on the logic flow and the contract design, validate the most difficult assumption

How do we bootstrap the system?
How much is the first stable rate <- need to do the maths
Each come up with the design of the contract and see how it might work
Lets set up our own private channel on Discord and communicate there


## Supply Side

1. Grants-giving institutions and groups: ConsenSys Grants, Ethereum Foundation, Moloch DAO, MetaCartel DAO, DeFi projects.

2. Whales: high net-worth individuals who are well-known in the ecosystem, like Andre Cronje (yearn), Joe Lubin, Kain Warwick (Synthetix) etc. They are agnostic and would want to have a role in funding the ecosystem as a whole without the cognitive overhead of selecting specific projects. These individuals are "matchers" of Gitcoin Grants. They don't select the individual projects, but pool their money towards a matching pool that gets allocated through QF.

3. Long-tail of Ethereum users: pick individual projects they like, "vote" with their dollar and then signal this on social media.

## Product Validation

### Problem we are tackling:
OSS Developers: Lack of value capture from their contribution to a public good, accessing global capital
Donors/Investor: Reducing friction of donors see in putting money into OSS projects that they rely on. Continuous, passive contributions from interest on their savings.

### Possible Approaches

- Work backwards from defined salary (stable? variable?)
    - How do we define a salary?
     - A salary is an instance of our 'salary' contract deployed via our 'salary contract factory'. Each deployed instance of a 'salary contract' contains:
       1. The 'salary contract' initiator signature (could be proposed by either the developer or investor)
       3. The frequency of payment for this given salary contract payment (weekly, monthly, etc)
       4. The amount of money the developer will receive with each payment
       5. An expiration date of the agreed to 'salary contract'. Aka the day in which the investor can remove their principal.
       6. A 'salary contract' acceptor signature, completing the mutlisig, completing the circle of the agreement.

     - An investor or developer 'salary contract' proposal and acceptance are pretty much identical, only in the funds flow in reverse. Example:

       Hi, I'm Jacob (dev's signature), and I propose to work on repo X. I will agree to work on it for 200 Dai paid to me 1 time every week. I agree to this work for 6 months.

       Howdy, my name is Investor Bester and I agree to your terms (investor's signature).
       
     - Since each proposal requires a contract deployment which costs gas, this helps ensure good actors. Spamming the bazaar with half-hearted proposals just wastes money.

     - This idea/workflow needs validation. Is it realistic to think the such a marketplace/bazaar would appear and is this a realistic form the 'bids and asks' in the marketplace?
       - Major over-simplification here for now. There will likely be more than 1 investor in some if not most of the 'salary contracts'. In theory I don't think it makes a big difference at the 'salary contract' level. The only difference would be we would need to store a map of all investors signatures as a key that maps to the value they invested.
         - The UI/UX get more complex. 

- Emergency funds (is guaranteed minimum income viable?)
- Multisig per deployed contract
    - Added complexity with governance concerns but could implement some MVP version if we have time
- One deployed contract per recipient
    - Parameters for interest rate split
    - Expiration dates: how does it affect the unit economics
- Tokens?
    - Token lockups, expiration date, yield farm $BREW governance tokens
    - Signaling on GitHub issues
    - Governance token can be used to vote on more projects, added features
      - super cool!  tokens also allow devs extra income by earning gov tokens and 
        and they also get a seat at the goverance table.
      - investors also get more yield than just interest and can also vote on their side of the table.
    - issuance increase in the beginning, goes down after surplus interest rates kick in

### Dependencies
- Variable APY of lending protocols
- can we find a fixed interest rate?

### Startup CTO's feedback 

puts in $500 every month to fund downstream open source project via GitHub Sponsors.
expect ROI:

1. ability to communicate with Maintainer and get respond
2. informally convey priority and accountability of said project
3. find that currently the funding amount is a sunk cost
4. suggest we look at VC and funds like YCombinator, as the treasuries are currently idle asset
5. find that the product idea reduce significant friction for funders
6. finds the additional yield earned to the depositor to be a big plus
7. suggests using Github Badge on the project readme to show funding goals


### Smart Contract Pseudo Code

constructor(address recipient, address token, address pool, uint salary, address bToken)
    // initialise a recipient variable
    // initialise a ERC-20 token variable 
    // initialise address pool
    // initalise uint salary
    // initialise address bToken (assumed already deployed separately)
    // initialise uint256 

    
    
// deposit(uint256 amount):
    // assume that this contract is approved in the ERC-20 contract to spend caller tokens 
    // transferFrom(address(this), amount) <- send ERC20 to this contract
    // approve(address(pool), amount) <- approve the pool to spend
    // pool.deposit() <- deposit ERC20 token into Aave pool and get aTokens
    // updateExchangeRate()
    // bToken.mint(msg.sender, amount * exchangeRate)
    

// updateExchangeRate(){
    interestEarned = ... a.tokenBalanceOf(address(this)) - principal; 
    exchangeRate = aToken.balanceOf(address(this)) / bToken.totalSupply()
    }
    

// withdraw(amount)
    // updateExchangeRate()
    // uint bTokenAmount = amount / exchangeRate; 
    // bToken.approve(address(this), bTokenAmount);
    // bToken.transferFrom(msg.sender, address(0x), amount)
    // aToken.approve(address(pool), amount)
 
 
 

exchangeRateUpdate()
    
    
Questions: 

1. At any point in time, how do we calculate how much recipient can withdraw? 
    Constraints: 
    - Cannot be greater than the defined target ie. $1000 a month. 
    - Should accrue in real-time and be withdrawable at any time. 
        
2. At any point in time, how do we calculate a total (principal and interest) that a depositor/funder can withdraw? 
    Constraints: 
    - Earned interest in percentage terms on a deposit should be proportional to time.
    - Should accrue in real-time and be withdrawable at anytime.
    
The problem of dynamic accruing interests seemed to be solved on Aave, wrt. how they calculate real time interests earned by users with respect of time [via liquidity index && scaled balance][https://docs.aave.com/developers/the-core-protocol/atokens#scaledbalanceof]




### Interests Accrual

because of AAVE's variable interest rates potentially changing on every eth block (10-15 seconds), each time a new block is published, do an accounting calculations of who owns which interest between investors and developer aave's code might be useful for the math discussion. they calculate interest rates based on how much of a given currency is in their reserve.

https://github.com/aave/protocol-v2/blob/master/contracts/protocol/lendingpool/DefaultReserveInterestRateStrategy.sol#L107-L184a

with our reserve fund, one approach would be to do something similar where we we may want to make similar/parallel calculations each block on how earned interest is divvied up. OTOH, making guaranteed/predictable 'salary', then another strategy would be to collect/pay 100% of the interest 
earned for the developer 1st and once their monthly payment/salary has been met, we can begin to share the interest between both the investor and developer.

quick brainstormy algorithm
_assumption for MVP: is that we'll make the numbers work. IOW: either the investors will put in enough money to make it an almost mathematical certainty the dev gets paid what they want or the dev will lower his asking price._ :wink:
_assumption for MVP: below several 'governance' decisions are being proposed, but later can be voted on_

1. until the dev is paid in full, 100% of accrued interest goes to dev.
2. once dev is paid in full, the remaining interest accrued will be divied up between investor the 
   and the reserve fund.
    a. the lower the reserve fund is in proportion to the total amount that will be paid out to the dev(s)
       then a higher % of interest will go into the reserve fund. we can likely use something similar to a collateralization ratio to always ensure the fund is a safe % of the total amount needed to be paid.
    b. simplest math case: set reserve fund to some amount >= 100% of what will need to be paid at the end of the month. if apy is 0% for the month the dev gets paid. still risky though...perhaps set reserve fund to 200 - 300% of total amount to be paid
    c. interest would flow like this. 100% -> dev until dev is paid in full, then 100% of interest is redirected to reserve fund for as long as it is under our pre-decided reserve ratio. after ratio is fulfilled, then 100% of interest goes to investor.
    
### Approach to Interest Redirection

https://miro.com/welcomeonboard/I5EYh4eb3HOdSvAst8Bfcq8x9AkJZeckyXDSVosd8q0SdyvXlNlv7rBucIinOb57
    
### Approach to Dynamic Interest Surplus Formula for Depositor


One possible way to do a dynamic interest & principal pool is similar to the ratio that Compound uses to calculate exchange rate of cToken -> Token. The exchange rate should be updated for every single interaction done on the contract:

_Do you mean to say interest rate here? Although we'll definitely need to now the Dai to aDai exchange rate too._

This may be a blockchain cost naive way to do things (too much in gas costs?), but Aave's interest rates can change every block (10-15 seconds). So we'll have to update the interest rates once per block. Does that make sense? I think it should be a cheap operation, correct?

> exchangeRate = principal  + surplusInterest / bTokenTotalSupply

For example, starting off with a fresh pool: at Time T1

***T1: Alice deposit 1000 Token, receives1000 bToken back***

> Exchange rate = 1000 + 0 / 1000 = 1

***T2: Interest surplus accrued by 100***

> Exchange rate = 1000 + 100 / 1000 = 1.1

Alice can redeem 1000 btoken for 1100 aToken

***T3 Bob deposits 1000, supply increases by 1000***
Bob receives 1000/1.1 = 909.0909090909 bToken

> Exchange rate = 2000 + 100 / 1,909.0909090909 = 1.1000005238

Bob can redeem 909.09 for 909.09 * 1.1000005238 = 1000
Alice can redeem 1000 btoken for 1000 * 1.1000005238 =  1100.0005238

***T4 Interests surplus accrued by 200***

> Exchange rate = 2000 + 300 / 1,909.0909090909 = 1.2047619048

Bob can redeem 909.09 for 909.09 * 1.2047619048 = 1095.237000035
Alice can redeem 1000 btoken for 1000 * 1.2047619048 =  1204.7619048

***T5 Alice cash out her entire balance***
Alice redeems 1000 btoken for 1000 * 1.2047619048 =  1204.7619048

> Exchange rate = 795.2380952 + 300 / 909.0909090909 = 1.2047619047

Alice has 0 balance
Bob can redeem 909.09 for 909.09 * 1.2047619047 = 1204.7619048

# Product Specs

## Glossary

**Recipient**: the beneficiary wallet address that has the priority to the portion of the interest earned

**Depositor**: the wallet address(s) make a deposit of tokens

**Goal**: the target amount which the recipient would like to make per interval

**Interval**: time period in which the goal is supposed to be met before phase 2 is reached

**Epoch**: the Ethereum Block that marks the end of the current interval. Each Epoch should increase by an interval.

**Interest**: the amount in aTokens earned from Aave, calculated by the formula aTokenBalance - TotalDepositSupply

**Exchange rate**: exchangeRate = principal + surplusInterest / bTokenTotalSupply

**TotalDepositSupply**: amount of tokens deposited into the contract via `deposit()` function

**Tokens**: representation of tokens in it's native ERC20 form

**aTokens**: Aave representation of native tokens + interest earned

**bTokens**: our representation of tokens, redeemable for original principal amount + any interests earned

**Maturity**: the point where the interests earned during the interval is > the goal, and the vault goes from phase 1 to phase 2.

**Phase 1**: the contract generates interest for the recipient, interests generated in this duration < the goal

**Phase 2**: the contract generates interest into the surplus bucket, where the depositor can withdraw

**surplus bucket**: bucket of interests allocated to depositors, withdrawable by bTokens

**recipient bucket**: bucket of interests allocated to recipient, withdrawable anytime.

## User Stories

As a recipient, I can take out at most Y amount of tokens on every given interval.

As a depositor, I can deposit funds and be expected to withdraw my principal out at any time.

As a depositor, I can expect to earn additional interest if the needs for the recipient have already been covered.

As a depositor, I expect that the amount I deposit will earn interests for the recipient first.

## Specs

### Feature: Recipient can withdraw at most X interests in Y tokens, every Z intervals

Given that the recipient has waited out the correct amount of time since last interval.
When the recipient calls recipientWithdraw() on the contract with an amount as argument
And the amount is smaller than his goal
And the amount is smaller than the total amount raised from interest
Then recipient should receive the amount in that underlying tokens.

**TODO**: think about rollover(s)

### Feature: Depositor's interest is channeled towards Recipient's bucket.

Given that the depositor(s) have deposited X amount of tokens into the contract
And the amount deposited has earned interest
When the amount of interest earned is less than the target goal
Then the interest is only channeled to recipient's bucket

### Feature: Depositor's interest is channeled towards surplus bucket.

Given that the depositor(s) have deposited X amount of tokens into the contract
And the amount deposited has earned interest
When the amount of interest earned is larger than the target goal
Then the differences of the total interest earned and goal amount is channeled to the surplus bucket.

### Feature: Interest and Principal can be withdrawn at any point in time.

Given that a depositor deposit X amount of tokens into the pool.
And receive back Y amount of bTokens.
And some time has passed
Then the depositor call redeem with bTokens
Then the depositor should receive back his/her principal amount of tokens with the corresponding bTokens, with the interest that maybe earned during the period


### Feature: Interest surplus bucket allocation is distributed to the depositors equally.

Given that there are more than one depositors.
When the interest earned is channeled to the surplus pool.
And an older depositor call withdraw with bTokens
Then the older depositor will receive back the principle
And the amount of interest proportion to the amount and age of his deposit
 

# Bucket List (post MVP for fun, let your imagination run wild!)
- Assuming the stable salary route, we can kind of think of our project as a bit like getting into the payroll business. If enough developers are getting paid in our ecosystem and enough investors are supporting projects, then we can think about lots of neat stuff. 
  - __Savings account for developer__. We could have a variant of the withdrawal method, where the developer can withdrawal a certain percent to their wallet and specify another % to be sent to one of our own savings vaults (similar to yearn).
    - In the future, our vaults could possibly get __tax-deferred status__ and people could lock their retirement money similar to an IRA (Individual Retirement Account in the US).
    - Owners of IRAs often choose mutual funds that have a target retirement year (mine is 2035). As retirement date gets closer and closer the retirement accounts shift from more risky, but high yield positions to lower risk lower yield positions. have target retirement years (mine is 2035). You cannot withdrawal before your government's designated retirement age without getting hit with a penalty (in the US it's 20%).
      - What would this mean for us? Lots and __lots of potential $$ increasing our retirement vaults' TVLs__. The TVLs on these types of vaults would usually span long ranges of time.
      - Has anyone seen any kind of vault strategies that __optimize risk/return of the vaults' assets based on how long the money is expected to be invested__ in the DeFI jungle yet? Yearn, Farm, they're great, but I haven't seen any strategies yet that optimize holder's profit based on how long the investor signals they're intending to hold money in the vault.
  - __Life Insurance, Health Insurance Vaults__
