Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Drip the yield within WOETH #2420

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
142 changes: 76 additions & 66 deletions contracts/contracts/token/WOETH.sol
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";

import { StableMath } from "../utils/StableMath.sol";
import { Governable } from "../governance/Governable.sol";
Expand All @@ -28,16 +30,21 @@ import { OETH } from "./OETH.sol";
contract WOETH is ERC4626, Governable, Initializable {
using SafeERC20 for IERC20;
using StableMath for uint256;
uint256 public oethCreditsHighres;
using SafeCast for uint256;
uint128 public yieldRate;
uint128 public yieldEnd;
uint256 public hardAssets;
uint256 public yieldAssets;
bool private _oethCreditsInitialized;
uint256[48] private __gap;

uint256 constant YIELD_TIME = 1 days;
uint256 constant MAX_DAILY_DRIP_RATE_PCT = 3;

// no need to set ERC20 name and symbol since they are overridden in WOETH & WOETHBase
constructor(ERC20 underlying_)
ERC20("", "")
ERC4626(underlying_)
Governable()
{}
constructor(
ERC20 underlying_
) ERC20("", "") ERC4626(underlying_) Governable() {}

/**
* @notice Enable OETH rebasing for this contract
Expand All @@ -57,22 +64,15 @@ contract WOETH is ERC4626, Governable, Initializable {
require(!_oethCreditsInitialized, "Initialize2 already called");

_oethCreditsInitialized = true;
/*
* This contract is using creditsBalanceOfHighres rather than creditsBalanceOf since this
* ensures better accuracy when rounding. Also creditsBalanceOf can be a little
* finicky since it reports Highres version of credits and creditsPerToken
* when the account is a fresh one. That doesn't have an effect on mainnet since
* WOETH has already seen transactions. But it is rather annoying in unit test
* environment.
*/
oethCreditsHighres = _getOETHCredits();
hardAssets = OETH(asset()).balanceOf(address(this));
}


function name()
public
view
virtual
override(ERC20, IERC20Metadata)
override(ERC20,IERC20Metadata)
returns (string memory)
{
return "Wrapped OETH";
Expand All @@ -82,7 +82,7 @@ contract WOETH is ERC4626, Governable, Initializable {
public
view
virtual
override(ERC20, IERC20Metadata)
override(ERC20,IERC20Metadata)
returns (string memory)
{
return "wOETH";
Expand All @@ -104,64 +104,78 @@ contract WOETH is ERC4626, Governable, Initializable {
IERC20(asset_).safeTransfer(governor(), amount_);
}

/** @dev See {IERC4262-totalAssets} */
function totalAssets() public view override returns (uint256) {
uint256 creditsPerTokenHighres = OETH(asset())
.rebasingCreditsPerTokenHighres();

return (oethCreditsHighres).divPrecisely(creditsPerTokenHighres);
function yieldDripRate() public {
// no need to update the yield drip rate twice in the same block
if(yieldEnd >= block.timestamp){
return;
}

uint256 _computedAssets = totalAssets();
uint256 _actualAssets = OETH(asset()).balanceOf(address(this));

// all yield has dripped or WOETH has less assets than shown in the accounting
// the later should never happen as we don't do negative rebases on OToken (OETH)
if(_actualAssets <= _computedAssets){
yieldAssets = 0;
yieldRate = 0;
hardAssets = _computedAssets;
yieldEnd = uint128(block.timestamp);
} else if (_actualAssets > _computedAssets ){
// Maximum of 3% increase in assets per day
uint256 _maxYield = _actualAssets * MAX_DAILY_DRIP_RATE_PCT / 100;
uint256 _newYield = _actualAssets - _computedAssets;
_newYield = Math.min(_newYield, _maxYield);
_newYield = Math.min(_newYield, type(uint128).max);

uint128 _newYieldRate = (_newYield / YIELD_TIME).toUint128();
/**
* Don't allow for negative changes in the yield rate if that yield drip is still
* active. If allowed continuous calls to
* deposit/mint/withdraw/redeem could delay or minimize the yield drip.
*
*
* TODO: add a test for this
*/
if (_newYieldRate > yieldRate || yieldEnd + YIELD_TIME < block.timestamp) {
yieldRate = _newYieldRate;
yieldAssets = _newYield;
hardAssets = _computedAssets;
yieldEnd = uint128(block.timestamp);
}
}
}

function _getOETHCredits()
internal
view
returns (uint256 oethCreditsHighres)
{
(oethCreditsHighres, , ) = OETH(asset()).creditsBalanceOfHighres(
address(this)
);
/** @dev See {IERC4262-totalAssets} */
function totalAssets() public view override returns (uint256) {
uint256 _end = yieldEnd;
if(block.timestamp >= _end){
return hardAssets + yieldAssets;
} else if(block.timestamp < _end - YIELD_TIME){
return hardAssets;
}
return hardAssets + yieldAssets * (YIELD_TIME - (_end - block.timestamp)) / (YIELD_TIME + 1);
}

/** @dev See {IERC4262-deposit} */
function deposit(uint256 oethAmount, address receiver)
public
override
returns (uint256 woethAmount)
{
if (oethAmount == 0) return 0;

/**
* Initially we attempted to do the credits calculation within this contract and try
* to mimic OUSD's implementation. This way 1 external call less would be required. Due
* to a different way OUSD is calculating credits:
* - always rounds credits up
* - operates on final user balances before converting to credits
* - doesn't perform additive / subtractive calculation with credits once they are converted
* from balances
*
* We've decided that it is safer to read the credits diff directly from the OUSD contract
* and not face the risk of a compounding error in oethCreditsHighres that could result in
* inaccurate `convertToShares` & `convertToAssets` which consequently would result in faulty
* `previewMint` & `previewRedeem`. High enough error can result in different conversion rates
* which a flash loan entering via `deposit` and exiting via `redeem` (or entering via `mint`
* and exiting via `withdraw`) could take advantage of.
*/
uint256 creditsBefore = _getOETHCredits();
{
woethAmount = super.deposit(oethAmount, receiver);
oethCreditsHighres += _getOETHCredits() - creditsBefore;
hardAssets += oethAmount;
yieldDripRate();
}

/** @dev See {IERC4262-mint} */
function mint(uint256 woethAmount, address receiver)
public
override
returns (uint256 oethAmount)
{
if (woethAmount == 0) return 0;

uint256 creditsBefore = _getOETHCredits();
{
oethAmount = super.mint(woethAmount, receiver);
oethCreditsHighres += _getOETHCredits() - creditsBefore;
hardAssets += oethAmount;
yieldDripRate();
}

/** @dev See {IERC4262-withdraw} */
Expand All @@ -170,11 +184,9 @@ contract WOETH is ERC4626, Governable, Initializable {
address receiver,
address owner
) public override returns (uint256 woethAmount) {
if (oethAmount == 0) return 0;

uint256 creditsBefore = _getOETHCredits();
woethAmount = super.withdraw(oethAmount, receiver, owner);
oethCreditsHighres -= creditsBefore - _getOETHCredits();
hardAssets -= oethAmount;
yieldDripRate();
}

/** @dev See {IERC4262-redeem} */
Expand All @@ -183,10 +195,8 @@ contract WOETH is ERC4626, Governable, Initializable {
address receiver,
address owner
) public override returns (uint256 oethAmount) {
if (woethAmount == 0) return 0;

uint256 creditsBefore = _getOETHCredits();
oethAmount = super.redeem(woethAmount, receiver, owner);
oethCreditsHighres -= creditsBefore - _getOETHCredits();
hardAssets -= oethAmount;
yieldDripRate();
}
}
}
18 changes: 15 additions & 3 deletions contracts/test/token/woeth.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const { expect } = require("chai");

const { loadDefaultFixture } = require("../_fixture");
const { oethUnits, daiUnits, isFork } = require("../helpers");
const { oethUnits, daiUnits, isFork, advanceTime } = require("../helpers");
const { hardhatSetBalance } = require("../_fund");

describe("WOETH", function () {
Expand Down Expand Up @@ -33,8 +33,14 @@ describe("WOETH", function () {

// rebase OETH balances in wallets by 2x
await increaseOETHSupplyAndRebase(await oeth.totalSupply());

// josh account starts each test with 100 OETH

// 3% max drip rate within WOETH means 34 days for the doubling of WOETH
// value to drip
for (let i = 0; i < 34; i++) {
await woeth.connect(josh).deposit(oethUnits("0"), josh.address);
await advanceTime(86400);
}
});

const increaseOETHSupplyAndRebase = async (wethAmount) => {
Expand Down Expand Up @@ -62,6 +68,8 @@ describe("WOETH", function () {
it("should deposit at the correct ratio", async () => {
await expect(woeth).to.have.a.totalSupply("50");
await woeth.connect(josh).deposit(oethUnits("50"), josh.address);


await expect(josh).to.have.a.balanceOf("75", woeth);
await expect(josh).to.have.a.balanceOf("50", oeth);
await expect(woeth).to.have.a.totalSupply("75");
Expand Down Expand Up @@ -159,6 +167,7 @@ describe("WOETH", function () {
await expect(woeth).to.have.a.totalSupply("50");
await expect(woeth).to.have.approxBalanceOf("100", oeth);
await expect(josh).to.have.a.balanceOf("50", woeth);
await expect(josh).to.have.a.balanceOf("100", oeth);

// attempt to "attack" the contract to inflate the WOETH balance
await oeth.connect(josh).transfer(woeth.address, oethUnits("50"));
Expand All @@ -170,7 +179,10 @@ describe("WOETH", function () {
.redeem(oethUnits("50"), josh.address, josh.address);

await expect(josh).to.have.a.balanceOf("0", woeth);
await expect(woeth).to.have.approxBalanceOf("50", oeth);
await expect(josh).to.have.a.balanceOf("150", oeth);
await expect(woeth).to.have.a.balanceOf("50", oeth);

//await expect(woeth).to.have.approxBalanceOf("50", oeth);
await expect(await woeth.totalAssets()).to.equal("0");
await expect(woeth).to.have.a.totalSupply("0");
});
Expand Down
Loading