Skip to content

Add yearn vault wrapper module and oracle #61

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

Merged
merged 21 commits into from
Apr 13, 2021
Merged
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
24 changes: 24 additions & 0 deletions contracts/interfaces/external/IYearnVault.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
Copyright 2021 Set Labs Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

SPDX-License-Identifier: Apache License, Version 2.0
*/

pragma solidity 0.6.10;

interface IYearnVault {
function token() external view returns(address);
function pricePerShare() external view returns(uint256);
}
124 changes: 124 additions & 0 deletions contracts/mocks/external/YearnStrategyMock.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {BaseStrategyInitializable, StrategyParams, VaultAPI} from "../../../external/contracts/yearn/BaseStrategy.sol";

/*
* This Strategy serves as both a mock Strategy for testing, and an example
* for integrators on how to use BaseStrategy
*/

contract YearnStrategyMock is BaseStrategyInitializable {
bool public doReentrancy;
bool public delegateEverything;

// Some token that needs to be protected for some reason
// Initialize this to some fake address, because we're just using it
// to test `BaseStrategy.protectedTokens()`
address public constant protectedToken = address(0xbad);

constructor(address _vault) public BaseStrategyInitializable(_vault) {}

function name() external override view returns (string memory) {
return string(abi.encodePacked("YearnStrategyMock ", apiVersion()));
}

// NOTE: This is a test-only function to simulate delegation
function _toggleDelegation() public {
delegateEverything = !delegateEverything;
}

function delegatedAssets() external override view returns (uint256) {
if (delegateEverything) {
return vault.strategies(address(this)).totalDebt;
} else {
return 0;
}
}

// NOTE: This is a test-only function to simulate losses
function _takeFunds(uint256 amount) public {
want.safeTransfer(msg.sender, amount);
}

// NOTE: This is a test-only function to enable reentrancy on withdraw
function _toggleReentrancyExploit() public {
doReentrancy = !doReentrancy;
}

// NOTE: This is a test-only function to simulate a wrong want token
function _setWant(IERC20 _want) public {
want = _want;
}

function estimatedTotalAssets() public override view returns (uint256) {
// For mock, this is just everything we have
return want.balanceOf(address(this));
}

function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
// During testing, send this contract some tokens to simulate "Rewards"
uint256 totalAssets = want.balanceOf(address(this));
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
if (totalAssets > _debtOutstanding) {
_debtPayment = _debtOutstanding;
totalAssets = totalAssets.sub(_debtOutstanding);
} else {
_debtPayment = totalAssets;
totalAssets = 0;
}
totalDebt = totalDebt.sub(_debtPayment);

if (totalAssets > totalDebt) {
_profit = totalAssets.sub(totalDebt);
} else {
_loss = totalDebt.sub(totalAssets);
}
}

function adjustPosition(uint256 _debtOutstanding) internal override {
// Whatever we have "free", consider it "invested" now
}

function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) {
if (doReentrancy) {
// simulate a malicious protocol or reentrancy situation triggered by strategy withdraw interactions
uint256 stratBalance = VaultAPI(address(vault)).balanceOf(address(this));
VaultAPI(address(vault)).withdraw(stratBalance, address(this));
}

uint256 totalDebt = vault.strategies(address(this)).totalDebt;
uint256 totalAssets = want.balanceOf(address(this));
if (_amountNeeded > totalAssets) {
_liquidatedAmount = totalAssets;
_loss = _amountNeeded.sub(totalAssets);
} else {
// NOTE: Just in case something was stolen from this contract
if (totalDebt > totalAssets) {
_loss = totalDebt.sub(totalAssets);
if (_loss > _amountNeeded) _loss = _amountNeeded;
}
_liquidatedAmount = _amountNeeded;
}
}

function prepareMigration(address _newStrategy) internal override {
// Nothing needed here because no additional tokens/tokenized positions for mock
}

function protectedTokens() internal override view returns (address[] memory) {
address[] memory protected = new address[](1);
protected[0] = protectedToken;
return protected;
}
}
28 changes: 28 additions & 0 deletions contracts/mocks/external/YearnVaultMock.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
Copyright 2020 Set Labs Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

SPDX-License-Identifier: Apache License, Version 2.0
*/

pragma solidity 0.6.10;

contract YearnVaultMock {
uint256 public pricePerShare;

constructor(uint256 _pricePerShare) public {
pricePerShare = _pricePerShare;
}

}
121 changes: 121 additions & 0 deletions contracts/protocol/integration/YearnWrapAdapter.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
/*
Copyright 2020 Set Labs Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

SPDX-License-Identifier: Apache License, Version 2.0
*/

pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";

import { IYearnVault } from "../../interfaces/external/IYearnVault.sol";

/**
* @title YearnWrapAdapter
* @author Set Protocol, Ember Fund
*
* Wrap adapter for Yearn that returns data for wraps/unwraps of tokens
*/
contract YearnWrapAdapter {

/* ============ Modifiers ============ */

/**
* Throws if the underlying/wrapped token pair is not valid
*/
modifier _onlyValidTokenPair(address _underlyingToken, address _wrappedToken) {
require(validTokenPair(_underlyingToken, _wrappedToken), "Must be a valid token pair");
_;
}

/* ============ Constructor ============ */

constructor() public { }

/* ============ External Getter Functions ============ */

/**
* Generates the calldata to wrap an underlying asset into a wrappedToken.
*
* @param _underlyingToken Address of the component to be wrapped
* @param _wrappedToken Address of the desired wrapped token
* @param _underlyingUnits Total quantity of underlying units to wrap
*
* @return address Target contract address
* @return uint256 Total quantity of underlying units (if underlying is ETH)
* @return bytes Wrap calldata
*/
function getWrapCallData(
address _underlyingToken,
address _wrappedToken,
uint256 _underlyingUnits
)
external
view
_onlyValidTokenPair(_underlyingToken, _wrappedToken)
returns (address, uint256, bytes memory)
{
bytes memory callData = abi.encodeWithSignature("deposit(uint256)", _underlyingUnits);
return (address(_wrappedToken), 0, callData);
}

/**
* Generates the calldata to unwrap a wrapped asset into its underlying.
*
* @param _underlyingToken Address of the underlying asset
* @param _wrappedToken Address of the component to be unwrapped
* @param _wrappedTokenUnits Total quantity of wrapped token units to unwrap
*
* @return address Target contract address
* @return uint256 Total quantity of wrapped token units to unwrap. This will always be 0 for unwrapping
* @return bytes Unwrap calldata
*/
function getUnwrapCallData(
address _underlyingToken,
address _wrappedToken,
uint256 _wrappedTokenUnits
)
external
view
_onlyValidTokenPair(_underlyingToken, _wrappedToken)
returns (address, uint256, bytes memory)
{
bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _wrappedTokenUnits);
return (address(_wrappedToken), 0, callData);
}

/**
* Returns the address to approve source tokens for wrapping.
*
* @return address Address of the contract to approve tokens to
*/
function getSpenderAddress(address /* _underlyingToken */, address _wrappedToken) external view returns(address) {
return address(_wrappedToken);
}

/* ============ Internal Functions ============ */

/**
* Validates the underlying and wrapped token pair
*
* @param _underlyingToken Address of the underlying asset
* @param _wrappedToken Address of the wrapped asset
*
* @return bool Whether or not the wrapped token accepts the underlying token as collateral
*/
function validTokenPair(address _underlyingToken, address _wrappedToken) internal view returns(bool) {
address unwrappedToken = IYearnVault(_wrappedToken).token();
return unwrappedToken == _underlyingToken;
}
}
84 changes: 84 additions & 0 deletions contracts/protocol/integration/oracles/YearnVaultOracle.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
Copyright 2021 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

pragma solidity 0.6.10;

import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";

import { PreciseUnitMath } from "../../../lib/PreciseUnitMath.sol";
import { IYearnVault } from "../../../interfaces/external/IYearnVault.sol";
import { IOracle } from "../../../interfaces/IOracle.sol";


/**
* @title YearnVaultOracle
* @author Set Protocol, Ember Fund
*
* Oracle built to retrieve the Yearn vault price
*/
contract YearnVaultOracle is IOracle
{
using SafeMath for uint256;
using PreciseUnitMath for uint256;


/* ============ State Variables ============ */
IYearnVault public immutable vault;
IOracle public immutable underlyingOracle; // Underlying token oracle
string public dataDescription;

// Underlying Asset Full Unit
uint256 public immutable underlyingFullUnit;

/* ============ Constructor ============ */

/*
* @param _vault The address of Yearn Vault Token
* @param _underlyingOracle The address of the underlying oracle
* @param _underlyingFullUnit The full unit of the underlying asset
* @param _dataDescription Human readable description of oracle
*/
constructor(
IYearnVault _vault,
IOracle _underlyingOracle,
uint256 _underlyingFullUnit,
string memory _dataDescription
)
public
{
vault = _vault;
underlyingFullUnit = _underlyingFullUnit;
underlyingOracle = _underlyingOracle;
dataDescription = _dataDescription;
}

/**
* Returns the price value of a full vault token denominated in underlyingOracle value.
* The derived price of the vault token is the price of a share multiplied divided by
* underlying full unit and multiplied by the underlying price.
*/
function read()
external
override
view
returns (uint256)
{
// Retrieve the price of the underlying
uint256 underlyingPrice = underlyingOracle.read();

// Price per share is the amount of the underlying asset per 1 full vaultToken
uint256 pricePerShare = vault.pricePerShare();

return pricePerShare.mul(underlyingPrice).div(underlyingFullUnit);
}
}
Loading