contract_name
stringlengths 1
61
| file_path
stringlengths 5
50.4k
| contract_address
stringlengths 42
42
| language
stringclasses 1
value | class_name
stringlengths 1
61
| class_code
stringlengths 4
330k
| class_documentation
stringlengths 0
29.1k
| class_documentation_type
stringclasses 6
values | func_name
stringlengths 0
62
| func_code
stringlengths 1
303k
| func_documentation
stringlengths 2
14.9k
| func_documentation_type
stringclasses 4
values | compiler_version
stringlengths 15
42
| license_type
stringclasses 14
values | swarm_source
stringlengths 0
71
| meta
dict | __index_level_0__
int64 0
60.4k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
KojiCrowdSale | /C/Users/carme/OneDrive/Documents/Crypto/projects/ethereum/Koji_Perm/contracts/KojiCrowdSale.sol | 0x70988224d9b203cf10fabd550249e383f39f3707 | Solidity | KojiCrowdSale | contract KojiCrowdSale is Crowdsale, AllowanceCrowdsale, TimedCrowdsale, FinalizableCrowdsale, RefundableCrowdsale, PostDeliveryCrowdsale, CappedCrowdsale, CapperRole {
using SafeMath for uint256;
mapping(address => uint256) private _contributions;
mapping(address => uint256) private _caps;
uint256 private _individualDefaultCap;
constructor(
uint256 _rate, //000000003 = 3 billion per eth
address payable _wallet, //where the eth goes
IERC20 _token, //token contract address
address _tokenWallet, //address holding the tokens
uint256 _openingTime, //start time in unix time
uint256 _closingTime, //end time in unix time
uint256 individualCap, //per wallet cap in wei
uint256 _softcap, //minimum goal
uint256 _cap //total sale cap in wei
)
public
AllowanceCrowdsale(_tokenWallet)
Crowdsale(_rate, _wallet, _token)
TimedCrowdsale(_openingTime, _closingTime)
FinalizableCrowdsale()
RefundableCrowdsale(_softcap)
PostDeliveryCrowdsale(_softcap)
CappedCrowdsale(_cap)
{
_individualDefaultCap = individualCap;
}
address payable owner = msg.sender;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function withdrawUnsoldTokens(address tokenAddress) onlyOwner public
{
require(msg.sender == owner);
ERC20 mytoken = ERC20(tokenAddress);
uint256 unsold = mytoken.balanceOf(address(this));
mytoken.transfer(owner, unsold);
}
/**
* @dev Sets a specific beneficiary's maximum contribution.
* @param beneficiary Address to be capped
* @param cap Wei limit for individual contribution
*/
function setCap(address beneficiary, uint256 cap) external onlyCapper {
_caps[beneficiary] = cap;
}
/**
* @dev Returns the cap of a specific beneficiary.
* @param beneficiary Address whose cap is to be checked
* @return Current cap for individual beneficiary
*/
function getCap(address beneficiary) public view returns (uint256) {
uint256 cap = _caps[beneficiary];
if (cap == 0) {
cap = _individualDefaultCap;
}
return cap;
}
/**
* @dev Returns the amount contributed so far by a specific beneficiary.
* @param beneficiary Address of contributor
* @return Beneficiary contribution so far
*/
function getContribution(address beneficiary) public view returns (uint256) {
return _contributions[beneficiary];
}
/**
* @dev Extend parent behavior requiring purchase to respect the beneficiary's funding cap.
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
super._preValidatePurchase(beneficiary, weiAmount);
// solhint-disable-next-line max-line-length
require(_contributions[beneficiary].add(weiAmount) <= getCap(beneficiary), "KOJISale: wallet cap exceeded");
}
/**
* @dev Extend parent behavior to update beneficiary contributions.
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
super._updatePurchasingState(beneficiary, weiAmount);
_contributions[beneficiary] = _contributions[beneficiary].add(weiAmount);
}
} | setCap | function setCap(address beneficiary, uint256 cap) external onlyCapper {
_caps[beneficiary] = cap;
}
| /**
* @dev Sets a specific beneficiary's maximum contribution.
* @param beneficiary Address to be capped
* @param cap Wei limit for individual contribution
*/ | NatSpecMultiLine | v0.5.0+commit.1d4f565a | {
"func_code_index": [
1844,
1962
]
} | 12,000 |
||||
KojiCrowdSale | /C/Users/carme/OneDrive/Documents/Crypto/projects/ethereum/Koji_Perm/contracts/KojiCrowdSale.sol | 0x70988224d9b203cf10fabd550249e383f39f3707 | Solidity | KojiCrowdSale | contract KojiCrowdSale is Crowdsale, AllowanceCrowdsale, TimedCrowdsale, FinalizableCrowdsale, RefundableCrowdsale, PostDeliveryCrowdsale, CappedCrowdsale, CapperRole {
using SafeMath for uint256;
mapping(address => uint256) private _contributions;
mapping(address => uint256) private _caps;
uint256 private _individualDefaultCap;
constructor(
uint256 _rate, //000000003 = 3 billion per eth
address payable _wallet, //where the eth goes
IERC20 _token, //token contract address
address _tokenWallet, //address holding the tokens
uint256 _openingTime, //start time in unix time
uint256 _closingTime, //end time in unix time
uint256 individualCap, //per wallet cap in wei
uint256 _softcap, //minimum goal
uint256 _cap //total sale cap in wei
)
public
AllowanceCrowdsale(_tokenWallet)
Crowdsale(_rate, _wallet, _token)
TimedCrowdsale(_openingTime, _closingTime)
FinalizableCrowdsale()
RefundableCrowdsale(_softcap)
PostDeliveryCrowdsale(_softcap)
CappedCrowdsale(_cap)
{
_individualDefaultCap = individualCap;
}
address payable owner = msg.sender;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function withdrawUnsoldTokens(address tokenAddress) onlyOwner public
{
require(msg.sender == owner);
ERC20 mytoken = ERC20(tokenAddress);
uint256 unsold = mytoken.balanceOf(address(this));
mytoken.transfer(owner, unsold);
}
/**
* @dev Sets a specific beneficiary's maximum contribution.
* @param beneficiary Address to be capped
* @param cap Wei limit for individual contribution
*/
function setCap(address beneficiary, uint256 cap) external onlyCapper {
_caps[beneficiary] = cap;
}
/**
* @dev Returns the cap of a specific beneficiary.
* @param beneficiary Address whose cap is to be checked
* @return Current cap for individual beneficiary
*/
function getCap(address beneficiary) public view returns (uint256) {
uint256 cap = _caps[beneficiary];
if (cap == 0) {
cap = _individualDefaultCap;
}
return cap;
}
/**
* @dev Returns the amount contributed so far by a specific beneficiary.
* @param beneficiary Address of contributor
* @return Beneficiary contribution so far
*/
function getContribution(address beneficiary) public view returns (uint256) {
return _contributions[beneficiary];
}
/**
* @dev Extend parent behavior requiring purchase to respect the beneficiary's funding cap.
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
super._preValidatePurchase(beneficiary, weiAmount);
// solhint-disable-next-line max-line-length
require(_contributions[beneficiary].add(weiAmount) <= getCap(beneficiary), "KOJISale: wallet cap exceeded");
}
/**
* @dev Extend parent behavior to update beneficiary contributions.
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
super._updatePurchasingState(beneficiary, weiAmount);
_contributions[beneficiary] = _contributions[beneficiary].add(weiAmount);
}
} | getCap | function getCap(address beneficiary) public view returns (uint256) {
uint256 cap = _caps[beneficiary];
if (cap == 0) {
cap = _individualDefaultCap;
}
return cap;
}
| /**
* @dev Returns the cap of a specific beneficiary.
* @param beneficiary Address whose cap is to be checked
* @return Current cap for individual beneficiary
*/ | NatSpecMultiLine | v0.5.0+commit.1d4f565a | {
"func_code_index": [
2156,
2378
]
} | 12,001 |
||||
KojiCrowdSale | /C/Users/carme/OneDrive/Documents/Crypto/projects/ethereum/Koji_Perm/contracts/KojiCrowdSale.sol | 0x70988224d9b203cf10fabd550249e383f39f3707 | Solidity | KojiCrowdSale | contract KojiCrowdSale is Crowdsale, AllowanceCrowdsale, TimedCrowdsale, FinalizableCrowdsale, RefundableCrowdsale, PostDeliveryCrowdsale, CappedCrowdsale, CapperRole {
using SafeMath for uint256;
mapping(address => uint256) private _contributions;
mapping(address => uint256) private _caps;
uint256 private _individualDefaultCap;
constructor(
uint256 _rate, //000000003 = 3 billion per eth
address payable _wallet, //where the eth goes
IERC20 _token, //token contract address
address _tokenWallet, //address holding the tokens
uint256 _openingTime, //start time in unix time
uint256 _closingTime, //end time in unix time
uint256 individualCap, //per wallet cap in wei
uint256 _softcap, //minimum goal
uint256 _cap //total sale cap in wei
)
public
AllowanceCrowdsale(_tokenWallet)
Crowdsale(_rate, _wallet, _token)
TimedCrowdsale(_openingTime, _closingTime)
FinalizableCrowdsale()
RefundableCrowdsale(_softcap)
PostDeliveryCrowdsale(_softcap)
CappedCrowdsale(_cap)
{
_individualDefaultCap = individualCap;
}
address payable owner = msg.sender;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function withdrawUnsoldTokens(address tokenAddress) onlyOwner public
{
require(msg.sender == owner);
ERC20 mytoken = ERC20(tokenAddress);
uint256 unsold = mytoken.balanceOf(address(this));
mytoken.transfer(owner, unsold);
}
/**
* @dev Sets a specific beneficiary's maximum contribution.
* @param beneficiary Address to be capped
* @param cap Wei limit for individual contribution
*/
function setCap(address beneficiary, uint256 cap) external onlyCapper {
_caps[beneficiary] = cap;
}
/**
* @dev Returns the cap of a specific beneficiary.
* @param beneficiary Address whose cap is to be checked
* @return Current cap for individual beneficiary
*/
function getCap(address beneficiary) public view returns (uint256) {
uint256 cap = _caps[beneficiary];
if (cap == 0) {
cap = _individualDefaultCap;
}
return cap;
}
/**
* @dev Returns the amount contributed so far by a specific beneficiary.
* @param beneficiary Address of contributor
* @return Beneficiary contribution so far
*/
function getContribution(address beneficiary) public view returns (uint256) {
return _contributions[beneficiary];
}
/**
* @dev Extend parent behavior requiring purchase to respect the beneficiary's funding cap.
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
super._preValidatePurchase(beneficiary, weiAmount);
// solhint-disable-next-line max-line-length
require(_contributions[beneficiary].add(weiAmount) <= getCap(beneficiary), "KOJISale: wallet cap exceeded");
}
/**
* @dev Extend parent behavior to update beneficiary contributions.
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
super._updatePurchasingState(beneficiary, weiAmount);
_contributions[beneficiary] = _contributions[beneficiary].add(weiAmount);
}
} | getContribution | function getContribution(address beneficiary) public view returns (uint256) {
return _contributions[beneficiary];
}
| /**
* @dev Returns the amount contributed so far by a specific beneficiary.
* @param beneficiary Address of contributor
* @return Beneficiary contribution so far
*/ | NatSpecMultiLine | v0.5.0+commit.1d4f565a | {
"func_code_index": [
2575,
2709
]
} | 12,002 |
||||
KojiCrowdSale | /C/Users/carme/OneDrive/Documents/Crypto/projects/ethereum/Koji_Perm/contracts/KojiCrowdSale.sol | 0x70988224d9b203cf10fabd550249e383f39f3707 | Solidity | KojiCrowdSale | contract KojiCrowdSale is Crowdsale, AllowanceCrowdsale, TimedCrowdsale, FinalizableCrowdsale, RefundableCrowdsale, PostDeliveryCrowdsale, CappedCrowdsale, CapperRole {
using SafeMath for uint256;
mapping(address => uint256) private _contributions;
mapping(address => uint256) private _caps;
uint256 private _individualDefaultCap;
constructor(
uint256 _rate, //000000003 = 3 billion per eth
address payable _wallet, //where the eth goes
IERC20 _token, //token contract address
address _tokenWallet, //address holding the tokens
uint256 _openingTime, //start time in unix time
uint256 _closingTime, //end time in unix time
uint256 individualCap, //per wallet cap in wei
uint256 _softcap, //minimum goal
uint256 _cap //total sale cap in wei
)
public
AllowanceCrowdsale(_tokenWallet)
Crowdsale(_rate, _wallet, _token)
TimedCrowdsale(_openingTime, _closingTime)
FinalizableCrowdsale()
RefundableCrowdsale(_softcap)
PostDeliveryCrowdsale(_softcap)
CappedCrowdsale(_cap)
{
_individualDefaultCap = individualCap;
}
address payable owner = msg.sender;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function withdrawUnsoldTokens(address tokenAddress) onlyOwner public
{
require(msg.sender == owner);
ERC20 mytoken = ERC20(tokenAddress);
uint256 unsold = mytoken.balanceOf(address(this));
mytoken.transfer(owner, unsold);
}
/**
* @dev Sets a specific beneficiary's maximum contribution.
* @param beneficiary Address to be capped
* @param cap Wei limit for individual contribution
*/
function setCap(address beneficiary, uint256 cap) external onlyCapper {
_caps[beneficiary] = cap;
}
/**
* @dev Returns the cap of a specific beneficiary.
* @param beneficiary Address whose cap is to be checked
* @return Current cap for individual beneficiary
*/
function getCap(address beneficiary) public view returns (uint256) {
uint256 cap = _caps[beneficiary];
if (cap == 0) {
cap = _individualDefaultCap;
}
return cap;
}
/**
* @dev Returns the amount contributed so far by a specific beneficiary.
* @param beneficiary Address of contributor
* @return Beneficiary contribution so far
*/
function getContribution(address beneficiary) public view returns (uint256) {
return _contributions[beneficiary];
}
/**
* @dev Extend parent behavior requiring purchase to respect the beneficiary's funding cap.
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
super._preValidatePurchase(beneficiary, weiAmount);
// solhint-disable-next-line max-line-length
require(_contributions[beneficiary].add(weiAmount) <= getCap(beneficiary), "KOJISale: wallet cap exceeded");
}
/**
* @dev Extend parent behavior to update beneficiary contributions.
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
super._updatePurchasingState(beneficiary, weiAmount);
_contributions[beneficiary] = _contributions[beneficiary].add(weiAmount);
}
} | _preValidatePurchase | function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
super._preValidatePurchase(beneficiary, weiAmount);
// solhint-disable-next-line max-line-length
require(_contributions[beneficiary].add(weiAmount) <= getCap(beneficiary), "KOJISale: wallet cap exceeded");
}
| /**
* @dev Extend parent behavior requiring purchase to respect the beneficiary's funding cap.
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/ | NatSpecMultiLine | v0.5.0+commit.1d4f565a | {
"func_code_index": [
2921,
3251
]
} | 12,003 |
||||
KojiCrowdSale | /C/Users/carme/OneDrive/Documents/Crypto/projects/ethereum/Koji_Perm/contracts/KojiCrowdSale.sol | 0x70988224d9b203cf10fabd550249e383f39f3707 | Solidity | KojiCrowdSale | contract KojiCrowdSale is Crowdsale, AllowanceCrowdsale, TimedCrowdsale, FinalizableCrowdsale, RefundableCrowdsale, PostDeliveryCrowdsale, CappedCrowdsale, CapperRole {
using SafeMath for uint256;
mapping(address => uint256) private _contributions;
mapping(address => uint256) private _caps;
uint256 private _individualDefaultCap;
constructor(
uint256 _rate, //000000003 = 3 billion per eth
address payable _wallet, //where the eth goes
IERC20 _token, //token contract address
address _tokenWallet, //address holding the tokens
uint256 _openingTime, //start time in unix time
uint256 _closingTime, //end time in unix time
uint256 individualCap, //per wallet cap in wei
uint256 _softcap, //minimum goal
uint256 _cap //total sale cap in wei
)
public
AllowanceCrowdsale(_tokenWallet)
Crowdsale(_rate, _wallet, _token)
TimedCrowdsale(_openingTime, _closingTime)
FinalizableCrowdsale()
RefundableCrowdsale(_softcap)
PostDeliveryCrowdsale(_softcap)
CappedCrowdsale(_cap)
{
_individualDefaultCap = individualCap;
}
address payable owner = msg.sender;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function withdrawUnsoldTokens(address tokenAddress) onlyOwner public
{
require(msg.sender == owner);
ERC20 mytoken = ERC20(tokenAddress);
uint256 unsold = mytoken.balanceOf(address(this));
mytoken.transfer(owner, unsold);
}
/**
* @dev Sets a specific beneficiary's maximum contribution.
* @param beneficiary Address to be capped
* @param cap Wei limit for individual contribution
*/
function setCap(address beneficiary, uint256 cap) external onlyCapper {
_caps[beneficiary] = cap;
}
/**
* @dev Returns the cap of a specific beneficiary.
* @param beneficiary Address whose cap is to be checked
* @return Current cap for individual beneficiary
*/
function getCap(address beneficiary) public view returns (uint256) {
uint256 cap = _caps[beneficiary];
if (cap == 0) {
cap = _individualDefaultCap;
}
return cap;
}
/**
* @dev Returns the amount contributed so far by a specific beneficiary.
* @param beneficiary Address of contributor
* @return Beneficiary contribution so far
*/
function getContribution(address beneficiary) public view returns (uint256) {
return _contributions[beneficiary];
}
/**
* @dev Extend parent behavior requiring purchase to respect the beneficiary's funding cap.
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
super._preValidatePurchase(beneficiary, weiAmount);
// solhint-disable-next-line max-line-length
require(_contributions[beneficiary].add(weiAmount) <= getCap(beneficiary), "KOJISale: wallet cap exceeded");
}
/**
* @dev Extend parent behavior to update beneficiary contributions.
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
super._updatePurchasingState(beneficiary, weiAmount);
_contributions[beneficiary] = _contributions[beneficiary].add(weiAmount);
}
} | _updatePurchasingState | function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
super._updatePurchasingState(beneficiary, weiAmount);
_contributions[beneficiary] = _contributions[beneficiary].add(weiAmount);
}
| /**
* @dev Extend parent behavior to update beneficiary contributions.
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/ | NatSpecMultiLine | v0.5.0+commit.1d4f565a | {
"func_code_index": [
3439,
3681
]
} | 12,004 |
||||
Pool5 | Pool5.sol | 0xbe85b1caae77b85e572b1d85262b5c36852ee9eb | Solidity | EnumerableSet | library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
} | /**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/ | NatSpecMultiLine | _add | function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
| /**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://0094ff82d0c2c1b967b6cd670bc54616ec16abf15694641bcc271837a136a3ed | {
"func_code_index": [
908,
1327
]
} | 12,005 |
Pool5 | Pool5.sol | 0xbe85b1caae77b85e572b1d85262b5c36852ee9eb | Solidity | EnumerableSet | library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
} | /**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/ | NatSpecMultiLine | _remove | function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
| /**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://0094ff82d0c2c1b967b6cd670bc54616ec16abf15694641bcc271837a136a3ed | {
"func_code_index": [
1498,
3047
]
} | 12,006 |
Pool5 | Pool5.sol | 0xbe85b1caae77b85e572b1d85262b5c36852ee9eb | Solidity | EnumerableSet | library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
} | /**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/ | NatSpecMultiLine | _contains | function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
| /**
* @dev Returns true if the value is in the set. O(1).
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://0094ff82d0c2c1b967b6cd670bc54616ec16abf15694641bcc271837a136a3ed | {
"func_code_index": [
3128,
3262
]
} | 12,007 |
Pool5 | Pool5.sol | 0xbe85b1caae77b85e572b1d85262b5c36852ee9eb | Solidity | EnumerableSet | library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
} | /**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/ | NatSpecMultiLine | _length | function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
| /**
* @dev Returns the number of values on the set. O(1).
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://0094ff82d0c2c1b967b6cd670bc54616ec16abf15694641bcc271837a136a3ed | {
"func_code_index": [
3343,
3457
]
} | 12,008 |
Pool5 | Pool5.sol | 0xbe85b1caae77b85e572b1d85262b5c36852ee9eb | Solidity | EnumerableSet | library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
} | /**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/ | NatSpecMultiLine | _at | function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
| /**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://0094ff82d0c2c1b967b6cd670bc54616ec16abf15694641bcc271837a136a3ed | {
"func_code_index": [
3796,
4005
]
} | 12,009 |
Pool5 | Pool5.sol | 0xbe85b1caae77b85e572b1d85262b5c36852ee9eb | Solidity | EnumerableSet | library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
} | /**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/ | NatSpecMultiLine | add | function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
| /**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://0094ff82d0c2c1b967b6cd670bc54616ec16abf15694641bcc271837a136a3ed | {
"func_code_index": [
4254,
4402
]
} | 12,010 |
Pool5 | Pool5.sol | 0xbe85b1caae77b85e572b1d85262b5c36852ee9eb | Solidity | EnumerableSet | library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
} | /**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/ | NatSpecMultiLine | remove | function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
| /**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://0094ff82d0c2c1b967b6cd670bc54616ec16abf15694641bcc271837a136a3ed | {
"func_code_index": [
4573,
4727
]
} | 12,011 |
Pool5 | Pool5.sol | 0xbe85b1caae77b85e572b1d85262b5c36852ee9eb | Solidity | EnumerableSet | library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
} | /**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/ | NatSpecMultiLine | contains | function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
| /**
* @dev Returns true if the value is in the set. O(1).
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://0094ff82d0c2c1b967b6cd670bc54616ec16abf15694641bcc271837a136a3ed | {
"func_code_index": [
4808,
4971
]
} | 12,012 |
Pool5 | Pool5.sol | 0xbe85b1caae77b85e572b1d85262b5c36852ee9eb | Solidity | EnumerableSet | library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
} | /**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/ | NatSpecMultiLine | length | function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
| /**
* @dev Returns the number of values in the set. O(1).
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://0094ff82d0c2c1b967b6cd670bc54616ec16abf15694641bcc271837a136a3ed | {
"func_code_index": [
5052,
5174
]
} | 12,013 |
Pool5 | Pool5.sol | 0xbe85b1caae77b85e572b1d85262b5c36852ee9eb | Solidity | EnumerableSet | library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
} | /**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/ | NatSpecMultiLine | at | function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
| /**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://0094ff82d0c2c1b967b6cd670bc54616ec16abf15694641bcc271837a136a3ed | {
"func_code_index": [
5513,
5667
]
} | 12,014 |
Pool5 | Pool5.sol | 0xbe85b1caae77b85e572b1d85262b5c36852ee9eb | Solidity | EnumerableSet | library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
} | /**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/ | NatSpecMultiLine | add | function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
| /**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://0094ff82d0c2c1b967b6cd670bc54616ec16abf15694641bcc271837a136a3ed | {
"func_code_index": [
5912,
6048
]
} | 12,015 |
Pool5 | Pool5.sol | 0xbe85b1caae77b85e572b1d85262b5c36852ee9eb | Solidity | EnumerableSet | library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
} | /**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/ | NatSpecMultiLine | remove | function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
| /**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://0094ff82d0c2c1b967b6cd670bc54616ec16abf15694641bcc271837a136a3ed | {
"func_code_index": [
6219,
6361
]
} | 12,016 |
Pool5 | Pool5.sol | 0xbe85b1caae77b85e572b1d85262b5c36852ee9eb | Solidity | EnumerableSet | library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
} | /**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/ | NatSpecMultiLine | contains | function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
| /**
* @dev Returns true if the value is in the set. O(1).
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://0094ff82d0c2c1b967b6cd670bc54616ec16abf15694641bcc271837a136a3ed | {
"func_code_index": [
6442,
6593
]
} | 12,017 |
Pool5 | Pool5.sol | 0xbe85b1caae77b85e572b1d85262b5c36852ee9eb | Solidity | EnumerableSet | library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
} | /**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/ | NatSpecMultiLine | length | function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
| /**
* @dev Returns the number of values on the set. O(1).
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://0094ff82d0c2c1b967b6cd670bc54616ec16abf15694641bcc271837a136a3ed | {
"func_code_index": [
6674,
6793
]
} | 12,018 |
Pool5 | Pool5.sol | 0xbe85b1caae77b85e572b1d85262b5c36852ee9eb | Solidity | EnumerableSet | library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
} | /**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/ | NatSpecMultiLine | at | function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
| /**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://0094ff82d0c2c1b967b6cd670bc54616ec16abf15694641bcc271837a136a3ed | {
"func_code_index": [
7132,
7274
]
} | 12,019 |
Pool5 | Pool5.sol | 0xbe85b1caae77b85e572b1d85262b5c36852ee9eb | Solidity | Ownable | contract Ownable {
address public admin;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
admin = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == admin);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(admin, newOwner);
admin = newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | transferOwnership | function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(admin, newOwner);
admin = newOwner;
}
| /**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://0094ff82d0c2c1b967b6cd670bc54616ec16abf15694641bcc271837a136a3ed | {
"func_code_index": [
639,
820
]
} | 12,020 |
Pool5 | Pool5.sol | 0xbe85b1caae77b85e572b1d85262b5c36852ee9eb | Solidity | Pool5 | contract Pool5 is Ownable {
using SafeMath for uint;
using EnumerableSet for EnumerableSet.AddressSet;
event RewardsTransferred(address holder, uint amount);
address public tokenAddress;
address public liquiditytoken1;
// reward rate % per year
uint public rewardRate = 60000;
uint public rewardInterval = 365 days;
// staking fee percent
uint public stakingFeeRate = 0;
// unstaking fee percent
uint public unstakingFeeRate = 0;
// unstaking possible Time
uint public PossibleUnstakeTime = 24 hours;
uint public totalClaimedRewards = 0;
uint private FundedTokens;
bool public stakingStatus = false;
EnumerableSet.AddressSet private holders;
mapping (address => uint) public depositedTokens;
mapping (address => uint) public stakingTime;
mapping (address => uint) public lastClaimedTime;
mapping (address => uint) public totalEarnedTokens;
/*=============================ADMINISTRATIVE FUNCTIONS ==================================*/
function setTokenAddresses(address _tokenAddr, address _liquidityAddr) public onlyOwner returns(bool){
require(_tokenAddr != address(0) && _liquidityAddr != address(0), "Invalid addresses format are not supported");
tokenAddress = _tokenAddr;
liquiditytoken1 = _liquidityAddr;
}
function stakingFeeRateSet(uint _stakingFeeRate, uint _unstakingFeeRate) public onlyOwner returns(bool){
stakingFeeRate = _stakingFeeRate;
unstakingFeeRate = _unstakingFeeRate;
}
function rewardRateSet(uint _rewardRate) public onlyOwner returns(bool){
rewardRate = _rewardRate;
}
function StakingReturnsAmountSet(uint _poolreward) public onlyOwner returns(bool){
FundedTokens = _poolreward;
}
function possibleUnstakeTimeSet(uint _possibleUnstakeTime) public onlyOwner returns(bool){
PossibleUnstakeTime = _possibleUnstakeTime;
}
function rewardIntervalSet(uint _rewardInterval) public onlyOwner returns(bool){
rewardInterval = _rewardInterval;
}
function allowStaking(bool _status) public onlyOwner returns(bool){
require(tokenAddress != address(0) && liquiditytoken1 != address(0), "Interracting token addresses are not yet configured");
stakingStatus = _status;
}
function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner {
if (_tokenAddr == tokenAddress) {
if (_amount > getFundedTokens()) {
revert();
}
totalClaimedRewards = totalClaimedRewards.add(_amount);
}
Token(_tokenAddr).transfer(_to, _amount);
}
function updateAccount(address account) private {
uint unclaimedDivs = getUnclaimedDivs(account);
if (unclaimedDivs > 0) {
require(Token(tokenAddress).transfer(account, unclaimedDivs), "Could not transfer tokens.");
totalEarnedTokens[account] = totalEarnedTokens[account].add(unclaimedDivs);
totalClaimedRewards = totalClaimedRewards.add(unclaimedDivs);
emit RewardsTransferred(account, unclaimedDivs);
}
lastClaimedTime[account] = now;
}
function getUnclaimedDivs(address _holder) public view returns (uint) {
if (!holders.contains(_holder)) return 0;
if (depositedTokens[_holder] == 0) return 0;
uint timeDiff = now.sub(lastClaimedTime[_holder]);
uint stakedAmount = depositedTokens[_holder];
uint unclaimedDivs = stakedAmount
.mul(rewardRate)
.mul(timeDiff)
.div(rewardInterval)
.div(1e4);
return unclaimedDivs;
}
function getNumberOfHolders() public view returns (uint) {
return holders.length();
}
function place(uint amountToStake) public {
require(stakingStatus == true, "Staking is not yet initialized");
require(amountToStake > 0, "Cannot deposit 0 Tokens");
require(Token(liquiditytoken1).transferFrom(msg.sender, address(this), amountToStake), "Insufficient Token Allowance");
updateAccount(msg.sender);
uint fee = amountToStake.mul(stakingFeeRate).div(1e4);
uint amountAfterFee = amountToStake.sub(fee);
require(Token(liquiditytoken1).transfer(admin, fee), "Could not transfer deposit fee.");
depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountAfterFee);
if (!holders.contains(msg.sender)) {
holders.add(msg.sender);
stakingTime[msg.sender] = now;
}
}
function lift(uint amountToWithdraw) public {
require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw");
require(now.sub(stakingTime[msg.sender]) > PossibleUnstakeTime, "You have not staked for a while yet, kindly wait a bit more");
updateAccount(msg.sender);
uint fee = amountToWithdraw.mul(unstakingFeeRate).div(1e4);
uint amountAfterFee = amountToWithdraw.sub(fee);
require(Token(liquiditytoken1).transfer(admin, fee), "Could not transfer withdraw fee.");
require(Token(liquiditytoken1).transfer(msg.sender, amountAfterFee), "Could not transfer tokens.");
depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw);
if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) {
holders.remove(msg.sender);
}
}
function claimYields() public {
updateAccount(msg.sender);
}
function getFundedTokens() public view returns (uint) {
if (totalClaimedRewards >= FundedTokens) {
return 0;
}
uint remaining = FundedTokens.sub(totalClaimedRewards);
return remaining;
}
} | setTokenAddresses | function setTokenAddresses(address _tokenAddr, address _liquidityAddr) public onlyOwner returns(bool){
require(_tokenAddr != address(0) && _liquidityAddr != address(0), "Invalid addresses format are not supported");
tokenAddress = _tokenAddr;
liquiditytoken1 = _liquidityAddr;
}
| /*=============================ADMINISTRATIVE FUNCTIONS ==================================*/ | Comment | v0.6.12+commit.27d51765 | MIT | ipfs://0094ff82d0c2c1b967b6cd670bc54616ec16abf15694641bcc271837a136a3ed | {
"func_code_index": [
1125,
1437
]
} | 12,021 |
||
Wearables | multi-token-standard/contracts/interfaces/IERC1155.sol | 0xdb8cfaa3c4de5d03602a9da8d0ff248ff00fadef | Solidity | IERC1155 | interface IERC1155 {
// Events
/**
* @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning
* Operator MUST be msg.sender
* When minting/creating tokens, the `_from` field MUST be set to `0x0`
* When burning/destroying tokens, the `_to` field MUST be set to `0x0`
* The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID
* To broadcast the existence of a token ID with no initial balance, the contract SHOULD emit the TransferSingle event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0
*/
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount);
/**
* @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning
* Operator MUST be msg.sender
* When minting/creating tokens, the `_from` field MUST be set to `0x0`
* When burning/destroying tokens, the `_to` field MUST be set to `0x0`
* The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID
* To broadcast the existence of multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0
*/
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts);
/**
* @dev MUST emit when an approval is updated
*/
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/**
* @dev MUST emit when the URI is updated for a token ID
* URIs are defined in RFC 3986
* The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata JSON Schema"
*/
event URI(string _amount, uint256 indexed _id);
/**
* @notice Transfers amount of an _id from the _from address to the _to address specified
* @dev MUST emit TransferSingle event on success
* Caller must be approved to manage the _from account's tokens (see isApprovedForAll)
* MUST throw if `_to` is the zero address
* MUST throw if balance of sender for token `_id` is lower than the `_amount` sent
* MUST throw on any other error
* When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155Received` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes calldata _data) external;
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @dev MUST emit TransferBatch event on success
* Caller must be approved to manage the _from account's tokens (see isApprovedForAll)
* MUST throw if `_to` is the zero address
* MUST throw if length of `_ids` is not the same as length of `_amounts`
* MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_amounts` sent
* MUST throw on any other error
* When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* Transfers and events MUST occur in the array order they were submitted (_ids[0] before _ids[1], etc)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external;
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @dev MUST emit the ApprovalForAll event on success
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved) external;
} | safeTransferFrom | function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes calldata _data) external;
| /**
* @notice Transfers amount of an _id from the _from address to the _to address specified
* @dev MUST emit TransferSingle event on success
* Caller must be approved to manage the _from account's tokens (see isApprovedForAll)
* MUST throw if `_to` is the zero address
* MUST throw if balance of sender for token `_id` is lower than the `_amount` sent
* MUST throw on any other error
* When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155Received` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/ | NatSpecMultiLine | v0.5.12+commit.7709ece9 | None | bzzr://56974c90a9d406cedbf8e2c662434e6f24abd72fc449a93edc6c0776a34bafa4 | {
"func_code_index": [
3152,
3270
]
} | 12,022 |
||
Wearables | multi-token-standard/contracts/interfaces/IERC1155.sol | 0xdb8cfaa3c4de5d03602a9da8d0ff248ff00fadef | Solidity | IERC1155 | interface IERC1155 {
// Events
/**
* @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning
* Operator MUST be msg.sender
* When minting/creating tokens, the `_from` field MUST be set to `0x0`
* When burning/destroying tokens, the `_to` field MUST be set to `0x0`
* The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID
* To broadcast the existence of a token ID with no initial balance, the contract SHOULD emit the TransferSingle event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0
*/
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount);
/**
* @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning
* Operator MUST be msg.sender
* When minting/creating tokens, the `_from` field MUST be set to `0x0`
* When burning/destroying tokens, the `_to` field MUST be set to `0x0`
* The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID
* To broadcast the existence of multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0
*/
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts);
/**
* @dev MUST emit when an approval is updated
*/
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/**
* @dev MUST emit when the URI is updated for a token ID
* URIs are defined in RFC 3986
* The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata JSON Schema"
*/
event URI(string _amount, uint256 indexed _id);
/**
* @notice Transfers amount of an _id from the _from address to the _to address specified
* @dev MUST emit TransferSingle event on success
* Caller must be approved to manage the _from account's tokens (see isApprovedForAll)
* MUST throw if `_to` is the zero address
* MUST throw if balance of sender for token `_id` is lower than the `_amount` sent
* MUST throw on any other error
* When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155Received` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes calldata _data) external;
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @dev MUST emit TransferBatch event on success
* Caller must be approved to manage the _from account's tokens (see isApprovedForAll)
* MUST throw if `_to` is the zero address
* MUST throw if length of `_ids` is not the same as length of `_amounts`
* MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_amounts` sent
* MUST throw on any other error
* When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* Transfers and events MUST occur in the array order they were submitted (_ids[0] before _ids[1], etc)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external;
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @dev MUST emit the ApprovalForAll event on success
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved) external;
} | safeBatchTransferFrom | function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external;
| /**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @dev MUST emit TransferBatch event on success
* Caller must be approved to manage the _from account's tokens (see isApprovedForAll)
* MUST throw if `_to` is the zero address
* MUST throw if length of `_ids` is not the same as length of `_amounts`
* MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_amounts` sent
* MUST throw on any other error
* When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* Transfers and events MUST occur in the array order they were submitted (_ids[0] before _ids[1], etc)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/ | NatSpecMultiLine | v0.5.12+commit.7709ece9 | None | bzzr://56974c90a9d406cedbf8e2c662434e6f24abd72fc449a93edc6c0776a34bafa4 | {
"func_code_index": [
4464,
4611
]
} | 12,023 |
||
Wearables | multi-token-standard/contracts/interfaces/IERC1155.sol | 0xdb8cfaa3c4de5d03602a9da8d0ff248ff00fadef | Solidity | IERC1155 | interface IERC1155 {
// Events
/**
* @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning
* Operator MUST be msg.sender
* When minting/creating tokens, the `_from` field MUST be set to `0x0`
* When burning/destroying tokens, the `_to` field MUST be set to `0x0`
* The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID
* To broadcast the existence of a token ID with no initial balance, the contract SHOULD emit the TransferSingle event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0
*/
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount);
/**
* @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning
* Operator MUST be msg.sender
* When minting/creating tokens, the `_from` field MUST be set to `0x0`
* When burning/destroying tokens, the `_to` field MUST be set to `0x0`
* The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID
* To broadcast the existence of multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0
*/
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts);
/**
* @dev MUST emit when an approval is updated
*/
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/**
* @dev MUST emit when the URI is updated for a token ID
* URIs are defined in RFC 3986
* The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata JSON Schema"
*/
event URI(string _amount, uint256 indexed _id);
/**
* @notice Transfers amount of an _id from the _from address to the _to address specified
* @dev MUST emit TransferSingle event on success
* Caller must be approved to manage the _from account's tokens (see isApprovedForAll)
* MUST throw if `_to` is the zero address
* MUST throw if balance of sender for token `_id` is lower than the `_amount` sent
* MUST throw on any other error
* When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155Received` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes calldata _data) external;
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @dev MUST emit TransferBatch event on success
* Caller must be approved to manage the _from account's tokens (see isApprovedForAll)
* MUST throw if `_to` is the zero address
* MUST throw if length of `_ids` is not the same as length of `_amounts`
* MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_amounts` sent
* MUST throw on any other error
* When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* Transfers and events MUST occur in the array order they were submitted (_ids[0] before _ids[1], etc)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external;
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @dev MUST emit the ApprovalForAll event on success
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved) external;
} | setApprovalForAll | function setApprovalForAll(address _operator, bool _approved) external;
| /**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @dev MUST emit the ApprovalForAll event on success
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/ | NatSpecMultiLine | v0.5.12+commit.7709ece9 | None | bzzr://56974c90a9d406cedbf8e2c662434e6f24abd72fc449a93edc6c0776a34bafa4 | {
"func_code_index": [
4947,
5021
]
} | 12,024 |
||
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | getAccountBatches | function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
| /**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
5197,
5327
]
} | 12,025 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | depositForMint | function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
| /**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
5595,
6084
]
} | 12,026 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | depositForRedeem | function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
| /**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
6206,
6518
]
} | 12,027 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | withdrawFromBatch | function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
| /**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
6935,
7967
]
} | 12,028 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | claim | function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
| /**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
8240,
9269
]
} | 12,029 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | claimAndStake | function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
| /**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
9505,
9949
]
} | 12,030 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | moveUnclaimedDepositsIntoCurrentBatch | function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
| /**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
10711,
12463
]
} | 12,031 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | batchMint | function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
| /**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
13108,
17576
]
} | 12,032 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | batchRedeem | function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
| /**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
18082,
20678
]
} | 12,033 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | setApprovals | function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
| /**
* @notice sets approval for contracts that require access to assets held by this contract
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
20785,
21459
]
} | 12,034 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | getMinAmountToMint | function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
| /**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
21621,
21947
]
} | 12,035 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | getMinAmount3CrvFromRedeem | function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
| /**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
22113,
22431
]
} | 12,036 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | valueOfComponents | function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
| /**
* @notice returns the value of butter in virtualPrice
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
22502,
22948
]
} | 12,037 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | valueOf3Crv | function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
| /**
* @notice returns the value of an amount of 3crv in virtualPrice
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
23030,
23164
]
} | 12,038 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | _maxApprove | function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
| /**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
23429,
23589
]
} | 12,039 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | _getPoolAllocation | function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
| /**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
24872,
25014
]
} | 12,040 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | _setBasicIssuanceModuleAllowance | function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
| /**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
25120,
25325
]
} | 12,041 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | _getRecipient | function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
| /**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
25838,
26362
]
} | 12,042 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | _generateNextBatch | function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
| /**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
26561,
27238
]
} | 12,043 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | _deposit | function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
| /**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
27716,
28504
]
} | 12,044 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | _prepareClaim | function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
| /**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
28813,
29750
]
} | 12,045 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | _sendToCurve | function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
| /**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
29961,
30362
]
} | 12,046 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | _withdrawFromCurve | function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
| /**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
30568,
30973
]
} | 12,047 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | _sendToYearn | function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
| /**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
31155,
31332
]
} | 12,048 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | _withdrawFromYearn | function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
| /**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
31512,
31689
]
} | 12,049 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | _generateNextBatchId | function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
| /**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
31831,
31999
]
} | 12,050 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | setCurvePoolTokenPairs | function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
| /**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
32350,
32581
]
} | 12,051 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | _setCurvePoolTokenPairs | function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
| /**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
33121,
33470
]
} | 12,052 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | setProcessingThreshold | function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
| /**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
33785,
34262
]
} | 12,053 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | setSlippage | function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
| /**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
34439,
34802
]
} | 12,054 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | setRedemptionFee | function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
| /**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
35147,
35425
]
} | 12,055 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | claimRedemptionFee | function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
| /**
* @notice Claims all accumulated redemption fees in 3CRV
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
35499,
35659
]
} | 12,056 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | recoverLeftover | function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
| /**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
36084,
36382
]
} | 12,057 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | updateSweetheart | function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
| /**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
36577,
36766
]
} | 12,058 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | pause | function pause() external onlyRole(DAO_ROLE) {
_pause();
}
| /**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
36925,
36991
]
} | 12,059 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | unpause | function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
| /**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
37152,
37222
]
} | 12,060 |
|
ButterBatchProcessing | contracts/core/defi/butter/ButterBatchProcessing.sol | 0xcd979a9219db9a353e29981042a509f2e7074d8b | Solidity | ButterBatchProcessing | contract ButterBatchProcessing is Pausable, ReentrancyGuard, ACLAuth, KeeperIncentivized, ContractRegistryAccess {
using SafeERC20 for YearnVault;
using SafeERC20 for ISetToken;
using SafeERC20 for IERC20;
/**
* @notice Defines if the Batch will mint or redeem Butter
*/
enum BatchType {
Mint,
Redeem
}
/**
* @notice Defines if the Batch will mint or redeem Butter
* @param curveMetaPool A CurveMetaPool for trading an exotic stablecoin against 3CRV
* @param crvLPToken The LP-Token of the CurveMetapool
*/
struct CurvePoolTokenPair {
CurveMetapool curveMetaPool;
IERC20 crvLPToken;
}
struct ProcessingThreshold {
uint256 batchCooldown;
uint256 mintThreshold;
uint256 redeemThreshold;
}
struct RedemptionFee {
uint256 accumulated;
uint256 rate;
address recipient;
}
struct Slippage {
uint256 mintBps; // in bps
uint256 redeemBps; // in bps
}
/**
* @notice The Batch structure is used both for Batches of Minting and Redeeming
* @param batchType Determines if this Batch is for Minting or Redeeming Butter
* @param batchId bytes32 id of the batch
* @param claimable Shows if a batch has been processed and is ready to be claimed, the suppliedToken cant be withdrawn if a batch is claimable
* @param unclaimedShares The total amount of unclaimed shares in this batch
* @param suppliedTokenBalance The total amount of deposited token (either 3CRV or Butter)
* @param claimableTokenBalance The total amount of claimable token (either 3CRV or Butter)
* @param tokenAddress The address of the the token to be claimed
* @param shareBalance The individual share balance per user that has deposited token
*/
struct Batch {
BatchType batchType;
bytes32 batchId;
bool claimable;
uint256 unclaimedShares;
uint256 suppliedTokenBalance;
uint256 claimableTokenBalance;
address suppliedTokenAddress;
address claimableTokenAddress;
}
/* ========== STATE VARIABLES ========== */
bytes32 public immutable contractName = "ButterBatchProcessing";
IStaking public staking;
ISetToken public setToken;
IERC20 public threeCrv;
CurveMetapool public threePool;
BasicIssuanceModule public setBasicIssuanceModule;
mapping(address => CurvePoolTokenPair) public curvePoolTokenPairs;
/**
* @notice This maps batch ids to addresses with share balances
*/
mapping(bytes32 => mapping(address => uint256)) public accountBalances;
mapping(address => bytes32[]) public accountBatches;
mapping(bytes32 => Batch) public batches;
bytes32[] public batchIds;
uint256 public lastMintedAt;
uint256 public lastRedeemedAt;
bytes32 public currentMintBatchId;
bytes32 public currentRedeemBatchId;
Slippage public slippage;
ProcessingThreshold public processingThreshold;
RedemptionFee public redemptionFee;
mapping(address => bool) public sweethearts;
/* ========== EVENTS ========== */
event Deposit(address indexed from, uint256 deposit);
event Withdrawal(address indexed to, uint256 amount);
event SlippageUpdated(Slippage prev, Slippage current);
event BatchMinted(bytes32 batchId, uint256 suppliedTokenAmount, uint256 butterAmount);
event BatchRedeemed(bytes32 batchId, uint256 suppliedTokenAmount, uint256 threeCrvAmount);
event Claimed(address indexed account, BatchType batchType, uint256 shares, uint256 claimedToken);
event WithdrawnFromBatch(bytes32 batchId, uint256 amount, address indexed to);
event MovedUnclaimedDepositsIntoCurrentBatch(uint256 amount, BatchType batchType, address indexed account);
event CurveTokenPairsUpdated(address[] yTokenAddresses, CurvePoolTokenPair[] curveTokenPairs);
event ProcessingThresholdUpdated(ProcessingThreshold previousThreshold, ProcessingThreshold newProcessingThreshold);
event RedemptionFeeUpdated(uint256 newRedemptionFee, address newFeeRecipient);
event SweetheartUpdated(address sweetheart, bool isSweeheart);
event StakingUpdated(address beforeAddress, address afterAddress);
/* ========== CONSTRUCTOR ========== */
constructor(
IContractRegistry _contractRegistry,
IStaking _staking,
ISetToken _setToken,
IERC20 _threeCrv,
CurveMetapool _threePool,
BasicIssuanceModule _basicIssuanceModule,
address[] memory _yTokenAddresses,
CurvePoolTokenPair[] memory _curvePoolTokenPairs,
ProcessingThreshold memory _processingThreshold
) ContractRegistryAccess(_contractRegistry) {
staking = _staking;
setToken = _setToken;
threeCrv = _threeCrv;
threePool = _threePool;
setBasicIssuanceModule = _basicIssuanceModule;
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
processingThreshold = _processingThreshold;
lastMintedAt = block.timestamp;
lastRedeemedAt = block.timestamp;
_generateNextBatch(bytes32("mint"), BatchType.Mint);
_generateNextBatch(bytes32("redeem"), BatchType.Redeem);
slippage.mintBps = 7;
slippage.redeemBps = 7;
}
/* ========== VIEWS ========== */
/**
* @notice Get ids for all batches that a user has interacted with
* @param _account The address for whom we want to retrieve batches
*/
function getAccountBatches(address _account) external view returns (bytes32[] memory) {
return accountBatches[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Deposits funds in the current mint batch
* @param _amount Amount of 3cr3CRV to use for minting
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
*/
function depositForMint(uint256 _amount, address _depositFor)
external
nonReentrant
whenNotPaused
onlyApprovedContractOrEOA
{
require(
_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _depositFor,
"you cant transfer other funds"
);
require(threeCrv.balanceOf(msg.sender) >= _amount, "insufficent balance");
threeCrv.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentMintBatchId, _depositFor);
}
/**
* @notice deposits funds in the current redeem batch
* @param _amount amount of Butter to be redeemed
*/
function depositForRedeem(uint256 _amount) external nonReentrant whenNotPaused onlyApprovedContractOrEOA {
require(setToken.balanceOf(msg.sender) >= _amount, "insufficient balance");
setToken.transferFrom(msg.sender, address(this), _amount);
_deposit(_amount, currentRedeemBatchId, msg.sender);
}
/**
* @notice This function allows a user to withdraw their funds from a batch before that batch has been processed
* @param _batchId From which batch should funds be withdrawn from
* @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)
* @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)
*/
function withdrawFromBatch(
bytes32 _batchId,
uint256 _amountToWithdraw,
address _withdrawFor
) external {
address recipient = _getRecipient(_withdrawFor);
Batch storage batch = batches[_batchId];
uint256 accountBalance = accountBalances[_batchId][_withdrawFor];
require(batch.claimable == false, "already processed");
require(accountBalance >= _amountToWithdraw, "account has insufficient funds");
//At this point the account balance is equal to the supplied token and can be used interchangeably
accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;
batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;
batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;
if (batch.batchType == BatchType.Mint) {
threeCrv.safeTransfer(recipient, _amountToWithdraw);
} else {
setToken.safeTransfer(recipient, _amountToWithdraw);
}
emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);
}
/**
* @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
//Transfer token
if (batchType == BatchType.Mint) {
setToken.safeTransfer(recipient, tokenAmountToClaim);
} else {
//We only want to apply a fee on redemption of Butter
//Sweethearts are partner addresses that we want to exclude from this fee
if (!sweethearts[_claimFor]) {
//Fee is deducted from threeCrv -- This allows it to work with the Zapper
//Fes are denominated in BasisPoints
uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;
redemptionFee.accumulated += fee;
tokenAmountToClaim = tokenAmountToClaim - fee;
}
threeCrv.safeTransfer(recipient, tokenAmountToClaim);
}
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
return tokenAmountToClaim;
}
/**
* @notice Claims BTR after batch has been processed and stakes it in Staking.sol
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function claimAndStake(bytes32 _batchId, address _claimFor) external {
(address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(
_batchId,
_claimFor
);
emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);
//Transfer token
require(batchType == BatchType.Mint, "Can only stake BTR");
staking.stakeFor(tokenAmountToClaim, recipient);
}
/**
* @notice Moves unclaimed token (3crv or butter) from their respective Batches into a new redeemBatch / mintBatch without needing to claim them first. This will typically be used when butter has already been minted and a user has never claimed / transfered the token to their address and they would like to convert it to stablecoin.
* @param _batchIds the ids of each batch where butter should be moved from
* @param _shares how many shares should redeemed in each of the batches
* @param _batchType the batchType where funds should be taken from (Mint -> Take Hysi and redeem then, Redeem -> Take 3Crv and Mint Butter)
* @dev the indices of batchIds must match the amountsInHysi to work properly (This will be done by the frontend)
*/
function moveUnclaimedDepositsIntoCurrentBatch(
bytes32[] calldata _batchIds,
uint256[] calldata _shares,
BatchType _batchType
) external whenNotPaused {
require(_batchIds.length == _shares.length, "array lengths must match");
uint256 totalAmount;
for (uint256 i; i < _batchIds.length; i++) {
Batch storage batch = batches[_batchIds[i]];
uint256 accountBalance = accountBalances[batch.batchId][msg.sender];
//Check that the user has enough funds and that the batch was already minted
//Only the current redeemBatch is claimable == false so this check allows us to not adjust batch.suppliedTokenBalance
//Additionally it makes no sense to move funds from the current redeemBatch to the current redeemBatch
require(batch.claimable == true, "has not yet been processed");
require(batch.batchType == _batchType, "incorrect batchType");
require(accountBalance >= _shares[i], "account has insufficient funds");
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * _shares[i]) / batch.unclaimedShares;
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - _shares[i];
accountBalances[batch.batchId][msg.sender] = accountBalance - _shares[i];
totalAmount = totalAmount + tokenAmountToClaim;
}
require(totalAmount > 0, "totalAmount must be larger 0");
if (BatchType.Mint == _batchType) {
_deposit(totalAmount, currentRedeemBatchId, msg.sender);
}
if (BatchType.Redeem == _batchType) {
_deposit(totalAmount, currentMintBatchId, msg.sender);
}
emit MovedUnclaimedDepositsIntoCurrentBatch(totalAmount, _batchType, msg.sender);
}
/**
* @notice Mint Butter token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of Butter
* @dev This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint Butter
* @dev This process leaves some leftovers which are partially used in the next mint batches.
* @dev In order to get 3CRV we can implement a zap to move stables into the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchMint() external whenNotPaused keeperIncentive(contractName, 0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastMintedAt) >= processingThreshold.batchCooldown ||
(batch.suppliedTokenBalance >= processingThreshold.mintThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch mint yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantities of yToken needed to mint 1 BTR (This should be an equal amount per Token)
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, 1e18);
//The value of 1 BTR in virtual Price (`quantities` * `virtualPrice`)
uint256 setValue = valueOfComponents(tokenAddresses, quantities);
uint256 threeCrvValue = threePool.get_virtual_price();
//Remaining amount of 3CRV in this batch which hasnt been allocated yet
uint256 remainingBatchBalanceValue = (batch.suppliedTokenBalance * threeCrvValue) / 1e18;
//Temporary allocation of 3CRV to be deployed in curveMetapools
uint256[] memory poolAllocations = new uint256[](quantities.length);
//Ratio of 3CRV needed to mint 1 BTR
uint256[] memory ratios = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
// prettier-ignore
(uint256 allocation, uint256 ratio) = _getPoolAllocationAndRatio(tokenAddresses[i], quantities[i], batch, setValue, threeCrvValue);
poolAllocations[i] = allocation;
ratios[i] = ratio;
remainingBatchBalanceValue -= allocation;
}
for (uint256 i; i < tokenAddresses.length; i++) {
uint256 poolAllocation;
//RemainingLeftovers should only be 0 if there were no yToken leftover from previous batches
//since the first iteration of poolAllocation uses all 3CRV. Therefore we can only have `remainingBatchBalanceValue` from subtracted leftovers
if (remainingBatchBalanceValue > 0) {
poolAllocation = _getPoolAllocation(remainingBatchBalanceValue, ratios[i]);
}
//Pool 3CRV to get crvLPToken
_sendToCurve(
((poolAllocation + poolAllocations[i]) * 1e18) / threeCrvValue,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this)),
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of butter that we can mint with our balances of yToken
uint256 butterAmount = (YearnVault(tokenAddresses[0]).balanceOf(address(this)) * 1e18) / quantities[0];
for (uint256 i = 1; i < tokenAddresses.length; i++) {
butterAmount = Math.min(
butterAmount,
(YearnVault(tokenAddresses[i]).balanceOf(address(this)) * 1e18) / quantities[i]
);
}
require(
butterAmount >=
getMinAmountToMint((batch.suppliedTokenBalance * threeCrvValue) / 1e18, setValue, slippage.mintBps),
"slippage too high"
);
//Mint Butter
setBasicIssuanceModule.issue(setToken, butterAmount, address(this));
//Save the minted amount Butter as claimable token for the batch
batch.claimableTokenBalance = butterAmount;
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(currentMintBatchId, batch.suppliedTokenBalance, butterAmount);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
/**
* @notice Redeems Butter for 3CRV. This function goes through all the steps necessary to get 3CRV
* @dev This function reedeems Butter for the underlying yToken and deposits these yToken in curve Metapools for 3CRV
* @dev In order to get stablecoins from 3CRV we can use a zap to redeem 3CRV for stables in the curve tri-pool
* @dev handleKeeperIncentive checks if the msg.sender is a permissioned keeper and pays them a reward for calling this function (see KeeperIncentive.sol)
*/
function batchRedeem() external whenNotPaused keeperIncentive(contractName, 1) {
Batch storage batch = batches[currentRedeemBatchId];
//Check if there was enough time between the last batch redemption and this attempt...
//...or if enough Butter was deposited to make the redemption worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
((block.timestamp - lastRedeemedAt >= processingThreshold.batchCooldown) ||
(batch.suppliedTokenBalance >= processingThreshold.redeemThreshold)) && batch.suppliedTokenBalance > 0,
"can not execute batch redeem yet"
);
//Check if the Batch got already processed
require(batch.claimable == false, "already redeemed");
//Get tokenAddresses for mapping of underlying
(address[] memory tokenAddresses, uint256[] memory quantities) = setBasicIssuanceModule
.getRequiredComponentUnitsForIssue(setToken, batch.suppliedTokenBalance);
//Allow setBasicIssuanceModule to use Butter
_setBasicIssuanceModuleAllowance(batch.suppliedTokenBalance);
//Redeem Butter for yToken
setBasicIssuanceModule.redeem(setToken, batch.suppliedTokenBalance, address(this));
//Check our balance of 3CRV since we could have some still around from previous batches
uint256 oldBalance = threeCrv.balanceOf(address(this));
for (uint256 i; i < tokenAddresses.length; i++) {
//Deposit yToken to receive crvLPToken
_withdrawFromYearn(YearnVault(tokenAddresses[i]).balanceOf(address(this)), YearnVault(tokenAddresses[i]));
uint256 crvLPTokenBalance = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(address(this));
//Deposit crvLPToken to receive 3CRV
_withdrawFromCurve(crvLPTokenBalance, curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool);
}
//Save the redeemed amount of 3CRV as claimable token for the batch
batch.claimableTokenBalance = threeCrv.balanceOf(address(this)) - oldBalance;
require(
batch.claimableTokenBalance >=
getMinAmount3CrvFromRedeem(valueOfComponents(tokenAddresses, quantities), slippage.redeemBps),
"slippage too high"
);
emit BatchRedeemed(currentRedeemBatchId, batch.suppliedTokenBalance, batch.claimableTokenBalance);
//Set claimable to true so users can claim their Butter
batch.claimable = true;
//Update lastRedeemedAt for cooldown calculations
lastRedeemedAt = block.timestamp;
//Create the next redeem batch id
_generateNextBatch(currentRedeemBatchId, BatchType.Redeem);
}
/**
* @notice sets approval for contracts that require access to assets held by this contract
*/
function setApprovals() external {
(address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);
for (uint256 i; i < tokenAddresses.length; i++) {
IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;
CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;
YearnVault yearnVault = YearnVault(tokenAddresses[i]);
_maxApprove(curveLpToken, address(curveMetapool));
_maxApprove(curveLpToken, address(yearnVault));
_maxApprove(threeCrv, address(curveMetapool));
}
_maxApprove(IERC20(address(setToken)), address(staking));
}
/**
* @notice returns the min amount of butter that should be minted given an amount of 3crv
* @dev this controls slippage in the minting process
*/
function getMinAmountToMint(
uint256 _valueOfBatch,
uint256 _valueOfComponentsPerUnit,
uint256 _slippage
) public pure returns (uint256) {
uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;
uint256 _delta = (_mintAmount * _slippage) / 10_000;
return _mintAmount - _delta;
}
/**
* @notice returns the min amount of 3crv that should be redeemed given an amount of butter
* @dev this controls slippage in the redeeming process
*/
function getMinAmount3CrvFromRedeem(uint256 _valueOfComponents, uint256 _slippage) public view returns (uint256) {
uint256 _threeCrvToReceive = (_valueOfComponents * 1e18) / threePool.get_virtual_price();
uint256 _delta = (_threeCrvToReceive * _slippage) / 10_000;
return _threeCrvToReceive - _delta;
}
/**
* @notice returns the value of butter in virtualPrice
*/
function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)
public
view
returns (uint256)
{
uint256 value;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
value +=
(((YearnVault(_tokenAddresses[i]).pricePerShare() *
curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /
1e18;
}
return value;
}
/**
* @notice returns the value of an amount of 3crv in virtualPrice
*/
function valueOf3Crv(uint256 _units) public view returns (uint256) {
return (_units * threePool.get_virtual_price()) / 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice sets max allowance given a token and a spender
* @param _token the token which gets approved to be spend
* @param _spender the spender which gets a max allowance to spend `_token`
*/
function _maxApprove(IERC20 _token, address _spender) internal {
_token.safeApprove(_spender, 0);
_token.safeApprove(_spender, type(uint256).max);
}
function _getPoolAllocationAndRatio(
address _component,
uint256 _quantity,
Batch memory _batch,
uint256 _setValue,
uint256 _threePoolPrice
) internal view returns (uint256 poolAllocation, uint256 ratio) {
//Calculate the virtualPrice of one yToken
uint256 componentValuePerShare = (YearnVault(_component).pricePerShare() *
curvePoolTokenPairs[_component].curveMetaPool.get_virtual_price()) / 1e18;
//Calculate the value of quantity (of yToken) in virtualPrice
uint256 componentValuePerSet = (_quantity * componentValuePerShare) / 1e18;
//Calculate the value of leftover yToken in virtualPrice
uint256 componentValueHeldByContract = (YearnVault(_component).balanceOf(address(this)) * componentValuePerShare) /
1e18;
ratio = (componentValuePerSet * 1e18) / _setValue;
poolAllocation =
_getPoolAllocation((_batch.suppliedTokenBalance * _threePoolPrice) / 1e18, ratio) -
componentValueHeldByContract;
return (poolAllocation, ratio);
}
/**
* @notice returns the amount of 3CRV that should be allocated for a curveMetapool
* @param _balance the max amount of 3CRV that is available in this iteration
* @param _ratio the ratio of 3CRV needed to get enough yToken to mint butter
*/
function _getPoolAllocation(uint256 _balance, uint256 _ratio) internal pure returns (uint256) {
return ((_balance * _ratio) / 1e18);
}
/**
* @notice sets allowance for basic issuance module
* @param _amount amount to approve
*/
function _setBasicIssuanceModuleAllowance(uint256 _amount) internal {
setToken.safeApprove(address(setBasicIssuanceModule), 0);
setToken.safeApprove(address(setBasicIssuanceModule), _amount);
}
/**
* @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token
* @param _account is the address which gets withdrawn from
* @dev returns recipient of the withdrawn funds
* @dev By default a user should set _account to their address
* @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user
*/
function _getRecipient(address _account) internal view returns (address) {
//Make sure that only zapper can withdraw from someone else
require(_hasRole(keccak256("ButterZapper"), msg.sender) || msg.sender == _account, "you cant transfer other funds");
//Set recipient per default to _account
address recipient = _account;
//set the recipient to zapper if its called by the zapper
if (_hasRole(keccak256("ButterZapper"), msg.sender)) {
recipient = msg.sender;
}
return recipient;
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
* @param _batchType BatchType of the newly created id
*/
function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {
bytes32 id = _generateNextBatchId(_currentBatchId);
batchIds.push(id);
Batch storage batch = batches[id];
batch.batchType = _batchType;
batch.batchId = id;
if (BatchType.Mint == _batchType) {
currentMintBatchId = id;
batch.suppliedTokenAddress = address(threeCrv);
batch.claimableTokenAddress = address(setToken);
}
if (BatchType.Redeem == _batchType) {
currentRedeemBatchId = id;
batch.suppliedTokenAddress = address(setToken);
batch.claimableTokenAddress = address(threeCrv);
}
return id;
}
/**
* @notice Deposit either Butter or 3CRV in their respective batches
* @param _amount The amount of 3CRV or Butter a user is depositing
* @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed
* @param _depositFor User that gets the shares attributed to (for use in zapper contract)
* @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication
*/
function _deposit(
uint256 _amount,
bytes32 _currentBatchId,
address _depositFor
) internal {
Batch storage batch = batches[_currentBatchId];
//Add the new funds to the batch
batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;
batch.unclaimedShares = batch.unclaimedShares + _amount;
accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;
//Save the batchId for the user so they can be retrieved to claim the batch
if (
accountBatches[_depositFor].length == 0 ||
accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId
) {
accountBatches[_depositFor].push(_currentBatchId);
}
emit Deposit(_depositFor, _amount);
}
/**
* @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens
* @param _batchId Id of batch to claim from
* @param _claimFor User that gets the shares attributed to (for use in zapper contract)
*/
function _prepareClaim(bytes32 _batchId, address _claimFor)
internal
returns (
address,
BatchType,
uint256,
uint256
)
{
Batch storage batch = batches[_batchId];
require(batch.claimable, "not yet claimable");
address recipient = _getRecipient(_claimFor);
uint256 accountBalance = accountBalances[_batchId][_claimFor];
require(accountBalance <= batch.unclaimedShares, "claiming too many shares");
//Calculate how many token will be claimed
uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;
//Subtract the claimed token from the batch
batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;
batch.unclaimedShares = batch.unclaimedShares - accountBalance;
accountBalances[_batchId][_claimFor] = 0;
return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);
}
/**
* @notice Deposit 3CRV in a curve metapool for its LP-Token
* @param _amount The amount of 3CRV that gets deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes 3CRV and sends lpToken to this contract
//Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.
//The second variable determines the min amount of LP-Token we want to receive (slippage control)
_curveMetapool.add_liquidity([0, _amount], 0);
}
/**
* @notice Withdraws 3CRV for deposited crvLPToken
* @param _amount The amount of crvLPToken that get deposited
* @param _curveMetapool The metapool where we want to provide liquidity
*/
function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {
//Takes lp Token and sends 3CRV to this contract
//The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)
//The third variable determines min amount of token we want to receive (slippage control)
_curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);
}
/**
* @notice Deposits crvLPToken for yToken
* @param _amount The amount of crvLPToken that get deposited
* @param _yearnVault The yearn Vault in which we deposit
*/
function _sendToYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Mints yToken and sends them to msg.sender (this contract)
_yearnVault.deposit(_amount);
}
/**
* @notice Withdraw crvLPToken from yearn
* @param _amount The amount of crvLPToken which we deposit
* @param _yearnVault The yearn Vault in which we deposit
*/
function _withdrawFromYearn(uint256 _amount, YearnVault _yearnVault) internal {
//Takes yToken and sends crvLPToken to this contract
_yearnVault.withdraw(_amount);
}
/**
* @notice Generates the next batch id for new deposits
* @param _currentBatchId takes the current mint or redeem batch id
*/
function _generateNextBatchId(bytes32 _currentBatchId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.timestamp, _currentBatchId));
}
/* ========== ADMIN ========== */
/**
* @notice This function allows the owner to change the composition of underlying token of the Butter
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
*/
function setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] calldata _curvePoolTokenPairs)
public
onlyRole(DAO_ROLE)
{
_setCurvePoolTokenPairs(_yTokenAddresses, _curvePoolTokenPairs);
}
/**
* @notice This function defines which underlying token and pools are needed to mint a butter token
* @param _yTokenAddresses An array of addresses for the yToken needed to mint Butter
* @param _curvePoolTokenPairs An array structs describing underlying yToken, crvToken and curve metapool
* @dev since our calculations for minting just iterate through the index and match it with the quantities given by Set
* @dev we must make sure to align them correctly by index, otherwise our whole calculation breaks down
*/
function _setCurvePoolTokenPairs(address[] memory _yTokenAddresses, CurvePoolTokenPair[] memory _curvePoolTokenPairs)
internal
{
emit CurveTokenPairsUpdated(_yTokenAddresses, _curvePoolTokenPairs);
for (uint256 i; i < _yTokenAddresses.length; i++) {
curvePoolTokenPairs[_yTokenAddresses[i]] = _curvePoolTokenPairs[i];
}
}
/**
* @notice Changes the the ProcessingThreshold
* @param _cooldown Cooldown in seconds
* @param _mintThreshold Amount of MIM necessary to mint immediately
* @param _redeemThreshold Amount of Butter necessary to mint immediately
* @dev The cooldown is the same for redeem and mint batches
*/
function setProcessingThreshold(
uint256 _cooldown,
uint256 _mintThreshold,
uint256 _redeemThreshold
) public onlyRole(DAO_ROLE) {
ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({
batchCooldown: _cooldown,
mintThreshold: _mintThreshold,
redeemThreshold: _redeemThreshold
});
emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);
processingThreshold = newProcessingThreshold;
}
/**
* @notice sets slippage for mint and redeem
* @param _mintSlippage amount in bps (e.g. 50 = 0.5%)
* @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)
*/
function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {
require(_mintSlippage <= 200 && _redeemSlippage <= 200, "slippage too high");
Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });
emit SlippageUpdated(slippage, newSlippage);
slippage = newSlippage;
}
/**
* @notice Changes the redemption fee rate and the fee recipient
* @param _feeRate Redemption fee rate in basis points
* @param _recipient The recipient which receives these fees (Should be DAO treasury)
* @dev Per default both of these values are not set. Therefore a fee has to be explicitly be set with this function
*/
function setRedemptionFee(uint256 _feeRate, address _recipient) external onlyRole(DAO_ROLE) {
require(_feeRate <= 100, "dont get greedy");
redemptionFee.rate = _feeRate;
redemptionFee.recipient = _recipient;
emit RedemptionFeeUpdated(_feeRate, _recipient);
}
/**
* @notice Claims all accumulated redemption fees in 3CRV
*/
function claimRedemptionFee() external {
threeCrv.safeTransfer(redemptionFee.recipient, redemptionFee.accumulated);
redemptionFee.accumulated = 0;
}
/**
* @notice Allows the DAO to recover leftover yToken that have accumulated between pages and cant be used effectively in upcoming batches
* @dev This should only be used if there is a clear trend that a certain amount of yToken leftover wont be used in the minting process
* @param _yTokenAddress address of the yToken that should be recovered
* @param _amount amount of yToken that should recovered
*/
function recoverLeftover(address _yTokenAddress, uint256 _amount) external onlyRole(DAO_ROLE) {
require(address(curvePoolTokenPairs[_yTokenAddress].curveMetaPool) != address(0), "yToken doesnt exist");
IERC20(_yTokenAddress).safeTransfer(_getContract(keccak256("Treasury")), _amount);
}
/**
* @notice Toggles an address as Sweetheart (partner addresses that don't pay a redemption fee)
* @param _sweetheart The address that shall become/lose their sweetheart status
*/
function updateSweetheart(address _sweetheart, bool _enabled) external onlyRole(DAO_ROLE) {
sweethearts[_sweetheart] = _enabled;
emit SweetheartUpdated(_sweetheart, _enabled);
}
/**
* @notice Pauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function pause() external onlyRole(DAO_ROLE) {
_pause();
}
/**
* @notice Unpauses the contract.
* @dev All function with the modifer `whenNotPaused` cant be called anymore. Namly deposits and mint/redeem
*/
function unpause() external onlyRole(DAO_ROLE) {
_unpause();
}
/**
* @notice Updates the staking contract
*/
function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
function _getContract(bytes32 _name)
internal
view
override(ACLAuth, KeeperIncentivized, ContractRegistryAccess)
returns (address)
{
return super._getContract(_name);
}
} | /*
* @notice This Contract allows smaller depositors to mint and redeem Butter (formerly known as HYSI) without needing to through all the steps necessary on their own,
* which not only takes long but mainly costs enormous amounts of gas.
* The Butter is created from several different yTokens which in turn need each a deposit of a crvLPToken.
* This means multiple approvals and deposits are necessary to mint one Butter.
* We batch this process and allow users to pool their funds. Then we pay a keeper to mint or redeem Butter regularly.
*/ | Comment | setStaking | function setStaking(address _staking) external onlyRole(DAO_ROLE) {
emit StakingUpdated(address(staking), _staking);
staking = IStaking(_staking);
}
| /**
* @notice Updates the staking contract
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | GNU GPLv3 | {
"func_code_index": [
37278,
37438
]
} | 12,061 |
|
StealthDoge | StealthDoge.sol | 0xdafa1e4e7409e830b71c83c806debf44e48230ab | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | totalSupply | function totalSupply() external view returns (uint256);
| /**
* @dev Returns the amount of tokens in existence.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://95fabf50265d2bb95ba0a78b03d2c8d94252865905f12e87efcd36ba0f7d494f | {
"func_code_index": [
94,
154
]
} | 12,062 |
||
StealthDoge | StealthDoge.sol | 0xdafa1e4e7409e830b71c83c806debf44e48230ab | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | balanceOf | function balanceOf(address account) external view returns (uint256);
| /**
* @dev Returns the amount of tokens owned by `account`.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://95fabf50265d2bb95ba0a78b03d2c8d94252865905f12e87efcd36ba0f7d494f | {
"func_code_index": [
237,
310
]
} | 12,063 |
||
StealthDoge | StealthDoge.sol | 0xdafa1e4e7409e830b71c83c806debf44e48230ab | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | transfer | function transfer(address recipient, uint256 amount) external returns (bool);
| /**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://95fabf50265d2bb95ba0a78b03d2c8d94252865905f12e87efcd36ba0f7d494f | {
"func_code_index": [
534,
616
]
} | 12,064 |
||
StealthDoge | StealthDoge.sol | 0xdafa1e4e7409e830b71c83c806debf44e48230ab | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | allowance | function allowance(address owner, address spender) external view returns (uint256);
| /**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://95fabf50265d2bb95ba0a78b03d2c8d94252865905f12e87efcd36ba0f7d494f | {
"func_code_index": [
895,
983
]
} | 12,065 |
||
StealthDoge | StealthDoge.sol | 0xdafa1e4e7409e830b71c83c806debf44e48230ab | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | approve | function approve(address spender, uint256 amount) external returns (bool);
| /**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://95fabf50265d2bb95ba0a78b03d2c8d94252865905f12e87efcd36ba0f7d494f | {
"func_code_index": [
1647,
1726
]
} | 12,066 |
||
StealthDoge | StealthDoge.sol | 0xdafa1e4e7409e830b71c83c806debf44e48230ab | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | transferFrom | function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
| /**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://95fabf50265d2bb95ba0a78b03d2c8d94252865905f12e87efcd36ba0f7d494f | {
"func_code_index": [
2039,
2141
]
} | 12,067 |
||
StealthDoge | StealthDoge.sol | 0xdafa1e4e7409e830b71c83c806debf44e48230ab | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | add | function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
| /**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://95fabf50265d2bb95ba0a78b03d2c8d94252865905f12e87efcd36ba0f7d494f | {
"func_code_index": [
259,
445
]
} | 12,068 |
||
StealthDoge | StealthDoge.sol | 0xdafa1e4e7409e830b71c83c806debf44e48230ab | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | sub | function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
| /**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://95fabf50265d2bb95ba0a78b03d2c8d94252865905f12e87efcd36ba0f7d494f | {
"func_code_index": [
723,
864
]
} | 12,069 |
||
StealthDoge | StealthDoge.sol | 0xdafa1e4e7409e830b71c83c806debf44e48230ab | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | sub | function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
| /**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://95fabf50265d2bb95ba0a78b03d2c8d94252865905f12e87efcd36ba0f7d494f | {
"func_code_index": [
1162,
1359
]
} | 12,070 |
||
StealthDoge | StealthDoge.sol | 0xdafa1e4e7409e830b71c83c806debf44e48230ab | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | mul | function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
| /**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://95fabf50265d2bb95ba0a78b03d2c8d94252865905f12e87efcd36ba0f7d494f | {
"func_code_index": [
1613,
2089
]
} | 12,071 |
||
StealthDoge | StealthDoge.sol | 0xdafa1e4e7409e830b71c83c806debf44e48230ab | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | div | function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
| /**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://95fabf50265d2bb95ba0a78b03d2c8d94252865905f12e87efcd36ba0f7d494f | {
"func_code_index": [
2560,
2697
]
} | 12,072 |
||
StealthDoge | StealthDoge.sol | 0xdafa1e4e7409e830b71c83c806debf44e48230ab | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | div | function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
| /**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://95fabf50265d2bb95ba0a78b03d2c8d94252865905f12e87efcd36ba0f7d494f | {
"func_code_index": [
3188,
3471
]
} | 12,073 |
||
StealthDoge | StealthDoge.sol | 0xdafa1e4e7409e830b71c83c806debf44e48230ab | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | mod | function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
| /**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://95fabf50265d2bb95ba0a78b03d2c8d94252865905f12e87efcd36ba0f7d494f | {
"func_code_index": [
3931,
4066
]
} | 12,074 |
||
StealthDoge | StealthDoge.sol | 0xdafa1e4e7409e830b71c83c806debf44e48230ab | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | mod | function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
| /**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://95fabf50265d2bb95ba0a78b03d2c8d94252865905f12e87efcd36ba0f7d494f | {
"func_code_index": [
4546,
4717
]
} | 12,075 |
||
StealthDoge | StealthDoge.sol | 0xdafa1e4e7409e830b71c83c806debf44e48230ab | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | isContract | function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
| /**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://95fabf50265d2bb95ba0a78b03d2c8d94252865905f12e87efcd36ba0f7d494f | {
"func_code_index": [
606,
1230
]
} | 12,076 |
||
StealthDoge | StealthDoge.sol | 0xdafa1e4e7409e830b71c83c806debf44e48230ab | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | sendValue | function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
| /**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://95fabf50265d2bb95ba0a78b03d2c8d94252865905f12e87efcd36ba0f7d494f | {
"func_code_index": [
2160,
2562
]
} | 12,077 |
||
StealthDoge | StealthDoge.sol | 0xdafa1e4e7409e830b71c83c806debf44e48230ab | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | functionCall | function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
| /**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://95fabf50265d2bb95ba0a78b03d2c8d94252865905f12e87efcd36ba0f7d494f | {
"func_code_index": [
3318,
3496
]
} | 12,078 |
||
StealthDoge | StealthDoge.sol | 0xdafa1e4e7409e830b71c83c806debf44e48230ab | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | functionCall | function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://95fabf50265d2bb95ba0a78b03d2c8d94252865905f12e87efcd36ba0f7d494f | {
"func_code_index": [
3721,
3922
]
} | 12,079 |
||
StealthDoge | StealthDoge.sol | 0xdafa1e4e7409e830b71c83c806debf44e48230ab | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | functionCallWithValue | function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://95fabf50265d2bb95ba0a78b03d2c8d94252865905f12e87efcd36ba0f7d494f | {
"func_code_index": [
4292,
4523
]
} | 12,080 |
||
StealthDoge | StealthDoge.sol | 0xdafa1e4e7409e830b71c83c806debf44e48230ab | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | functionCallWithValue | function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
| /**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://95fabf50265d2bb95ba0a78b03d2c8d94252865905f12e87efcd36ba0f7d494f | {
"func_code_index": [
4774,
5095
]
} | 12,081 |
||
StealthDoge | StealthDoge.sol | 0xdafa1e4e7409e830b71c83c806debf44e48230ab | Solidity | Ownable | contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | owner | function owner() public view returns (address) {
return _owner;
}
| /**
* @dev Returns the address of the current owner.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://95fabf50265d2bb95ba0a78b03d2c8d94252865905f12e87efcd36ba0f7d494f | {
"func_code_index": [
488,
572
]
} | 12,082 |
||
StealthDoge | StealthDoge.sol | 0xdafa1e4e7409e830b71c83c806debf44e48230ab | Solidity | Ownable | contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | renounceOwnership | function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
| /**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://95fabf50265d2bb95ba0a78b03d2c8d94252865905f12e87efcd36ba0f7d494f | {
"func_code_index": [
1130,
1283
]
} | 12,083 |
||
StealthDoge | StealthDoge.sol | 0xdafa1e4e7409e830b71c83c806debf44e48230ab | Solidity | Ownable | contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | transferOwnership | function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
| /**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://95fabf50265d2bb95ba0a78b03d2c8d94252865905f12e87efcd36ba0f7d494f | {
"func_code_index": [
1433,
1682
]
} | 12,084 |
||
GasTokenSwitcherV2 | GasTokenSwitcherV2.sol | 0xa311b14b2cf14f7988762185b5b3a0e3bea35eef | Solidity | GasTokenSwitcherV2 | contract GasTokenSwitcherV2 is Whitelist(tx.origin) {
receive() external payable {
}
//transfers ETH from this contract
function transferETH(address payable dest, uint256 amount) external onlyWhitelist() {
dest.transfer(amount);
}
//transfers ERC20 from this contract
function transferERC20(address tokenAddress, uint256 amountTokens, address dest) external onlyWhitelist() {
IERC20(tokenAddress).transfer(dest, amountTokens);
}
modifier discountGasToken(address burnToken) {
uint256 gasStart = gasleft();
_;
uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length;
GasToken(burnToken).freeUpTo((gasSpent + 14154) / 41130);
}
function mintAndBurn(address burnToken, address mintToken, uint256 newTokens)
external onlyWhitelist() discountGasToken(burnToken) {
GasToken(mintToken).mint(newTokens);
}
function burnMintSellChi(address burnToken, uint256 newTokens)
external onlyWhitelist() discountGasToken(burnToken) {
//mint CHI
GasToken(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c).mint(newTokens);
//CHI is token0 for the UniV2 ETH-CHI pool at 0xa6f3ef841d371a82ca757FaD08efc0DeE2F1f5e2
//emulate UniV2 getAmountOut functionality
(uint reserve0, uint reserve1,) = IUniswapV2Pair(0xa6f3ef841d371a82ca757FaD08efc0DeE2F1f5e2).getReserves();
uint amountInWithFee = (newTokens * 997);
uint numerator = (amountInWithFee * reserve1);
uint denominator = (reserve0 * 1000) + amountInWithFee;
uint amountOut = numerator / denominator;
//transfer new CHI to UniV2 pool
IERC20(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c).transfer(0xa6f3ef841d371a82ca757FaD08efc0DeE2F1f5e2, newTokens);
//get the appropriate amount out in WETH
IUniswapV2Pair(0xa6f3ef841d371a82ca757FaD08efc0DeE2F1f5e2).swap(newTokens, amountOut, address(this), new bytes(0));
//withdraw the WETH -- UniV2 uses WETH at 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).withdraw(amountOut);
}
function burnAndDeploy(address burnToken, bytes memory data)
external onlyWhitelist() discountGasToken(burnToken) returns(address contractAddress) {
assembly {
contractAddress := create(0, add(data, 32), mload(data))
}
}
function sendBatchedTransaction (address[] calldata dest, uint256[] calldata eth, bytes[] calldata hexData)
external onlyWhitelist() {
require(dest.length == eth.length && dest.length == hexData.length, "unequal input lengths");
for(uint256 i = 0; i < hexData.length; i++) {
(bool success,) = dest[i].call{value:eth[i]}(hexData[i]);
if (!success) revert("internal call failed");
}
}
function discountBatchedTransaction (address burnToken, address[] calldata dest, uint256[] calldata eth, bytes[] calldata hexData)
external onlyWhitelist() discountGasToken(burnToken) {
require(dest.length == eth.length && dest.length == hexData.length, "unequal input lengths");
for(uint256 i = 0; i < hexData.length; i++) {
(bool success,) = dest[i].call{value:eth[i]}(hexData[i]);
if (!success) revert("internal call failed");
}
}
} | transferETH | function transferETH(address payable dest, uint256 amount) external onlyWhitelist() {
dest.transfer(amount);
}
| //transfers ETH from this contract | LineComment | v0.8.1+commit.df193b15 | Unknown | ipfs://7f177d84bb46f917062c3750b79fecca1c3da51f4dc206e85fc1e5b43428ce32 | {
"func_code_index": [
140,
269
]
} | 12,085 |
||
GasTokenSwitcherV2 | GasTokenSwitcherV2.sol | 0xa311b14b2cf14f7988762185b5b3a0e3bea35eef | Solidity | GasTokenSwitcherV2 | contract GasTokenSwitcherV2 is Whitelist(tx.origin) {
receive() external payable {
}
//transfers ETH from this contract
function transferETH(address payable dest, uint256 amount) external onlyWhitelist() {
dest.transfer(amount);
}
//transfers ERC20 from this contract
function transferERC20(address tokenAddress, uint256 amountTokens, address dest) external onlyWhitelist() {
IERC20(tokenAddress).transfer(dest, amountTokens);
}
modifier discountGasToken(address burnToken) {
uint256 gasStart = gasleft();
_;
uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length;
GasToken(burnToken).freeUpTo((gasSpent + 14154) / 41130);
}
function mintAndBurn(address burnToken, address mintToken, uint256 newTokens)
external onlyWhitelist() discountGasToken(burnToken) {
GasToken(mintToken).mint(newTokens);
}
function burnMintSellChi(address burnToken, uint256 newTokens)
external onlyWhitelist() discountGasToken(burnToken) {
//mint CHI
GasToken(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c).mint(newTokens);
//CHI is token0 for the UniV2 ETH-CHI pool at 0xa6f3ef841d371a82ca757FaD08efc0DeE2F1f5e2
//emulate UniV2 getAmountOut functionality
(uint reserve0, uint reserve1,) = IUniswapV2Pair(0xa6f3ef841d371a82ca757FaD08efc0DeE2F1f5e2).getReserves();
uint amountInWithFee = (newTokens * 997);
uint numerator = (amountInWithFee * reserve1);
uint denominator = (reserve0 * 1000) + amountInWithFee;
uint amountOut = numerator / denominator;
//transfer new CHI to UniV2 pool
IERC20(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c).transfer(0xa6f3ef841d371a82ca757FaD08efc0DeE2F1f5e2, newTokens);
//get the appropriate amount out in WETH
IUniswapV2Pair(0xa6f3ef841d371a82ca757FaD08efc0DeE2F1f5e2).swap(newTokens, amountOut, address(this), new bytes(0));
//withdraw the WETH -- UniV2 uses WETH at 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).withdraw(amountOut);
}
function burnAndDeploy(address burnToken, bytes memory data)
external onlyWhitelist() discountGasToken(burnToken) returns(address contractAddress) {
assembly {
contractAddress := create(0, add(data, 32), mload(data))
}
}
function sendBatchedTransaction (address[] calldata dest, uint256[] calldata eth, bytes[] calldata hexData)
external onlyWhitelist() {
require(dest.length == eth.length && dest.length == hexData.length, "unequal input lengths");
for(uint256 i = 0; i < hexData.length; i++) {
(bool success,) = dest[i].call{value:eth[i]}(hexData[i]);
if (!success) revert("internal call failed");
}
}
function discountBatchedTransaction (address burnToken, address[] calldata dest, uint256[] calldata eth, bytes[] calldata hexData)
external onlyWhitelist() discountGasToken(burnToken) {
require(dest.length == eth.length && dest.length == hexData.length, "unequal input lengths");
for(uint256 i = 0; i < hexData.length; i++) {
(bool success,) = dest[i].call{value:eth[i]}(hexData[i]);
if (!success) revert("internal call failed");
}
}
} | transferERC20 | function transferERC20(address tokenAddress, uint256 amountTokens, address dest) external onlyWhitelist() {
IERC20(tokenAddress).transfer(dest, amountTokens);
}
| //transfers ERC20 from this contract | LineComment | v0.8.1+commit.df193b15 | Unknown | ipfs://7f177d84bb46f917062c3750b79fecca1c3da51f4dc206e85fc1e5b43428ce32 | {
"func_code_index": [
314,
493
]
} | 12,086 |
||
SkrumbleCandyToken | SkrumbleCandyToken.sol | 0x55d260f12a6627a11aa10256f00cfacc48994aa8 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | mul | function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
| /**
* @dev Multiplies two numbers, throws on overflow.
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://24e639f9833c8209b754bbd6a3b1ce87b9803b9becd8fc0a75b1a7929adcc1d2 | {
"func_code_index": [
95,
308
]
} | 12,087 |
|
SkrumbleCandyToken | SkrumbleCandyToken.sol | 0x55d260f12a6627a11aa10256f00cfacc48994aa8 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | div | function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
| /**
* @dev Integer division of two numbers, truncating the quotient.
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://24e639f9833c8209b754bbd6a3b1ce87b9803b9becd8fc0a75b1a7929adcc1d2 | {
"func_code_index": [
398,
691
]
} | 12,088 |
|
SkrumbleCandyToken | SkrumbleCandyToken.sol | 0x55d260f12a6627a11aa10256f00cfacc48994aa8 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | sub | function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
| /**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://24e639f9833c8209b754bbd6a3b1ce87b9803b9becd8fc0a75b1a7929adcc1d2 | {
"func_code_index": [
811,
939
]
} | 12,089 |
|
SkrumbleCandyToken | SkrumbleCandyToken.sol | 0x55d260f12a6627a11aa10256f00cfacc48994aa8 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | add | function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
| /**
* @dev Adds two numbers, throws on overflow.
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://24e639f9833c8209b754bbd6a3b1ce87b9803b9becd8fc0a75b1a7929adcc1d2 | {
"func_code_index": [
1009,
1161
]
} | 12,090 |
|
SkrumbleCandyToken | SkrumbleCandyToken.sol | 0x55d260f12a6627a11aa10256f00cfacc48994aa8 | Solidity | BasicToken | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
} | /**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/ | NatSpecMultiLine | totalSupply | function totalSupply() public view returns (uint256) {
return totalSupply_;
}
| /**
* @dev total number of tokens in existence
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://24e639f9833c8209b754bbd6a3b1ce87b9803b9becd8fc0a75b1a7929adcc1d2 | {
"func_code_index": [
211,
307
]
} | 12,091 |
|
SkrumbleCandyToken | SkrumbleCandyToken.sol | 0x55d260f12a6627a11aa10256f00cfacc48994aa8 | Solidity | BasicToken | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
} | /**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/ | NatSpecMultiLine | transfer | function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
| /**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://24e639f9833c8209b754bbd6a3b1ce87b9803b9becd8fc0a75b1a7929adcc1d2 | {
"func_code_index": [
475,
898
]
} | 12,092 |
|
SkrumbleCandyToken | SkrumbleCandyToken.sol | 0x55d260f12a6627a11aa10256f00cfacc48994aa8 | Solidity | BasicToken | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
} | /**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/ | NatSpecMultiLine | balanceOf | function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
| /**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://24e639f9833c8209b754bbd6a3b1ce87b9803b9becd8fc0a75b1a7929adcc1d2 | {
"func_code_index": [
1114,
1234
]
} | 12,093 |
|
SkrumbleCandyToken | SkrumbleCandyToken.sol | 0x55d260f12a6627a11aa10256f00cfacc48994aa8 | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | transferFrom | function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
| /**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://24e639f9833c8209b754bbd6a3b1ce87b9803b9becd8fc0a75b1a7929adcc1d2 | {
"func_code_index": [
410,
898
]
} | 12,094 |
|
SkrumbleCandyToken | SkrumbleCandyToken.sol | 0x55d260f12a6627a11aa10256f00cfacc48994aa8 | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | approve | function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
| /**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://24e639f9833c8209b754bbd6a3b1ce87b9803b9becd8fc0a75b1a7929adcc1d2 | {
"func_code_index": [
1541,
1747
]
} | 12,095 |
|
SkrumbleCandyToken | SkrumbleCandyToken.sol | 0x55d260f12a6627a11aa10256f00cfacc48994aa8 | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | allowance | function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
| /**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://24e639f9833c8209b754bbd6a3b1ce87b9803b9becd8fc0a75b1a7929adcc1d2 | {
"func_code_index": [
2078,
2217
]
} | 12,096 |
|
SkrumbleCandyToken | SkrumbleCandyToken.sol | 0x55d260f12a6627a11aa10256f00cfacc48994aa8 | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | increaseApproval | function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
| /**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://24e639f9833c8209b754bbd6a3b1ce87b9803b9becd8fc0a75b1a7929adcc1d2 | {
"func_code_index": [
2694,
2974
]
} | 12,097 |
|
SkrumbleCandyToken | SkrumbleCandyToken.sol | 0x55d260f12a6627a11aa10256f00cfacc48994aa8 | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | decreaseApproval | function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
| /**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://24e639f9833c8209b754bbd6a3b1ce87b9803b9becd8fc0a75b1a7929adcc1d2 | {
"func_code_index": [
3456,
3906
]
} | 12,098 |
|
SkrumbleCandyToken | SkrumbleCandyToken.sol | 0x55d260f12a6627a11aa10256f00cfacc48994aa8 | Solidity | SkrumbleCandyToken | contract SkrumbleCandyToken is StandardToken {
string public name = "Skrumble Candy Token";
string public symbol = "SKM-CDY";
uint8 public decimals = 18;
/**
* @dev Constructor, takes intial Token.
*/
function SkrumbleCandyToken() public {
totalSupply_ = 3000000 * 1 ether;
balances[msg.sender] = totalSupply_;
}
/**
* @dev Batch transfer some tokens to some addresses, address and value is one-on-one.
* @param _dests Array of addresses
* @param _values Array of transfer tokens number
*/
function batchTransfer(address[] _dests, uint256[] _values) public {
require(_dests.length == _values.length);
uint256 i = 0;
while (i < _dests.length) {
transfer(_dests[i], _values[i]);
i += 1;
}
}
/**
* @dev Batch transfer equal tokens amout to some addresses
* @param _dests Array of addresses
* @param _value Number of transfer tokens amount
*/
function batchTransferSingleValue(address[] _dests, uint256 _value) public {
uint256 i = 0;
while (i < _dests.length) {
transfer(_dests[i], _value);
i += 1;
}
}
} | SkrumbleCandyToken | function SkrumbleCandyToken() public {
totalSupply_ = 3000000 * 1 ether;
balances[msg.sender] = totalSupply_;
}
| /**
* @dev Constructor, takes intial Token.
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://24e639f9833c8209b754bbd6a3b1ce87b9803b9becd8fc0a75b1a7929adcc1d2 | {
"func_code_index": [
246,
385
]
} | 12,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.