Unnamed: 0 int64 0 7.36k | comments stringlengths 3 35.2k | code_string stringlengths 1 527k | code stringlengths 1 527k | __index_level_0__ int64 0 88.6k |
|---|---|---|---|---|
111 | // Send proceeds to seller/maker | orderMakerAddress.transfer(sellerProceeds);
| orderMakerAddress.transfer(sellerProceeds);
| 28,336 |
260 | // Combined into one function due to 24KiB contract memory limit | function setPoolParameters(uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee) external onlyByOwnerOrGovernance {
pool_ceiling = new_ceiling;
bonus_rate = new_bonus_rate;
redemption_delay = new_redemption_delay;
minting_fee = new_mint_fee;
redemption_fee = new_redeem_fee;
buyback_fee = new_buyback_fee;
recollat_fee = new_recollat_fee;
emit PoolParametersSet(new_ceiling, new_bonus_rate, new_redemption_delay, new_mint_fee, new_redeem_fee, new_buyback_fee, new_recollat_fee);
}
| function setPoolParameters(uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee) external onlyByOwnerOrGovernance {
pool_ceiling = new_ceiling;
bonus_rate = new_bonus_rate;
redemption_delay = new_redemption_delay;
minting_fee = new_mint_fee;
redemption_fee = new_redeem_fee;
buyback_fee = new_buyback_fee;
recollat_fee = new_recollat_fee;
emit PoolParametersSet(new_ceiling, new_bonus_rate, new_redemption_delay, new_mint_fee, new_redeem_fee, new_buyback_fee, new_recollat_fee);
}
| 22,915 |
103 | // Recover lost tokens can only be used after farming duration expires | require(duration < block.timestamp, "Cannot use if farm is live");
_token.safeTransfer(owner(), amount);
| require(duration < block.timestamp, "Cannot use if farm is live");
_token.safeTransfer(owner(), amount);
| 29,515 |
65 | // Allow to change the team multisig address in the case of emergency. / | function setMultisig(address addr) onlyOwner public {
//if (addr == address(0)) throw;
require(addr != address(0));
multisigEther = addr;
}
| function setMultisig(address addr) onlyOwner public {
//if (addr == address(0)) throw;
require(addr != address(0));
multisigEther = addr;
}
| 20,951 |
31 | // Modifiers | modifier onlyOwner() {
require(msg.sender == owner, "caller is not the owner!");
_;
}
| modifier onlyOwner() {
require(msg.sender == owner, "caller is not the owner!");
_;
}
| 6,534 |
4 | // Addresses of the co-founders of DNN. | address public cofounderA;
address public cofounderB;
| address public cofounderA;
address public cofounderB;
| 39,749 |
3 | // This is the tokenId to remove; | remove(staker, i);
| remove(staker, i);
| 38,033 |
264 | // Reserve 120 Pineapples for team - Giveaways/Prizes/Presales etc | uint public _reserve = 116;
mapping (string => address) public team;
| uint public _reserve = 116;
mapping (string => address) public team;
| 42,967 |
25 | // get the price of an asset / | function getAssetPrice() public pure returns (int256) {
return 1e18;
}
| function getAssetPrice() public pure returns (int256) {
return 1e18;
}
| 14,370 |
8 | // public functions//@inheritdoc IBuddleDestination / | function changeOwner(
TransferData memory _data,
uint256 _transferID,
uint256 sourceChain,
address _owner
) external
checkInitialization
| function changeOwner(
TransferData memory _data,
uint256 _transferID,
uint256 sourceChain,
address _owner
) external
checkInitialization
| 31,211 |
154 | // Sets a sender address of the failed message that came from the other side._messageId id of the message from the other side that triggered a call._receiver address of the receiver./ | function setFailedMessageReceiver(bytes32 _messageId, address _receiver) internal {
addressStorage[keccak256(abi.encodePacked("failedMessageReceiver", _messageId))] = _receiver;
}
| function setFailedMessageReceiver(bytes32 _messageId, address _receiver) internal {
addressStorage[keccak256(abi.encodePacked("failedMessageReceiver", _messageId))] = _receiver;
}
| 59,028 |
103 | // Burn users shares | _burn(msg.sender, _shares);
| _burn(msg.sender, _shares);
| 54,730 |
12 | // ChangedManagementProxy: :managementProxy can now manage :point | event ChangedManagementProxy( uint32 indexed point,
address indexed managementProxy );
| event ChangedManagementProxy( uint32 indexed point,
address indexed managementProxy );
| 2,896 |
71 | // Permissionless minting/to The address to mint to | function mint(address to)
public
virtual
payable
isCorrectPayment
canMint
isMintingOpen
| function mint(address to)
public
virtual
payable
isCorrectPayment
canMint
isMintingOpen
| 48,810 |
128 | // Removes a STFactory_major Major version of the proxy._minor Minor version of the proxy._patch Patch version of the proxy/ | function removeProtocolFactory(uint8 _major, uint8 _minor, uint8 _patch) external;
| function removeProtocolFactory(uint8 _major, uint8 _minor, uint8 _patch) external;
| 46,793 |
62 | // Sets `amount` as the allowance of `spender` over the `owner` s tokens. This internal function is equivalent to `approve`, and can be used toe.g. set automatic allowances for certain subsystems, etc. | * Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), 'ERC20: approve from the zero address');
require(spender != address(0), 'ERC20: approve to the zero address');
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| * Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), 'ERC20: approve from the zero address');
require(spender != address(0), 'ERC20: approve to the zero address');
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| 51,237 |
15 | // SafeDivs contract - GAIN 3% PER 24 HOURS (every 5900 blocks) // SafeMath v0.1.9 Math operations with safety checks that throw on errorchange notes:original SafeMath library from OpenZeppelin modified by Inventor- added sqrt- added sq- added pwr - changed asserts to requires with error log outputs- removed div, its useless / | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
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)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
| library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
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)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
| 36,519 |
2 | // default trading pair USDC-WETH | token = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); //''USDC'
weth = address (0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);//weth address
iWETH = IWETH(weth);
| token = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); //''USDC'
weth = address (0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);//weth address
iWETH = IWETH(weth);
| 5,617 |
72 | // Balances of token holders | mapping(address => uint256) internal balances;
| mapping(address => uint256) internal balances;
| 4,956 |
37 | // Allows a holder to stake a gorilla./First checks whether the specified gorilla has the genesis trait. Updates balances accordingly./ unchecked, because no arithmetic overflow is possible./_tokenId A specific gorilla, identified by its token ID. | function stake(uint256 _tokenId) public updateReward(msg.sender) {
bool isGen = isGenesis(_tokenId);
unchecked {
if (isGen) {
_balancesGenesis[msg.sender]++;
} else {
_balancesNormal[msg.sender]++;
}
}
tokenToAddr[_tokenId] = msg.sender;
gorillaContract.transferFrom(msg.sender, address(this), _tokenId);
}
| function stake(uint256 _tokenId) public updateReward(msg.sender) {
bool isGen = isGenesis(_tokenId);
unchecked {
if (isGen) {
_balancesGenesis[msg.sender]++;
} else {
_balancesNormal[msg.sender]++;
}
}
tokenToAddr[_tokenId] = msg.sender;
gorillaContract.transferFrom(msg.sender, address(this), _tokenId);
}
| 9,724 |
171 | // user | uint256 private constant INVITOR_WEIGHT = 10;
uint256 private constant MAX_MONTH = 36;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, uint256 weight);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
SashimiToken _sashimi,
address _commonToken,
uint256 _startBlock,
| uint256 private constant INVITOR_WEIGHT = 10;
uint256 private constant MAX_MONTH = 36;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, uint256 weight);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
SashimiToken _sashimi,
address _commonToken,
uint256 _startBlock,
| 32,488 |
267 | // Reserves contract to spend from | address public reserves;
| address public reserves;
| 10,904 |
14 | // DSMath.wpow | function bpowi(uint a, uint n)
internal pure
returns (uint)
| function bpowi(uint a, uint n)
internal pure
returns (uint)
| 14,298 |
807 | // Updates the Price Oracle based on the Pool's current state (balances, BPT supply and invariant). Must becalled on all state-changing functions with the balances before the state change happens, and with`lastChangeBlock` as the number of the block in which any of the balances last changed. / | function _updateOracle(
uint256 lastChangeBlock,
uint256 balanceToken0,
uint256 balanceToken1
| function _updateOracle(
uint256 lastChangeBlock,
uint256 balanceToken0,
uint256 balanceToken1
| 13,670 |
109 | // 0b00000000 0x00=> false, false0b01000000 0x40=> false, true0b10000000 0x80=> true, false0b11000000 0xc0=> true, true / | function activateStakeCampaign(
uint256 _cid,
address _stakeErc20,
uint256 _minStakeAmount,
uint256 _maxStakeAmount,
uint256 _lockBlockNum,
bytes1 _params,
uint256 _earlyStakeOutFine,
Operation[] calldata _op,
uint256[] calldata _networkFee,
| function activateStakeCampaign(
uint256 _cid,
address _stakeErc20,
uint256 _minStakeAmount,
uint256 _maxStakeAmount,
uint256 _lockBlockNum,
bytes1 _params,
uint256 _earlyStakeOutFine,
Operation[] calldata _op,
uint256[] calldata _networkFee,
| 71,930 |
11 | // Handle non-overflow cases, 256 by 256 division | if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
| if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
| 3,610 |
45 | // Emits a {Transfer} event with `to` set to the zero address. Requirements: - `account` cannot be the zero address. - `account` must have at least `amount` tokens./ | function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
| function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
| 44,616 |
32 | // Basic token Basic version of StandardToken, with no allowances. / | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public override view returns (uint256) {
return totalSupply_;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return balance An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public override view returns (uint256 balance) {
return balances[_owner];
}
/**
* @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 override virtual 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);
emit Transfer(msg.sender, _to, _value);
return true;
}
}
| contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public override view returns (uint256) {
return totalSupply_;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return balance An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public override view returns (uint256 balance) {
return balances[_owner];
}
/**
* @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 override virtual 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);
emit Transfer(msg.sender, _to, _value);
return true;
}
}
| 11,333 |
1 | // Unit Protocol parameters | IVaultParameters public constant vaultParameters = IVaultParameters(0xB46F8CF42e504Efe8BEf895f848741daA55e9f1D);
| IVaultParameters public constant vaultParameters = IVaultParameters(0xB46F8CF42e504Efe8BEf895f848741daA55e9f1D);
| 46,975 |
104 | // Generates team tokens after ICO finished | function generateTeamTokens() internal ICOFinished {
require(!teamTokensGenerated);
teamTokensGenerated = true;
if(tokensCap > totalSupply) {
//debugLog('before ', totalSupply);
uint unsoldAmount = tokensCap.sub(totalSupply);
token.mint(unsold, unsoldAmount);
//debugLog('unsold ', unsoldAmount);
totalSupply = totalSupply.add(unsoldAmount);
//debugLog('after ', totalSupply);
}
uint totalSupplyTokens = totalSupply;
totalSupplyTokens = totalSupplyTokens.mul(100);
totalSupplyTokens = totalSupplyTokens.div(60);
for (uint8 i = 0; i < listTeamTokens.length; ++i) {
uint teamTokensPart = percent(totalSupplyTokens, listTeamTokens[i].percent);
if (listTeamTokens[i].divider != 0) {
teamTokensPart = teamTokensPart.div(listTeamTokens[i].divider);
}
if (listTeamTokens[i].maxTokens != 0 && listTeamTokens[i].maxTokens < teamTokensPart) {
teamTokensPart = listTeamTokens[i].maxTokens;
}
token.mint(listTeamTokens[i].holder, teamTokensPart);
if(listTeamTokens[i].freezePeriod != 0) {
token.freezeTokens(listTeamTokens[i].holder, endTime + listTeamTokens[i].freezePeriod);
}
addToStat(teamTokensPart, 0);
}
}
| function generateTeamTokens() internal ICOFinished {
require(!teamTokensGenerated);
teamTokensGenerated = true;
if(tokensCap > totalSupply) {
//debugLog('before ', totalSupply);
uint unsoldAmount = tokensCap.sub(totalSupply);
token.mint(unsold, unsoldAmount);
//debugLog('unsold ', unsoldAmount);
totalSupply = totalSupply.add(unsoldAmount);
//debugLog('after ', totalSupply);
}
uint totalSupplyTokens = totalSupply;
totalSupplyTokens = totalSupplyTokens.mul(100);
totalSupplyTokens = totalSupplyTokens.div(60);
for (uint8 i = 0; i < listTeamTokens.length; ++i) {
uint teamTokensPart = percent(totalSupplyTokens, listTeamTokens[i].percent);
if (listTeamTokens[i].divider != 0) {
teamTokensPart = teamTokensPart.div(listTeamTokens[i].divider);
}
if (listTeamTokens[i].maxTokens != 0 && listTeamTokens[i].maxTokens < teamTokensPart) {
teamTokensPart = listTeamTokens[i].maxTokens;
}
token.mint(listTeamTokens[i].holder, teamTokensPart);
if(listTeamTokens[i].freezePeriod != 0) {
token.freezeTokens(listTeamTokens[i].holder, endTime + listTeamTokens[i].freezePeriod);
}
addToStat(teamTokensPart, 0);
}
}
| 28,624 |
159 | // updates the average rates / | function _updateAverageRates(Pool storage data, Fraction memory spotRate) private {
uint32 blockNumber = _blockNumber();
if (data.averageRates.blockNumber != blockNumber) {
data.averageRates = AverageRates({
blockNumber: blockNumber,
rate: _calcAverageRate(data.averageRates.rate, spotRate),
invRate: _calcAverageRate(data.averageRates.invRate, spotRate.inverse())
});
}
}
| function _updateAverageRates(Pool storage data, Fraction memory spotRate) private {
uint32 blockNumber = _blockNumber();
if (data.averageRates.blockNumber != blockNumber) {
data.averageRates = AverageRates({
blockNumber: blockNumber,
rate: _calcAverageRate(data.averageRates.rate, spotRate),
invRate: _calcAverageRate(data.averageRates.invRate, spotRate.inverse())
});
}
}
| 22,871 |
78 | // Change Governance of the contract to a new account (`newGovernor`). _newGovernor Address of the new Governor / | function _changeGovernor(address _newGovernor) internal {
require(_newGovernor != address(0), "New Governor is address(0)");
emit GovernorshipTransferred(_governor(), _newGovernor);
_setGovernor(_newGovernor);
}
| function _changeGovernor(address _newGovernor) internal {
require(_newGovernor != address(0), "New Governor is address(0)");
emit GovernorshipTransferred(_governor(), _newGovernor);
_setGovernor(_newGovernor);
}
| 7,537 |
3 | // Investors can claim refunds here if crowdsale is unsuccessful/ | function claimRefund() public {
require(isFinalized, "Crowdsale is not finalized yet");
require(!goalReached(), "Goal of the crowdsale is reached");
escrow.withdraw(msg.sender);
}
| function claimRefund() public {
require(isFinalized, "Crowdsale is not finalized yet");
require(!goalReached(), "Goal of the crowdsale is reached");
escrow.withdraw(msg.sender);
}
| 9,035 |
146 | // ERC-721 Non-Fungible Token Standard, optional metadata extension / | interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
| interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
| 1,495 |
128 | // update cached total vault and Aludel amounts | vaultData.totalStake = vaultData.totalStake.add(amount);
_aludel.totalStake = _aludel.totalStake.add(amount);
| vaultData.totalStake = vaultData.totalStake.add(amount);
_aludel.totalStake = _aludel.totalStake.add(amount);
| 41,526 |
157 | // Ensure that an escape hatch account has been provided. | if (account == address(0)) {
revert(_revertReason(5));
}
| if (account == address(0)) {
revert(_revertReason(5));
}
| 82,586 |
0 | // / | interface IGMMetadata {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
function add(string calldata ipfsHash) external returns (uint256 tokenId);
function setUpgrader(address upgrader_) external;
}
| interface IGMMetadata {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
function add(string calldata ipfsHash) external returns (uint256 tokenId);
function setUpgrader(address upgrader_) external;
}
| 32,916 |
1 | // 2041 - 2048 4 ETH | } else if (currentSupply >= 2024) {
| } else if (currentSupply >= 2024) {
| 50,853 |
5 | // create a new doc | docDetails memory newDoc = docDetails({dataHash: dataHash, status: "QUEUED", isDiscoverable: isDiscoverable,
verifiedBy: address(0), requestedBy: msg.sender} );
| docDetails memory newDoc = docDetails({dataHash: dataHash, status: "QUEUED", isDiscoverable: isDiscoverable,
verifiedBy: address(0), requestedBy: msg.sender} );
| 12,419 |
19 | // ,-.`-'/|\ |,-----------------./ \ |ZoraModuleManager|Caller`--------+--------'| setBatchApprovalForModule()|| --------------------------->||||| _____________________________________________________| ! LOOP/for each module !| !______/ | !| !|----.!| !|| set approval for module!| !|<---'!| !| !| !|----.!| !|| emit ModuleApprovalSet() !| !|<---'!| !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~!Caller,--------+--------.,-. |ZoraModuleManager|`-' `-----------------'/|\ |/ \/Sets approvals for multiple modules at once/_modules The list of module addresses to set approvals for/_approved A boolean, whether or not to approve the modules | function setBatchApprovalForModules(address[] memory _modules, bool _approved) public {
// Store the number of module addresses provided
uint256 numModules = _modules.length;
// Loop through each address
for (uint256 i = 0; i < numModules; ) {
// Ensure that it's a registered module and set the approval
_setApprovalForModule(_modules[i], msg.sender, _approved);
// Cannot overflow as array length cannot exceed uint256 max
unchecked {
++i;
}
}
}
| function setBatchApprovalForModules(address[] memory _modules, bool _approved) public {
// Store the number of module addresses provided
uint256 numModules = _modules.length;
// Loop through each address
for (uint256 i = 0; i < numModules; ) {
// Ensure that it's a registered module and set the approval
_setApprovalForModule(_modules[i], msg.sender, _approved);
// Cannot overflow as array length cannot exceed uint256 max
unchecked {
++i;
}
}
}
| 5,629 |
9 | // created by http:about.me/kh.bakhtiari | contract Lottery {
bool enabled = true;
address public owner;
uint private ROUND_PER_BLOCK = 20;
uint private TICKET_PRICE = 1 finney;
uint private MAX_PENDING_PARTICIPANTS = 50;
uint public targetBlock;
uint public ticketPrice;
uint8 public minParticipants;
uint8 public maxParticipants;
uint public totalRoundsPassed;
uint public totalTicketsSold;
address[] public participants;
address[] public pendingParticipants;
event RoundEnded(address winner, uint amount);
function Lottery() public payable {
increaseBlockTarget();
ticketPrice = 1 finney;
minParticipants = 2;
maxParticipants = 20;
owner = msg.sender;
}
function () payable {
if (!enabled)
throw;
if (msg.value < ticketPrice)
throw;
for (uint i = 0; i < msg.value / ticketPrice; i++) {
if (participants.length == maxParticipants) {
if (pendingParticipants.length >= MAX_PENDING_PARTICIPANTS)
if (msg.sender.send(msg.value - (i * TICKET_PRICE)))
return;
else
throw;
pendingParticipants.push(msg.sender);
} else {
participants.push(msg.sender);
}
totalTicketsSold++;
}
if (msg.value % ticketPrice > 0)
if (!msg.sender.send(msg.value % ticketPrice))
throw;
}
function conclude () public returns (bool) {
if (block.number < targetBlock)
return false;
totalRoundsPassed++;
increaseBlockTarget();
if (!findAndPayTheWinner())
return false;
delete participants;
uint m = pendingParticipants.length > maxParticipants ? maxParticipants : pendingParticipants.length;
for (uint i = 0; i < m; i++)
participants.push(pendingParticipants[i]);
if (m == pendingParticipants.length) {
delete pendingParticipants;
} else {
for (i = m; i < pendingParticipants.length; i++) {
pendingParticipants[i-m] == pendingParticipants[i];
delete pendingParticipants[i];
}
pendingParticipants.length -= m;
}
return true;
}
function findAndPayTheWinner() private returns (bool) {
uint winnerIndex = uint(block.blockhash(block.number - 1)) % participants.length;
address winner = participants[winnerIndex];
uint prize = (ticketPrice * participants.length) * 98 / 100;
bool success = winner.send(prize);
if (success)
RoundEnded(winner, prize);
return success;
}
function increaseBlockTarget() private {
if (block.number < targetBlock)
return;
targetBlock = block.number + ROUND_PER_BLOCK;
}
function currentParticipants() public constant returns (uint) {
return participants.length;
}
function currentPendingParticipants() public constant returns (uint) {
return pendingParticipants.length;
}
function maxPendingParticipants() public constant returns (uint) {
return MAX_PENDING_PARTICIPANTS;
}
function kill() public {
enabled = false;
}
}
| contract Lottery {
bool enabled = true;
address public owner;
uint private ROUND_PER_BLOCK = 20;
uint private TICKET_PRICE = 1 finney;
uint private MAX_PENDING_PARTICIPANTS = 50;
uint public targetBlock;
uint public ticketPrice;
uint8 public minParticipants;
uint8 public maxParticipants;
uint public totalRoundsPassed;
uint public totalTicketsSold;
address[] public participants;
address[] public pendingParticipants;
event RoundEnded(address winner, uint amount);
function Lottery() public payable {
increaseBlockTarget();
ticketPrice = 1 finney;
minParticipants = 2;
maxParticipants = 20;
owner = msg.sender;
}
function () payable {
if (!enabled)
throw;
if (msg.value < ticketPrice)
throw;
for (uint i = 0; i < msg.value / ticketPrice; i++) {
if (participants.length == maxParticipants) {
if (pendingParticipants.length >= MAX_PENDING_PARTICIPANTS)
if (msg.sender.send(msg.value - (i * TICKET_PRICE)))
return;
else
throw;
pendingParticipants.push(msg.sender);
} else {
participants.push(msg.sender);
}
totalTicketsSold++;
}
if (msg.value % ticketPrice > 0)
if (!msg.sender.send(msg.value % ticketPrice))
throw;
}
function conclude () public returns (bool) {
if (block.number < targetBlock)
return false;
totalRoundsPassed++;
increaseBlockTarget();
if (!findAndPayTheWinner())
return false;
delete participants;
uint m = pendingParticipants.length > maxParticipants ? maxParticipants : pendingParticipants.length;
for (uint i = 0; i < m; i++)
participants.push(pendingParticipants[i]);
if (m == pendingParticipants.length) {
delete pendingParticipants;
} else {
for (i = m; i < pendingParticipants.length; i++) {
pendingParticipants[i-m] == pendingParticipants[i];
delete pendingParticipants[i];
}
pendingParticipants.length -= m;
}
return true;
}
function findAndPayTheWinner() private returns (bool) {
uint winnerIndex = uint(block.blockhash(block.number - 1)) % participants.length;
address winner = participants[winnerIndex];
uint prize = (ticketPrice * participants.length) * 98 / 100;
bool success = winner.send(prize);
if (success)
RoundEnded(winner, prize);
return success;
}
function increaseBlockTarget() private {
if (block.number < targetBlock)
return;
targetBlock = block.number + ROUND_PER_BLOCK;
}
function currentParticipants() public constant returns (uint) {
return participants.length;
}
function currentPendingParticipants() public constant returns (uint) {
return pendingParticipants.length;
}
function maxPendingParticipants() public constant returns (uint) {
return MAX_PENDING_PARTICIPANTS;
}
function kill() public {
enabled = false;
}
}
| 47,549 |
111 | // The price is selected based on current sold tokens. Price can &39;overlap&39;. For example: 1. if currently we sold 699950 tokens (the price is 10% discount) 2. buyer buys 1000 tokens 3. the price of all 1000 tokens would be with 10% discount!!! | uint newTokens = (msg.value * getMntTokensPerEth(icoTokensSold)) / 1 ether;
issueTokensInternal(_buyer,newTokens);
| uint newTokens = (msg.value * getMntTokensPerEth(icoTokensSold)) / 1 ether;
issueTokensInternal(_buyer,newTokens);
| 41,216 |
88 | // Provides information of a vote when given its vote id. _voteid Vote Id. / | function getVoteDetails(uint _voteid)
external view
returns(
uint tokens,
uint claimId,
int8 verdict,
bool rewardClaimed
)
| function getVoteDetails(uint _voteid)
external view
returns(
uint tokens,
uint claimId,
int8 verdict,
bool rewardClaimed
)
| 28,886 |
19 | // extending an existing position g_st = g_st + (u_tot(u_new_st - u_st)) / (g_amt) | globalStartTime = _globalStartTime +
(userTotal * (newStartTime - startTime)) /
_totalLockedAmount;
| globalStartTime = _globalStartTime +
(userTotal * (newStartTime - startTime)) /
_totalLockedAmount;
| 2,399 |
2 | // Returns the name of the protocol the Ante Test is testing/This overrides the auto-generated getter for protocolName as a public var/ return The name of the protocol in string format | function protocolName() external view returns (string memory);
| function protocolName() external view returns (string memory);
| 29,727 |
127 | // so the bit shift does not overflow | require(upper <= uint112(-1), 'FixedPoint::muluq: upper overflow');
| require(upper <= uint112(-1), 'FixedPoint::muluq: upper overflow');
| 140 |
179 | // Storage of current hub instance | IHub internal hubInstance_;
| IHub internal hubInstance_;
| 41,375 |
57 | // makes the transfer | _transfer(this, msg.sender, amount);
| _transfer(this, msg.sender, amount);
| 12,845 |
61 | // if (user[userAddress] == false) { user[userAddress] = true; addresses.push(userAddress); } |
IERC20(tokenAddress).transferFrom(
userAddress,
address(this),
tokenAmount
);
_mint(userAddress, token[tokenAddress], tokenAmount, "");
timelock[userAddress] = block.timestamp;
lentAmount[tokenAddress][userAddress] += tokenAmount;
emit AmountChange(
|
IERC20(tokenAddress).transferFrom(
userAddress,
address(this),
tokenAmount
);
_mint(userAddress, token[tokenAddress], tokenAmount, "");
timelock[userAddress] = block.timestamp;
lentAmount[tokenAddress][userAddress] += tokenAmount;
emit AmountChange(
| 18,809 |
5 | // wrapping gives ownernship to NameWrapper | nameWrapper.wrapETH2LD(
labelResolvers[i].label,
wrappedOwner,
fuses,
labelResolvers[i].resolver
);
| nameWrapper.wrapETH2LD(
labelResolvers[i].label,
wrappedOwner,
fuses,
labelResolvers[i].resolver
);
| 41,005 |
160 | // emit transferFeeSubtracted(msg.sender, transferFee); |
return super.transferFrom(_sender, _recipient, _amount);
|
return super.transferFrom(_sender, _recipient, _amount);
| 39,502 |
1 | // Scores dos jogadores | struct PlayGame {
address player;
uint score;
}
| struct PlayGame {
address player;
uint score;
}
| 6,593 |
4 | // Mint new tokens. _to Address to send the newly minted tokens _amount Amount of tokens to mint / | function mint(address _to, uint256 _amount) external onlyGovernorOrGSR {
_mint(_to, _amount);
}
| function mint(address _to, uint256 _amount) external onlyGovernorOrGSR {
_mint(_to, _amount);
}
| 6,764 |
354 | // Calculate sign of x, i.e. -1 if x is negative, 0 if x if zero, and 1 if xis positive.Note that sign (-0) is zero.Revert if x is NaN. x quadruple precision numberreturn sign of x / | function sign (bytes16 x) internal pure returns (int8) {
unchecked {
uint128 absoluteX = uint128 (x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
require (absoluteX <= 0x7FFF0000000000000000000000000000); // Not NaN
if (absoluteX == 0) return 0;
else if (uint128 (x) >= 0x80000000000000000000000000000000) return -1;
else return 1;
}
}
| function sign (bytes16 x) internal pure returns (int8) {
unchecked {
uint128 absoluteX = uint128 (x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
require (absoluteX <= 0x7FFF0000000000000000000000000000); // Not NaN
if (absoluteX == 0) return 0;
else if (uint128 (x) >= 0x80000000000000000000000000000000) return -1;
else return 1;
}
}
| 36,757 |
33 | // submit transfer | Transfer(owner, msg.sender, requestedUnits);
owner.transfer(msg.value);
| Transfer(owner, msg.sender, requestedUnits);
owner.transfer(msg.value);
| 7,616 |
30 | // General // Get documentation about this contract. / | function doc() public view returns (string memory name, string memory description, string memory details) {
return MoonCatReference.doc(address(this));
}
| function doc() public view returns (string memory name, string memory description, string memory details) {
return MoonCatReference.doc(address(this));
}
| 46,806 |
54 | // reward rate % per year | uint public rewardRate = 5000;
uint public rewardInterval = 365 days;
| uint public rewardRate = 5000;
uint public rewardInterval = 365 days;
| 40,345 |
7 | // Revokes `role` from `account`. If `account` had been granted `role`, emits a {RoleRevoked} event. Requirements: - the caller must have ``role``'s admin role./ | function revokeRole(bytes32 role, address account) external;
| function revokeRole(bytes32 role, address account) external;
| 6,773 |
7 | // Pool for INO | struct INOPool {
uint256 Id;
uint256 Begin;
uint256 End;
uint256 Type; // 1:public, 2:private
uint256 AmountPBRRequire; //must e18,important when init
uint256 LockDuration; //lock after purchase
uint256 ActivedDate;
uint256 StopDate;
uint256 claimType; // 1: claim in PBR INO, 2: claim in other project
| struct INOPool {
uint256 Id;
uint256 Begin;
uint256 End;
uint256 Type; // 1:public, 2:private
uint256 AmountPBRRequire; //must e18,important when init
uint256 LockDuration; //lock after purchase
uint256 ActivedDate;
uint256 StopDate;
uint256 claimType; // 1: claim in PBR INO, 2: claim in other project
| 37,307 |
200 | // Note! It's possible that either of the two `.sub` calls below will underflow and return an error. This will only happen if the AMM does not have sufficient collateral balance to buy the bToken and wToken from the LP. If this happens, this transaction will revert with a "SafeMath: subtraction overflow" error | collateralLeft = collateralLeft.sub(collateralAmountB);
uint256 collateralAmountW = wTokenGetCollateralOutInternal(
optionMarket,
wTokenToSell,
collateralLeft
);
collateralLeft = collateralLeft.sub(collateralAmountW);
| collateralLeft = collateralLeft.sub(collateralAmountB);
uint256 collateralAmountW = wTokenGetCollateralOutInternal(
optionMarket,
wTokenToSell,
collateralLeft
);
collateralLeft = collateralLeft.sub(collateralAmountW);
| 7,072 |
225 | // -------------------------------------------------------- [external] 残高の確認-------------------------------------------------------- | function checkBalance() external view returns (uint256) {
return( address(this).balance );
}
| function checkBalance() external view returns (uint256) {
return( address(this).balance );
}
| 20,317 |
37 | // Take was called before `1` hour had passed from kick time. / | error TakeNotPastCooldown();
| error TakeNotPastCooldown();
| 39,885 |
89 | // The tokenId of the next token to be minted. | uint128 internal _currentIndex;
| uint128 internal _currentIndex;
| 3,005 |
0 | // TODO: Configure this value based on the cost of sends | uint8 internal constant MAX_SEND_COUNT = 100;
| uint8 internal constant MAX_SEND_COUNT = 100;
| 23,682 |
11 | // Integer division of two numbers truncating the quotient, reverts on division by zero./ | function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts 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;
}
| function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts 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;
}
| 31,445 |
128 | // In this function we don't have to change the stored length data | return (loadedData);
| return (loadedData);
| 27,530 |
111 | // Sets Buy/Sell limits | balanceLimit=InitialSupply/BalanceLimitDivider;
sellLimit=InitialSupply/SellLimitDivider;
buyLimit=InitialSupply/BuyLimitDivider;
| balanceLimit=InitialSupply/BalanceLimitDivider;
sellLimit=InitialSupply/SellLimitDivider;
buyLimit=InitialSupply/BuyLimitDivider;
| 11,470 |
68 | // in case of a higher market cap dev must change the minimBuy to a smaller amount | function changeMinimBuy(uint256 amount) external {
require(_msgSender() == _devWallet);
_minimBuy = amount * (10 ** 9);
}
| function changeMinimBuy(uint256 amount) external {
require(_msgSender() == _devWallet);
_minimBuy = amount * (10 ** 9);
}
| 25,474 |
108 | // Events | event NewProposal(
uint256 proposalID,
string indexed proposalType,
bytes proposalPayload
);
event Voted(address boardMember, uint256 proposalId);
event ProposalApprovedAndEnforced(
uint256 proposalID,
bytes payload,
bool success,
| event NewProposal(
uint256 proposalID,
string indexed proposalType,
bytes proposalPayload
);
event Voted(address boardMember, uint256 proposalId);
event ProposalApprovedAndEnforced(
uint256 proposalID,
bytes payload,
bool success,
| 28,691 |
10 | // amt subtrated from msg.sender and given to toAirline | toAirline.transfer(amt);
| toAirline.transfer(amt);
| 19,823 |
51 | // isLiquidityToken[ _OHMDAI ] = true;liquidityTokens.push( _OHMDAI ); |
secondsNeededForQueue = _secondsNeededForQueue;
limitAmount = _limitAmount;
|
secondsNeededForQueue = _secondsNeededForQueue;
limitAmount = _limitAmount;
| 15,444 |
221 | // ComptrollerLib Contract/Enzyme Council <[email protected]>/The core logic library shared by all funds | contract ComptrollerLib is IComptroller, IGasRelayPaymasterDepositor, GasRelayRecipientMixin {
import "../../../extensions/fee-manager/IFeeManager.sol";
import "../../../extensions/policy-manager/IPolicyManager.sol";
import "../../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol";
import "../../../infrastructure/gas-relayer/IGasRelayPaymaster.sol";
import "../../../infrastructure/gas-relayer/IGasRelayPaymasterDepositor.sol";
import "../../../infrastructure/value-interpreter/IValueInterpreter.sol";
import "../../../utils/beacon-proxy/IBeaconProxyFactory.sol";
import "../../../utils/AddressArrayLib.sol";
import "../../fund-deployer/IFundDeployer.sol";
import "../vault/IVault.sol";
import "./IComptroller.sol";
using AddressArrayLib for address[];
using SafeMath for uint256;
using SafeERC20 for ERC20;
event AutoProtocolFeeSharesBuybackSet(bool autoProtocolFeeSharesBuyback);
event BuyBackMaxProtocolFeeSharesFailed(
bytes indexed failureReturnData,
uint256 sharesAmount,
uint256 buybackValueInMln,
uint256 gav
);
event DeactivateFeeManagerFailed();
event GasRelayPaymasterSet(address gasRelayPaymaster);
event MigratedSharesDuePaid(uint256 sharesDue);
event PayProtocolFeeDuringDestructFailed();
event PreRedeemSharesHookFailed(
bytes indexed failureReturnData,
address indexed redeemer,
uint256 sharesAmount
);
event RedeemSharesInKindCalcGavFailed();
event SharesBought(
address indexed buyer,
uint256 investmentAmount,
uint256 sharesIssued,
uint256 sharesReceived
);
event SharesRedeemed(
address indexed redeemer,
address indexed recipient,
uint256 sharesAmount,
address[] receivedAssets,
uint256[] receivedAssetAmounts
);
event VaultProxySet(address vaultProxy);
// Constants and immutables - shared by all proxies
uint256 private constant ONE_HUNDRED_PERCENT = 10000;
uint256 private constant SHARES_UNIT = 10**18;
address
private constant SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS = 0x000000000000000000000000000000000000aaaa;
address private immutable DISPATCHER;
address private immutable EXTERNAL_POSITION_MANAGER;
address private immutable FUND_DEPLOYER;
address private immutable FEE_MANAGER;
address private immutable INTEGRATION_MANAGER;
address private immutable MLN_TOKEN;
address private immutable POLICY_MANAGER;
address private immutable PROTOCOL_FEE_RESERVE;
address private immutable VALUE_INTERPRETER;
address private immutable WETH_TOKEN;
// Pseudo-constants (can only be set once)
address internal denominationAsset;
address internal vaultProxy;
// True only for the one non-proxy
bool internal isLib;
// Storage
// Attempts to buy back protocol fee shares immediately after collection
bool internal autoProtocolFeeSharesBuyback;
// A reverse-mutex, granting atomic permission for particular contracts to make vault calls
bool internal permissionedVaultActionAllowed;
// A mutex to protect against reentrancy
bool internal reentranceLocked;
// A timelock after the last time shares were bought for an account
// that must expire before that account transfers or redeems their shares
uint256 internal sharesActionTimelock;
mapping(address => uint256) internal acctToLastSharesBoughtTimestamp;
// The contract which manages paying gas relayers
address private gasRelayPaymaster;
///////////////
// MODIFIERS //
///////////////
modifier allowsPermissionedVaultAction {
__assertPermissionedVaultActionNotAllowed();
permissionedVaultActionAllowed = true;
_;
permissionedVaultActionAllowed = false;
}
modifier locksReentrance() {
__assertNotReentranceLocked();
reentranceLocked = true;
_;
reentranceLocked = false;
}
modifier onlyFundDeployer() {
__assertIsFundDeployer();
_;
}
modifier onlyGasRelayPaymaster() {
__assertIsGasRelayPaymaster();
_;
}
modifier onlyOwner() {
__assertIsOwner(__msgSender());
_;
}
modifier onlyOwnerNotRelayable() {
__assertIsOwner(msg.sender);
_;
}
// ASSERTION HELPERS
// Modifiers are inefficient in terms of contract size,
// so we use helper functions to prevent repetitive inlining of expensive string values.
function __assertIsFundDeployer() private view {
require(msg.sender == getFundDeployer(), "Only FundDeployer callable");
}
function __assertIsGasRelayPaymaster() private view {
require(msg.sender == getGasRelayPaymaster(), "Only Gas Relay Paymaster callable");
}
function __assertIsOwner(address _who) private view {
require(_who == IVault(getVaultProxy()).getOwner(), "Only fund owner callable");
}
function __assertNotReentranceLocked() private view {
require(!reentranceLocked, "Re-entrance");
}
function __assertPermissionedVaultActionNotAllowed() private view {
require(!permissionedVaultActionAllowed, "Vault action re-entrance");
}
function __assertSharesActionNotTimelocked(address _vaultProxy, address _account)
private
view
{
uint256 lastSharesBoughtTimestamp = getLastSharesBoughtTimestampForAccount(_account);
require(
lastSharesBoughtTimestamp == 0 ||
block.timestamp.sub(lastSharesBoughtTimestamp) >= getSharesActionTimelock() ||
__hasPendingMigrationOrReconfiguration(_vaultProxy),
"Shares action timelocked"
);
}
constructor(
address _dispatcher,
address _protocolFeeReserve,
address _fundDeployer,
address _valueInterpreter,
address _externalPositionManager,
address _feeManager,
address _integrationManager,
address _policyManager,
address _gasRelayPaymasterFactory,
address _mlnToken,
address _wethToken
) public GasRelayRecipientMixin(_gasRelayPaymasterFactory) {
DISPATCHER = _dispatcher;
EXTERNAL_POSITION_MANAGER = _externalPositionManager;
FEE_MANAGER = _feeManager;
FUND_DEPLOYER = _fundDeployer;
INTEGRATION_MANAGER = _integrationManager;
MLN_TOKEN = _mlnToken;
POLICY_MANAGER = _policyManager;
PROTOCOL_FEE_RESERVE = _protocolFeeReserve;
VALUE_INTERPRETER = _valueInterpreter;
WETH_TOKEN = _wethToken;
isLib = true;
}
/////////////
// GENERAL //
/////////////
/// @notice Calls a specified action on an Extension
/// @param _extension The Extension contract to call (e.g., FeeManager)
/// @param _actionId An ID representing the action to take on the extension (see extension)
/// @param _callArgs The encoded data for the call
/// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy
/// (for access control). Uses a mutex of sorts that allows "permissioned vault actions"
/// during calls originating from this function.
function callOnExtension(
address _extension,
uint256 _actionId,
bytes calldata _callArgs
) external override locksReentrance allowsPermissionedVaultAction {
require(
_extension == getFeeManager() ||
_extension == getIntegrationManager() ||
_extension == getExternalPositionManager(),
"callOnExtension: _extension invalid"
);
IExtension(_extension).receiveCallFromComptroller(__msgSender(), _actionId, _callArgs);
}
/// @notice Makes an arbitrary call with the VaultProxy contract as the sender
/// @param _contract The contract to call
/// @param _selector The selector to call
/// @param _encodedArgs The encoded arguments for the call
/// @return returnData_ The data returned by the call
function vaultCallOnContract(
address _contract,
bytes4 _selector,
bytes calldata _encodedArgs
) external onlyOwner returns (bytes memory returnData_) {
require(
IFundDeployer(getFundDeployer()).isAllowedVaultCall(
_contract,
_selector,
keccak256(_encodedArgs)
),
"vaultCallOnContract: Not allowed"
);
return
IVault(getVaultProxy()).callOnContract(
_contract,
abi.encodePacked(_selector, _encodedArgs)
);
}
/// @dev Helper to check if a VaultProxy has a pending migration or reconfiguration request
function __hasPendingMigrationOrReconfiguration(address _vaultProxy)
private
view
returns (bool hasPendingMigrationOrReconfiguration)
{
return
IDispatcher(getDispatcher()).hasMigrationRequest(_vaultProxy) ||
IFundDeployer(getFundDeployer()).hasReconfigurationRequest(_vaultProxy);
}
//////////////////
// PROTOCOL FEE //
//////////////////
/// @notice Buys back shares collected as protocol fee at a discounted shares price, using MLN
/// @param _sharesAmount The amount of shares to buy back
function buyBackProtocolFeeShares(uint256 _sharesAmount) external {
address vaultProxyCopy = vaultProxy;
require(
IVault(vaultProxyCopy).canManageAssets(__msgSender()),
"buyBackProtocolFeeShares: Unauthorized"
);
uint256 gav = calcGav();
IVault(vaultProxyCopy).buyBackProtocolFeeShares(
_sharesAmount,
__getBuybackValueInMln(vaultProxyCopy, _sharesAmount, gav),
gav
);
}
/// @notice Sets whether to attempt to buyback protocol fee shares immediately when collected
/// @param _nextAutoProtocolFeeSharesBuyback True if protocol fee shares should be attempted
/// to be bought back immediately when collected
function setAutoProtocolFeeSharesBuyback(bool _nextAutoProtocolFeeSharesBuyback)
external
onlyOwner
{
autoProtocolFeeSharesBuyback = _nextAutoProtocolFeeSharesBuyback;
emit AutoProtocolFeeSharesBuybackSet(_nextAutoProtocolFeeSharesBuyback);
}
/// @dev Helper to buyback the max available protocol fee shares, during an auto-buyback
function __buyBackMaxProtocolFeeShares(address _vaultProxy, uint256 _gav) private {
uint256 sharesAmount = ERC20(_vaultProxy).balanceOf(getProtocolFeeReserve());
uint256 buybackValueInMln = __getBuybackValueInMln(_vaultProxy, sharesAmount, _gav);
try
IVault(_vaultProxy).buyBackProtocolFeeShares(sharesAmount, buybackValueInMln, _gav)
{} catch (bytes memory reason) {
emit BuyBackMaxProtocolFeeSharesFailed(reason, sharesAmount, buybackValueInMln, _gav);
}
}
| contract ComptrollerLib is IComptroller, IGasRelayPaymasterDepositor, GasRelayRecipientMixin {
import "../../../extensions/fee-manager/IFeeManager.sol";
import "../../../extensions/policy-manager/IPolicyManager.sol";
import "../../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol";
import "../../../infrastructure/gas-relayer/IGasRelayPaymaster.sol";
import "../../../infrastructure/gas-relayer/IGasRelayPaymasterDepositor.sol";
import "../../../infrastructure/value-interpreter/IValueInterpreter.sol";
import "../../../utils/beacon-proxy/IBeaconProxyFactory.sol";
import "../../../utils/AddressArrayLib.sol";
import "../../fund-deployer/IFundDeployer.sol";
import "../vault/IVault.sol";
import "./IComptroller.sol";
using AddressArrayLib for address[];
using SafeMath for uint256;
using SafeERC20 for ERC20;
event AutoProtocolFeeSharesBuybackSet(bool autoProtocolFeeSharesBuyback);
event BuyBackMaxProtocolFeeSharesFailed(
bytes indexed failureReturnData,
uint256 sharesAmount,
uint256 buybackValueInMln,
uint256 gav
);
event DeactivateFeeManagerFailed();
event GasRelayPaymasterSet(address gasRelayPaymaster);
event MigratedSharesDuePaid(uint256 sharesDue);
event PayProtocolFeeDuringDestructFailed();
event PreRedeemSharesHookFailed(
bytes indexed failureReturnData,
address indexed redeemer,
uint256 sharesAmount
);
event RedeemSharesInKindCalcGavFailed();
event SharesBought(
address indexed buyer,
uint256 investmentAmount,
uint256 sharesIssued,
uint256 sharesReceived
);
event SharesRedeemed(
address indexed redeemer,
address indexed recipient,
uint256 sharesAmount,
address[] receivedAssets,
uint256[] receivedAssetAmounts
);
event VaultProxySet(address vaultProxy);
// Constants and immutables - shared by all proxies
uint256 private constant ONE_HUNDRED_PERCENT = 10000;
uint256 private constant SHARES_UNIT = 10**18;
address
private constant SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS = 0x000000000000000000000000000000000000aaaa;
address private immutable DISPATCHER;
address private immutable EXTERNAL_POSITION_MANAGER;
address private immutable FUND_DEPLOYER;
address private immutable FEE_MANAGER;
address private immutable INTEGRATION_MANAGER;
address private immutable MLN_TOKEN;
address private immutable POLICY_MANAGER;
address private immutable PROTOCOL_FEE_RESERVE;
address private immutable VALUE_INTERPRETER;
address private immutable WETH_TOKEN;
// Pseudo-constants (can only be set once)
address internal denominationAsset;
address internal vaultProxy;
// True only for the one non-proxy
bool internal isLib;
// Storage
// Attempts to buy back protocol fee shares immediately after collection
bool internal autoProtocolFeeSharesBuyback;
// A reverse-mutex, granting atomic permission for particular contracts to make vault calls
bool internal permissionedVaultActionAllowed;
// A mutex to protect against reentrancy
bool internal reentranceLocked;
// A timelock after the last time shares were bought for an account
// that must expire before that account transfers or redeems their shares
uint256 internal sharesActionTimelock;
mapping(address => uint256) internal acctToLastSharesBoughtTimestamp;
// The contract which manages paying gas relayers
address private gasRelayPaymaster;
///////////////
// MODIFIERS //
///////////////
modifier allowsPermissionedVaultAction {
__assertPermissionedVaultActionNotAllowed();
permissionedVaultActionAllowed = true;
_;
permissionedVaultActionAllowed = false;
}
modifier locksReentrance() {
__assertNotReentranceLocked();
reentranceLocked = true;
_;
reentranceLocked = false;
}
modifier onlyFundDeployer() {
__assertIsFundDeployer();
_;
}
modifier onlyGasRelayPaymaster() {
__assertIsGasRelayPaymaster();
_;
}
modifier onlyOwner() {
__assertIsOwner(__msgSender());
_;
}
modifier onlyOwnerNotRelayable() {
__assertIsOwner(msg.sender);
_;
}
// ASSERTION HELPERS
// Modifiers are inefficient in terms of contract size,
// so we use helper functions to prevent repetitive inlining of expensive string values.
function __assertIsFundDeployer() private view {
require(msg.sender == getFundDeployer(), "Only FundDeployer callable");
}
function __assertIsGasRelayPaymaster() private view {
require(msg.sender == getGasRelayPaymaster(), "Only Gas Relay Paymaster callable");
}
function __assertIsOwner(address _who) private view {
require(_who == IVault(getVaultProxy()).getOwner(), "Only fund owner callable");
}
function __assertNotReentranceLocked() private view {
require(!reentranceLocked, "Re-entrance");
}
function __assertPermissionedVaultActionNotAllowed() private view {
require(!permissionedVaultActionAllowed, "Vault action re-entrance");
}
function __assertSharesActionNotTimelocked(address _vaultProxy, address _account)
private
view
{
uint256 lastSharesBoughtTimestamp = getLastSharesBoughtTimestampForAccount(_account);
require(
lastSharesBoughtTimestamp == 0 ||
block.timestamp.sub(lastSharesBoughtTimestamp) >= getSharesActionTimelock() ||
__hasPendingMigrationOrReconfiguration(_vaultProxy),
"Shares action timelocked"
);
}
constructor(
address _dispatcher,
address _protocolFeeReserve,
address _fundDeployer,
address _valueInterpreter,
address _externalPositionManager,
address _feeManager,
address _integrationManager,
address _policyManager,
address _gasRelayPaymasterFactory,
address _mlnToken,
address _wethToken
) public GasRelayRecipientMixin(_gasRelayPaymasterFactory) {
DISPATCHER = _dispatcher;
EXTERNAL_POSITION_MANAGER = _externalPositionManager;
FEE_MANAGER = _feeManager;
FUND_DEPLOYER = _fundDeployer;
INTEGRATION_MANAGER = _integrationManager;
MLN_TOKEN = _mlnToken;
POLICY_MANAGER = _policyManager;
PROTOCOL_FEE_RESERVE = _protocolFeeReserve;
VALUE_INTERPRETER = _valueInterpreter;
WETH_TOKEN = _wethToken;
isLib = true;
}
/////////////
// GENERAL //
/////////////
/// @notice Calls a specified action on an Extension
/// @param _extension The Extension contract to call (e.g., FeeManager)
/// @param _actionId An ID representing the action to take on the extension (see extension)
/// @param _callArgs The encoded data for the call
/// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy
/// (for access control). Uses a mutex of sorts that allows "permissioned vault actions"
/// during calls originating from this function.
function callOnExtension(
address _extension,
uint256 _actionId,
bytes calldata _callArgs
) external override locksReentrance allowsPermissionedVaultAction {
require(
_extension == getFeeManager() ||
_extension == getIntegrationManager() ||
_extension == getExternalPositionManager(),
"callOnExtension: _extension invalid"
);
IExtension(_extension).receiveCallFromComptroller(__msgSender(), _actionId, _callArgs);
}
/// @notice Makes an arbitrary call with the VaultProxy contract as the sender
/// @param _contract The contract to call
/// @param _selector The selector to call
/// @param _encodedArgs The encoded arguments for the call
/// @return returnData_ The data returned by the call
function vaultCallOnContract(
address _contract,
bytes4 _selector,
bytes calldata _encodedArgs
) external onlyOwner returns (bytes memory returnData_) {
require(
IFundDeployer(getFundDeployer()).isAllowedVaultCall(
_contract,
_selector,
keccak256(_encodedArgs)
),
"vaultCallOnContract: Not allowed"
);
return
IVault(getVaultProxy()).callOnContract(
_contract,
abi.encodePacked(_selector, _encodedArgs)
);
}
/// @dev Helper to check if a VaultProxy has a pending migration or reconfiguration request
function __hasPendingMigrationOrReconfiguration(address _vaultProxy)
private
view
returns (bool hasPendingMigrationOrReconfiguration)
{
return
IDispatcher(getDispatcher()).hasMigrationRequest(_vaultProxy) ||
IFundDeployer(getFundDeployer()).hasReconfigurationRequest(_vaultProxy);
}
//////////////////
// PROTOCOL FEE //
//////////////////
/// @notice Buys back shares collected as protocol fee at a discounted shares price, using MLN
/// @param _sharesAmount The amount of shares to buy back
function buyBackProtocolFeeShares(uint256 _sharesAmount) external {
address vaultProxyCopy = vaultProxy;
require(
IVault(vaultProxyCopy).canManageAssets(__msgSender()),
"buyBackProtocolFeeShares: Unauthorized"
);
uint256 gav = calcGav();
IVault(vaultProxyCopy).buyBackProtocolFeeShares(
_sharesAmount,
__getBuybackValueInMln(vaultProxyCopy, _sharesAmount, gav),
gav
);
}
/// @notice Sets whether to attempt to buyback protocol fee shares immediately when collected
/// @param _nextAutoProtocolFeeSharesBuyback True if protocol fee shares should be attempted
/// to be bought back immediately when collected
function setAutoProtocolFeeSharesBuyback(bool _nextAutoProtocolFeeSharesBuyback)
external
onlyOwner
{
autoProtocolFeeSharesBuyback = _nextAutoProtocolFeeSharesBuyback;
emit AutoProtocolFeeSharesBuybackSet(_nextAutoProtocolFeeSharesBuyback);
}
/// @dev Helper to buyback the max available protocol fee shares, during an auto-buyback
function __buyBackMaxProtocolFeeShares(address _vaultProxy, uint256 _gav) private {
uint256 sharesAmount = ERC20(_vaultProxy).balanceOf(getProtocolFeeReserve());
uint256 buybackValueInMln = __getBuybackValueInMln(_vaultProxy, sharesAmount, _gav);
try
IVault(_vaultProxy).buyBackProtocolFeeShares(sharesAmount, buybackValueInMln, _gav)
{} catch (bytes memory reason) {
emit BuyBackMaxProtocolFeeSharesFailed(reason, sharesAmount, buybackValueInMln, _gav);
}
}
| 68,458 |
8 | // Override in derived contracts to perform some action before the cache is updated. This is typically relevantto Pools that incur protocol debt between operations. To avoid altering the amount due retroactively, this debtneeds to be paid before the fee percentages change. / | function _beforeProtocolFeeCacheUpdate() internal virtual {
// solhint-disable-previous-line no-empty-blocks
}
| function _beforeProtocolFeeCacheUpdate() internal virtual {
// solhint-disable-previous-line no-empty-blocks
}
| 18,955 |
22 | // If sender didn't vote before and has a delegateif (!resolution.hasVoted[_msgSender()]) { Did sender's delegate vote? | if (
resolution.hasVoted[delegate] &&
resolution.hasVotedYes[delegate]
) {
resolution.yesVotesTotal -= votingPower;
}
| if (
resolution.hasVoted[delegate] &&
resolution.hasVotedYes[delegate]
) {
resolution.yesVotesTotal -= votingPower;
}
| 8,776 |
111 | // collect liquidity share | (amount0, amount1) = pool.collect(
to,
tickLower,
tickUpper,
amount0.toUint128(),
amount1.toUint128()
);
| (amount0, amount1) = pool.collect(
to,
tickLower,
tickUpper,
amount0.toUint128(),
amount1.toUint128()
);
| 42,867 |
7 | // Move to the next sale phase | function nextSalePhase() public onlyOwner {
require(salePhase < 5, "Sale phase is already at the end");
salePhase += 1;
}
| function nextSalePhase() public onlyOwner {
require(salePhase < 5, "Sale phase is already at the end");
salePhase += 1;
}
| 10,697 |
703 | // Remove from inProgressProposals array | _removeFromInProgressProposals(_proposalId);
emit ProposalOutcomeEvaluated(
_proposalId,
outcome,
proposals[_proposalId].voteMagnitudeYes,
proposals[_proposalId].voteMagnitudeNo,
proposals[_proposalId].numVotes
);
| _removeFromInProgressProposals(_proposalId);
emit ProposalOutcomeEvaluated(
_proposalId,
outcome,
proposals[_proposalId].voteMagnitudeYes,
proposals[_proposalId].voteMagnitudeNo,
proposals[_proposalId].numVotes
);
| 45,533 |
22 | // special case for selling the entire supply | if (_sellAmount == _supply)
return _connectorBalance;
| if (_sellAmount == _supply)
return _connectorBalance;
| 23,233 |
26 | // Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.newPendingAdmin New pending admin./ | function _setPendingAdmin(address newPendingAdmin) public {
// Check caller = admin
require(msg.sender == admin, "GovernorBravoDelegator:_setPendingAdmin: admin only");
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
}
| function _setPendingAdmin(address newPendingAdmin) public {
// Check caller = admin
require(msg.sender == admin, "GovernorBravoDelegator:_setPendingAdmin: admin only");
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
}
| 28,571 |
12 | // 0 and 2n - 1 | require(decimalValue < 256);
bytes1 b = bytes1(decimalValue);
c = new bytes(1);
for (uint i=0; i < 1; i++) {
c[i] = b[i];
}
| require(decimalValue < 256);
bytes1 b = bytes1(decimalValue);
c = new bytes(1);
for (uint i=0; i < 1; i++) {
c[i] = b[i];
}
| 49,183 |
14 | // SAKE tokens created per block for trade mining. | uint256 public sakePerBlockTradeMining = 10 * 10**18;
| uint256 public sakePerBlockTradeMining = 10 * 10**18;
| 53,572 |
36 | // BOA-TOKEN <- Sell taxed TOKEN-BOA <- Buy (not taxed) |
function transfer(address to, uint256 value)
public
|
function transfer(address to, uint256 value)
public
| 26,972 |
134 | // Sha3 is cheaper than sha256, make use of it | let hash := keccak256(0, 64)
| let hash := keccak256(0, 64)
| 48,595 |
225 | // bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58ebytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432abytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6 => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^ 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26 / | bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
| bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
| 21,613 |
345 | // A container for all Vaults Vaults are created and managed here Because Ethereum transactions are so expensive,we reinvent an OO system in this code. There are 4 primaryfunctions: deposit, withdraw: investors can add remove funds into aparticular tranche in a Vault.invest, redeem: a strategist pushes the Vault to buy/sell LP tokens inan underlying AMM / | contract AllPairVault is OndoRegistryClient, IPairVault {
using OLib for OLib.Investor;
using SafeERC20 for IERC20;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
// A Vault object is parameterized by these values.
struct Vault {
mapping(OLib.Tranche => Asset) assets; // Assets corresponding to each tranche
IStrategy strategy; // Shared contract that interacts with AMMs
address creator; // Account that calls createVault
address strategist; // Has the right to call invest() and redeem(), and harvest() if strategy supports it
address rollover; // Manager of investment auto-rollover, if any
uint256 rolloverId;
uint256 hurdleRate; // Return offered to senior tranche
OLib.State state; // Current state of Vault
uint256 startAt; // Time when the Vault is unpaused to begin accepting deposits
uint256 investAt; // Time when investors can't move funds, strategist can invest
uint256 redeemAt; // Time when strategist can redeem LP tokens, investors can withdraw
uint256 performanceFee; // Optional fee on junior tranche goes to strategist
}
// (TrancheToken address => (investor address => OLib.Investor)
mapping(address => mapping(address => OLib.Investor)) investors;
// An instance of TrancheToken from which all other tokens are cloned
address public immutable trancheTokenImpl;
// Address that collects performance fees
IFeeCollector public performanceFeeCollector;
// Locate Vault by hashing metadata about the product
mapping(uint256 => Vault) private Vaults;
// Locate Vault by starting from the TrancheToken address
mapping(address => uint256) public VaultsByTokens;
// All Vault IDs
EnumerableSet.UintSet private vaultIDs;
// Access restriction to registered strategist
modifier onlyStrategist(uint256 _vaultId) {
require(msg.sender == Vaults[_vaultId].strategist, "Invalid caller");
_;
}
// Access restriction to registered rollover
modifier onlyRollover(uint256 _vaultId, uint256 _rolloverId) {
Vault storage vault_ = Vaults[_vaultId];
require(
msg.sender == vault_.rollover && _rolloverId == vault_.rolloverId,
"Invalid caller"
);
_;
}
// Access is only rollover if rollover addr nonzero, else strategist
modifier onlyRolloverOrStrategist(uint256 _vaultId) {
Vault storage vault_ = Vaults[_vaultId];
address rollover = vault_.rollover;
require(
(rollover == address(0) && msg.sender == vault_.strategist) ||
(msg.sender == rollover),
"Invalid caller"
);
_;
}
// Guard functions with state machine
modifier atState(uint256 _vaultId, OLib.State _state) {
require(getState(_vaultId) == _state, "Invalid operation");
_;
}
// Determine if one can move to a new state. For now the transitions
// are strictly linear. No state machines, really.
function transition(uint256 _vaultId, OLib.State _nextState) private {
Vault storage vault_ = Vaults[_vaultId];
OLib.State curState = vault_.state;
if (_nextState == OLib.State.Live) {
require(curState == OLib.State.Deposit, "Invalid operation");
require(vault_.investAt <= block.timestamp, "Not time yet");
} else {
require(
curState == OLib.State.Live && _nextState == OLib.State.Withdraw,
"Invalid operation"
);
require(vault_.redeemAt <= block.timestamp, "Not time yet");
}
vault_.state = _nextState;
}
// Determine if a Vault can shift to an open state. A Vault is started
// in an inactive state. It can only move forward when time has
// moved past the starttime.
function maybeOpenDeposit(uint256 _vaultId) private {
Vault storage vault_ = Vaults[_vaultId];
if (vault_.state == OLib.State.Inactive) {
require(
vault_.startAt > 0 && vault_.startAt <= block.timestamp,
"Not time yet"
);
vault_.state = OLib.State.Deposit;
} else if (vault_.state != OLib.State.Deposit) {
revert("Invalid operation");
}
}
// modifier onlyETH(uint256 _vaultId, OLib.Tranche _tranche) {
// require(
// address((getVaultById(_vaultId)).assets[uint256(_tranche)].token) ==
// address(registry.weth()),
// "Not an ETH vault"
// );
// _;
// }
function onlyETH(uint256 _vaultId, OLib.Tranche _tranche) private view {
require(
address((getVaultById(_vaultId)).assets[uint256(_tranche)].token) ==
address(registry.weth()),
"Not an ETH vault"
);
}
/**
* Event declarations
*/
event CreatedPair(
uint256 indexed vaultId,
IERC20 indexed seniorAsset,
IERC20 indexed juniorAsset,
ITrancheToken seniorToken,
ITrancheToken juniorToken
);
event SetRollover(
address indexed rollover,
uint256 indexed rolloverId,
uint256 indexed vaultId
);
event Deposited(
address indexed depositor,
uint256 indexed vaultId,
uint256 indexed trancheId,
uint256 amount
);
event Invested(
uint256 indexed vaultId,
uint256 seniorAmount,
uint256 juniorAmount
);
event DepositedLP(
address indexed depositor,
uint256 indexed vaultId,
uint256 amount,
uint256 senior,
uint256 junior
);
event RolloverDeposited(
address indexed rollover,
uint256 indexed rolloverId,
uint256 indexed vaultId,
uint256 seniorAmount,
uint256 juniorAmount
);
event Claimed(
address indexed depositor,
uint256 indexed vaultId,
uint256 indexed trancheId,
uint256 shares,
uint256 excess
);
event RolloverClaimed(
address indexed rollover,
uint256 indexed rolloverId,
uint256 indexed vaultId,
uint256 seniorAmount,
uint256 juniorAmount
);
event Redeemed(
uint256 indexed vaultId,
uint256 seniorReceived,
uint256 juniorReceived
);
event Withdrew(
address indexed depositor,
uint256 indexed vaultId,
uint256 indexed trancheId,
uint256 amount
);
event WithdrewLP(address indexed depositor, uint256 amount);
event PerformanceFeeSet(uint256 indexed vaultId, uint256 fee);
event PerformanceFeeCollectorSet(address indexed collector);
/**
* @notice Container points back to registry
* @dev Hook up this contract to the global registry.
*/
constructor(address _registry, address _trancheTokenImpl)
OndoRegistryClient(_registry)
{
require(_trancheTokenImpl != address(0), "Invalid target");
trancheTokenImpl = _trancheTokenImpl;
}
/**
* @notice Initialize parameters for a Vault
* @dev
* @param _params Struct with all initialization info
* @return vaultId hashed identifier of Vault used everywhere
**/
function createVault(OLib.VaultParams calldata _params)
external
override
whenNotPaused
isAuthorized(OLib.CREATOR_ROLE)
nonReentrant
returns (uint256 vaultId)
{
require(
registry.authorized(OLib.STRATEGY_ROLE, _params.strategy),
"Invalid target"
);
require(
registry.authorized(OLib.STRATEGIST_ROLE, _params.strategist),
"Invalid target"
);
require(_params.startTime >= block.timestamp, "Invalid start time");
require(
_params.enrollment > 0 && _params.duration > 0,
"No zero intervals"
);
require(_params.hurdleRate < 1e8, "Maximum hurdle is 10000%");
require(denominator <= _params.hurdleRate, "Min hurdle is 100%");
require(
_params.seniorAsset != address(0) &&
_params.seniorAsset != address(this) &&
_params.juniorAsset != address(0) &&
_params.juniorAsset != address(this),
"Invalid target"
);
uint256 investAtTime = _params.startTime + _params.enrollment;
uint256 redeemAtTime = investAtTime + _params.duration;
TrancheToken seniorITrancheToken;
TrancheToken juniorITrancheToken;
{
vaultId = uint256(
keccak256(
abi.encode(
_params.seniorAsset,
_params.juniorAsset,
_params.strategy,
_params.hurdleRate,
_params.startTime,
investAtTime,
redeemAtTime
)
)
);
vaultIDs.add(vaultId);
Vault storage vault_ = Vaults[vaultId];
require(address(vault_.strategist) == address(0), "Duplicate");
vault_.strategy = IStrategy(_params.strategy);
vault_.creator = msg.sender;
vault_.strategist = _params.strategist;
vault_.hurdleRate = _params.hurdleRate;
vault_.startAt = _params.startTime;
vault_.investAt = investAtTime;
vault_.redeemAt = redeemAtTime;
registry.recycleDeadTokens(2);
seniorITrancheToken = TrancheToken(
Clones.cloneDeterministic(
trancheTokenImpl,
keccak256(abi.encodePacked(uint256(0), vaultId))
)
);
juniorITrancheToken = TrancheToken(
Clones.cloneDeterministic(
trancheTokenImpl,
keccak256(abi.encodePacked(uint256(1), vaultId))
)
);
vault_.assets[OLib.Tranche.Senior].token = IERC20(_params.seniorAsset);
vault_.assets[OLib.Tranche.Junior].token = IERC20(_params.juniorAsset);
vault_.assets[OLib.Tranche.Senior].trancheToken = seniorITrancheToken;
vault_.assets[OLib.Tranche.Junior].trancheToken = juniorITrancheToken;
vault_.assets[OLib.Tranche.Senior].trancheCap = _params.seniorTrancheCap;
vault_.assets[OLib.Tranche.Senior].userCap = _params.seniorUserCap;
vault_.assets[OLib.Tranche.Junior].trancheCap = _params.juniorTrancheCap;
vault_.assets[OLib.Tranche.Junior].userCap = _params.juniorUserCap;
VaultsByTokens[address(seniorITrancheToken)] = vaultId;
VaultsByTokens[address(juniorITrancheToken)] = vaultId;
if (vault_.startAt == block.timestamp) {
vault_.state = OLib.State.Deposit;
}
IStrategy(_params.strategy).addVault(
vaultId,
IERC20(_params.seniorAsset),
IERC20(_params.juniorAsset)
);
seniorITrancheToken.initialize(
vaultId,
_params.seniorName,
_params.seniorSym,
address(this)
);
juniorITrancheToken.initialize(
vaultId,
_params.juniorName,
_params.juniorSym,
address(this)
);
}
emit CreatedPair(
vaultId,
IERC20(_params.seniorAsset),
IERC20(_params.juniorAsset),
seniorITrancheToken,
juniorITrancheToken
);
}
/**
* @notice Set the rollover details for a Vault
* @dev
* @param _vaultId Vault to update
* @param _rollover Account of approved rollover agent
* @param _rolloverId Rollover fund in RolloverVault
*/
function setRollover(
uint256 _vaultId,
address _rollover,
uint256 _rolloverId
) external override isAuthorized(OLib.ROLLOVER_ROLE) {
Vault storage vault_ = Vaults[_vaultId];
if (vault_.rollover != address(0)) {
require(
msg.sender == vault_.rollover && _rolloverId == vault_.rolloverId,
"Invalid caller"
);
}
vault_.rollover = _rollover;
vault_.rolloverId = _rolloverId;
emit SetRollover(_rollover, _rolloverId, _vaultId);
}
/** @dev Enforce cap on user investment if any
*/
function depositCapGuard(uint256 _allowedAmount, uint256 _amount)
internal
pure
{
require(
_allowedAmount == 0 || _amount <= _allowedAmount,
"Exceeds user cap"
);
}
/**
* @notice Deposit funds into specific tranche of specific Vault
* @dev OLib.Tranche balances are maintained by a unique ERC20 contract
* @param _vaultId Specific ID for this Vault
* @param _tranche Tranche to be deposited in
* @param _amount Amount of tranche asset to transfer to the strategy contract
*/
function _deposit(
uint256 _vaultId,
OLib.Tranche _tranche,
uint256 _amount,
address _payer
) internal whenNotPaused {
maybeOpenDeposit(_vaultId);
Vault storage vault_ = Vaults[_vaultId];
vault_.assets[_tranche].token.safeTransferFrom(
_payer,
address(vault_.strategy),
_amount
);
uint256 _total = vault_.assets[_tranche].deposited += _amount;
OLib.Investor storage _investor =
investors[address(vault_.assets[_tranche].trancheToken)][msg.sender];
uint256 userSum =
_investor.userSums.length > 0
? _investor.userSums[_investor.userSums.length - 1] + _amount
: _amount;
depositCapGuard(vault_.assets[_tranche].userCap, userSum);
_investor.prefixSums.push(_total);
_investor.userSums.push(userSum);
emit Deposited(msg.sender, _vaultId, uint256(_tranche), _amount);
}
function deposit(
uint256 _vaultId,
OLib.Tranche _tranche,
uint256 _amount
) external override nonReentrant {
_deposit(_vaultId, _tranche, _amount, msg.sender);
}
function depositETH(uint256 _vaultId, OLib.Tranche _tranche)
external
payable
override
nonReentrant
{
onlyETH(_vaultId, _tranche);
registry.weth().deposit{value: msg.value}();
_deposit(_vaultId, _tranche, msg.value, address(this));
}
/**
* @notice Called by rollover to deposit funds
* @dev Rollover gets priority over other depositors.
* @param _vaultId Vault to work on
* @param _rolloverId Rollover that is depositing funds
* @param _seniorAmount Total available amount of assets
* @param _juniorAmount Total available amount of assets
*/
function depositFromRollover(
uint256 _vaultId,
uint256 _rolloverId,
uint256 _seniorAmount,
uint256 _juniorAmount
)
external
override
onlyRollover(_vaultId, _rolloverId)
whenNotPaused
nonReentrant
{
maybeOpenDeposit(_vaultId);
Vault storage vault_ = Vaults[_vaultId];
Asset storage senior_ = vault_.assets[OLib.Tranche.Senior];
Asset storage junior_ = vault_.assets[OLib.Tranche.Junior];
senior_.deposited += _seniorAmount;
junior_.deposited += _juniorAmount;
senior_.rolloverDeposited += _seniorAmount;
junior_.rolloverDeposited += _juniorAmount;
senior_.token.safeTransferFrom(
msg.sender,
address(vault_.strategy),
_seniorAmount
);
junior_.token.safeTransferFrom(
msg.sender,
address(vault_.strategy),
_juniorAmount
);
emit RolloverDeposited(
msg.sender,
_rolloverId,
_vaultId,
_seniorAmount,
_juniorAmount
);
}
/**
* @notice Deposit more LP tokens into a Vault that is live
* @dev When a Vault is created it establishes a ratio between
* senior/junior tranche tokens per LP token. If LP tokens are added
* while the Vault is running, it will get the same ratio of tranche
* tokens in return, regardless of the current balance in the pool.
* @param _vaultId reference to Vault
* @param _lpTokens Amount of LP tokens to provide
*/
function depositLp(uint256 _vaultId, uint256 _lpTokens)
external
override
whenNotPaused
nonReentrant
atState(_vaultId, OLib.State.Live)
returns (uint256 seniorTokensOwed, uint256 juniorTokensOwed)
{
require(registry.tokenMinting(), "Vault tokens inactive");
Vault storage vault_ = Vaults[_vaultId];
IERC20 pool;
(seniorTokensOwed, juniorTokensOwed, pool) = getDepositLp(
_vaultId,
_lpTokens
);
depositCapGuard(
vault_.assets[OLib.Tranche.Senior].userCap,
seniorTokensOwed
);
depositCapGuard(
vault_.assets[OLib.Tranche.Junior].userCap,
juniorTokensOwed
);
vault_.assets[OLib.Tranche.Senior].totalInvested += seniorTokensOwed;
vault_.assets[OLib.Tranche.Junior].totalInvested += juniorTokensOwed;
vault_.assets[OLib.Tranche.Senior].trancheToken.mint(
msg.sender,
seniorTokensOwed
);
vault_.assets[OLib.Tranche.Junior].trancheToken.mint(
msg.sender,
juniorTokensOwed
);
pool.safeTransferFrom(msg.sender, address(vault_.strategy), _lpTokens);
vault_.strategy.addLp(_vaultId, _lpTokens);
emit DepositedLP(
msg.sender,
_vaultId,
_lpTokens,
seniorTokensOwed,
juniorTokensOwed
);
}
function getDepositLp(uint256 _vaultId, uint256 _lpTokens)
public
view
atState(_vaultId, OLib.State.Live)
returns (
uint256 seniorTokensOwed,
uint256 juniorTokensOwed,
IERC20 pool
)
{
Vault storage vault_ = Vaults[_vaultId];
(uint256 shares, uint256 vaultShares, IERC20 ammPool) =
vault_.strategy.sharesFromLp(_vaultId, _lpTokens);
seniorTokensOwed =
(vault_.assets[OLib.Tranche.Senior].totalInvested * shares) /
vaultShares;
juniorTokensOwed =
(vault_.assets[OLib.Tranche.Junior].totalInvested * shares) /
vaultShares;
pool = ammPool;
}
/**
* @notice Invest funds into AMM
* @dev Push deposited funds into underlying strategy contract
* @param _vaultId Specific id for this Vault
* @param _seniorMinIn To ensure you get a decent price
* @param _juniorMinIn Same. Passed to addLiquidity on AMM
*
*/
function invest(
uint256 _vaultId,
uint256 _seniorMinIn,
uint256 _juniorMinIn
)
external
override
whenNotPaused
nonReentrant
onlyRolloverOrStrategist(_vaultId)
returns (uint256, uint256)
{
transition(_vaultId, OLib.State.Live);
Vault storage vault_ = Vaults[_vaultId];
investIntoStrategy(vault_, _vaultId, _seniorMinIn, _juniorMinIn);
Asset storage senior_ = vault_.assets[OLib.Tranche.Senior];
Asset storage junior_ = vault_.assets[OLib.Tranche.Junior];
senior_.totalInvested = vault_.assets[OLib.Tranche.Senior].originalInvested;
junior_.totalInvested = vault_.assets[OLib.Tranche.Junior].originalInvested;
emit Invested(_vaultId, senior_.totalInvested, junior_.totalInvested);
return (senior_.totalInvested, junior_.totalInvested);
}
/*
* @dev Separate investable amount calculation and strategy call from storage updates
to keep the stack down.
*/
function investIntoStrategy(
Vault storage vault_,
uint256 _vaultId,
uint256 _seniorMinIn,
uint256 _juniorMinIn
) private {
uint256 seniorInvestableAmount =
vault_.assets[OLib.Tranche.Senior].deposited;
uint256 seniorCappedAmount = seniorInvestableAmount;
if (vault_.assets[OLib.Tranche.Senior].trancheCap > 0) {
seniorCappedAmount = min(
seniorInvestableAmount,
vault_.assets[OLib.Tranche.Senior].trancheCap
);
}
uint256 juniorInvestableAmount =
vault_.assets[OLib.Tranche.Junior].deposited;
uint256 juniorCappedAmount = juniorInvestableAmount;
if (vault_.assets[OLib.Tranche.Junior].trancheCap > 0) {
juniorCappedAmount = min(
juniorInvestableAmount,
vault_.assets[OLib.Tranche.Junior].trancheCap
);
}
(
vault_.assets[OLib.Tranche.Senior].originalInvested,
vault_.assets[OLib.Tranche.Junior].originalInvested
) = vault_.strategy.invest(
_vaultId,
seniorCappedAmount,
juniorCappedAmount,
seniorInvestableAmount - seniorCappedAmount,
juniorInvestableAmount - juniorCappedAmount,
_seniorMinIn,
_juniorMinIn
);
}
/**
* @notice Return undeposited funds and trigger minting in Tranche Token
* @dev Because the tranches must be balanced to buy LP tokens at
* the right ratio, it is likely that some deposits will not be
* accepted. This function transfers that "excess" deposit. Also, it
* finally mints the tranche tokens for this customer.
* @param _vaultId Reference to specific Vault
* @param _tranche which tranche to act on
* @return userInvested Total amount actually invested from this tranche
* @return excess Any uninvested funds
*/
function _claim(
uint256 _vaultId,
OLib.Tranche _tranche,
address _receiver
)
internal
whenNotPaused
atState(_vaultId, OLib.State.Live)
returns (uint256 userInvested, uint256 excess)
{
Vault storage vault_ = Vaults[_vaultId];
Asset storage _asset = vault_.assets[_tranche];
ITrancheToken _trancheToken = _asset.trancheToken;
OLib.Investor storage investor =
investors[address(_trancheToken)][msg.sender];
require(!investor.claimed, "Already claimed");
IStrategy _strategy = vault_.strategy;
(userInvested, excess) = investor.getInvestedAndExcess(
_getNetOriginalInvested(_asset)
);
if (excess > 0)
_strategy.withdrawExcess(_vaultId, _tranche, _receiver, excess);
if (registry.tokenMinting()) {
_trancheToken.mint(msg.sender, userInvested);
}
investor.claimed = true;
emit Claimed(msg.sender, _vaultId, uint256(_tranche), userInvested, excess);
return (userInvested, excess);
}
function claim(uint256 _vaultId, OLib.Tranche _tranche)
external
override
nonReentrant
returns (uint256, uint256)
{
return _claim(_vaultId, _tranche, msg.sender);
}
function claimETH(uint256 _vaultId, OLib.Tranche _tranche)
external
override
nonReentrant
returns (uint256 invested, uint256 excess)
{
onlyETH(_vaultId, _tranche);
(invested, excess) = _claim(_vaultId, _tranche, address(this));
registry.weth().withdraw(excess);
safeTransferETH(msg.sender, excess);
}
/**
* @notice Called by rollover to claim both tranches
* @dev Triggers minting of tranche tokens. Moves excess to Rollover.
* @param _vaultId Vault id
* @param _rolloverId Rollover ID
* @return srRollInv Amount invested in tranche
* @return jrRollInv Amount invested in tranche
*/
function rolloverClaim(uint256 _vaultId, uint256 _rolloverId)
external
override
whenNotPaused
nonReentrant
atState(_vaultId, OLib.State.Live)
onlyRollover(_vaultId, _rolloverId)
returns (uint256 srRollInv, uint256 jrRollInv)
{
Vault storage vault_ = Vaults[_vaultId];
Asset storage senior_ = vault_.assets[OLib.Tranche.Senior];
Asset storage junior_ = vault_.assets[OLib.Tranche.Junior];
srRollInv = _getRolloverInvested(senior_);
jrRollInv = _getRolloverInvested(junior_);
if (srRollInv > 0) {
senior_.trancheToken.mint(msg.sender, srRollInv);
}
if (jrRollInv > 0) {
junior_.trancheToken.mint(msg.sender, jrRollInv);
}
if (senior_.rolloverDeposited > srRollInv) {
vault_.strategy.withdrawExcess(
_vaultId,
OLib.Tranche.Senior,
msg.sender,
senior_.rolloverDeposited - srRollInv
);
}
if (junior_.rolloverDeposited > jrRollInv) {
vault_.strategy.withdrawExcess(
_vaultId,
OLib.Tranche.Junior,
msg.sender,
junior_.rolloverDeposited - jrRollInv
);
}
emit RolloverClaimed(
msg.sender,
_rolloverId,
_vaultId,
srRollInv,
jrRollInv
);
return (srRollInv, jrRollInv);
}
/**
* @notice Redeem funds into AMM
* @dev Exchange LP tokens for senior/junior assets. Compute the amount
* the senior tranche should get (like 10% more). The senior._received
* value should be equal to or less than that expected amount. The
* junior.received should be all that's left.
* @param _vaultId Specific id for this Vault
* @param _seniorMinReceived Compute total expected to redeem, factoring in slippage
* @param _juniorMinReceived Same.
*/
function redeem(
uint256 _vaultId,
uint256 _seniorMinReceived,
uint256 _juniorMinReceived
)
external
override
whenNotPaused
nonReentrant
onlyRolloverOrStrategist(_vaultId)
returns (uint256, uint256)
{
transition(_vaultId, OLib.State.Withdraw);
Vault storage vault_ = Vaults[_vaultId];
Asset storage senior_ = vault_.assets[OLib.Tranche.Senior];
Asset storage junior_ = vault_.assets[OLib.Tranche.Junior];
(senior_.received, junior_.received) = vault_.strategy.redeem(
_vaultId,
_getSeniorExpected(vault_, senior_),
_seniorMinReceived,
_juniorMinReceived
);
junior_.received -= takePerformanceFee(vault_, _vaultId);
emit Redeemed(_vaultId, senior_.received, junior_.received);
return (senior_.received, junior_.received);
}
/**
* @notice Investors withdraw funds from Vault
* @dev Based on the fraction of ownership in the original pool of invested assets,
investors get the same fraction of the resulting pile of assets. All funds are withdrawn.
* @param _vaultId Specific ID for this Vault
* @param _tranche Tranche to be deposited in
* @return tokensToWithdraw Amount investor received from transfer
*/
function _withdraw(
uint256 _vaultId,
OLib.Tranche _tranche,
address _receiver
)
internal
whenNotPaused
atState(_vaultId, OLib.State.Withdraw)
returns (uint256 tokensToWithdraw)
{
Vault storage vault_ = Vaults[_vaultId];
Asset storage asset_ = vault_.assets[_tranche];
(, , , tokensToWithdraw) = vaultInvestor(_vaultId, _tranche);
ITrancheToken token_ = asset_.trancheToken;
if (registry.tokenMinting()) {
uint256 bal = token_.balanceOf(msg.sender);
if (bal > 0) {
token_.burn(msg.sender, bal);
}
}
asset_.token.safeTransferFrom(
address(vault_.strategy),
_receiver,
tokensToWithdraw
);
investors[address(asset_.trancheToken)][msg.sender].withdrawn = true;
emit Withdrew(msg.sender, _vaultId, uint256(_tranche), tokensToWithdraw);
return tokensToWithdraw;
}
function withdraw(uint256 _vaultId, OLib.Tranche _tranche)
external
override
nonReentrant
returns (uint256)
{
return _withdraw(_vaultId, _tranche, msg.sender);
}
function withdrawETH(uint256 _vaultId, OLib.Tranche _tranche)
external
override
nonReentrant
returns (uint256 amount)
{
onlyETH(_vaultId, _tranche);
amount = _withdraw(_vaultId, _tranche, address(this));
registry.weth().withdraw(amount);
safeTransferETH(msg.sender, amount);
}
receive() external payable {
assert(msg.sender == address(registry.weth()));
}
/**
* @notice Exchange the correct ratio of senior/junior tokens to get LP tokens
* @dev Burn tranche tokens on both sides and send LP tokens to customer
* @param _vaultId reference to Vault
* @param _shares Share of lp tokens to withdraw
*/
function withdrawLp(uint256 _vaultId, uint256 _shares)
external
override
whenNotPaused
nonReentrant
atState(_vaultId, OLib.State.Live)
returns (uint256 seniorTokensNeeded, uint256 juniorTokensNeeded)
{
require(registry.tokenMinting(), "Vault tokens inactive");
Vault storage vault_ = Vaults[_vaultId];
(seniorTokensNeeded, juniorTokensNeeded) = getWithdrawLp(_vaultId, _shares);
vault_.assets[OLib.Tranche.Senior].trancheToken.burn(
msg.sender,
seniorTokensNeeded
);
vault_.assets[OLib.Tranche.Junior].trancheToken.burn(
msg.sender,
juniorTokensNeeded
);
vault_.assets[OLib.Tranche.Senior].totalInvested -= seniorTokensNeeded;
vault_.assets[OLib.Tranche.Junior].totalInvested -= juniorTokensNeeded;
vault_.strategy.removeLp(_vaultId, _shares, msg.sender);
emit WithdrewLP(msg.sender, _shares);
}
function getWithdrawLp(uint256 _vaultId, uint256 _shares)
public
view
atState(_vaultId, OLib.State.Live)
returns (uint256 seniorTokensNeeded, uint256 juniorTokensNeeded)
{
Vault storage vault_ = Vaults[_vaultId];
(, uint256 totalShares) = vault_.strategy.getVaultInfo(_vaultId);
seniorTokensNeeded =
(vault_.assets[OLib.Tranche.Senior].totalInvested * _shares) /
totalShares;
juniorTokensNeeded =
(vault_.assets[OLib.Tranche.Junior].totalInvested * _shares) /
totalShares;
}
function getState(uint256 _vaultId)
public
view
override
returns (OLib.State)
{
Vault storage vault_ = Vaults[_vaultId];
return vault_.state;
}
/**
* Helper functions
*/
/**
* @notice Compute performance fee for strategist
* @dev If junior makes at least as much as the senior, then charge
* a performance fee on junior's earning beyond the hurdle.
* @param vault Vault to work on
* @return fee Amount of tokens deducted from junior tranche
*/
function takePerformanceFee(Vault storage vault, uint256 vaultId)
internal
returns (uint256 fee)
{
fee = 0;
if (address(performanceFeeCollector) != address(0)) {
Asset storage junior = vault.assets[OLib.Tranche.Junior];
uint256 juniorHurdle =
(junior.totalInvested * vault.hurdleRate) / denominator;
if (junior.received > juniorHurdle) {
fee = (vault.performanceFee * (junior.received - juniorHurdle)) / denominator;
IERC20(junior.token).safeTransferFrom(
address(vault.strategy),
address(performanceFeeCollector),
fee
);
performanceFeeCollector.processFee(vaultId, IERC20(junior.token), fee);
}
}
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, "ETH transfer failed");
}
/**
* @notice Multiply senior by hurdle raten
* @param vault Vault to work on
* @param senior Relevant asset
* @return Max value senior can earn for this Vault
*/
function _getSeniorExpected(Vault storage vault, Asset storage senior)
internal
view
returns (uint256)
{
return (senior.totalInvested * vault.hurdleRate) / denominator;
}
function _getNetOriginalInvested(Asset storage asset)
internal
view
returns (uint256)
{
uint256 o = asset.originalInvested;
uint256 r = asset.rolloverDeposited;
return o > r ? o - r : 0;
}
function _getRolloverInvested(Asset storage asset)
internal
view
returns (uint256)
{
uint256 o = asset.originalInvested;
uint256 r = asset.rolloverDeposited;
return o > r ? r : o;
}
/**
* Setters
*/
/**
* @notice Set optional performance fee for Vault
* @dev Only available before deposits are open
* @param _vaultId Vault to work on
* @param _performanceFee Percent fee, denominator is 10000
*/
function setPerformanceFee(uint256 _vaultId, uint256 _performanceFee)
external
onlyStrategist(_vaultId)
atState(_vaultId, OLib.State.Inactive)
{
require(_performanceFee <= denominator, "Too high");
Vault storage vault_ = Vaults[_vaultId];
vault_.performanceFee = _performanceFee;
emit PerformanceFeeSet(_vaultId, _performanceFee);
}
/**
* @notice All performanceFees go this address. Only set by governance role.
* @param _collector Address of collector contract
*/
function setPerformanceFeeCollector(address _collector)
external
isAuthorized(OLib.GOVERNANCE_ROLE)
{
performanceFeeCollector = IFeeCollector(_collector);
emit PerformanceFeeCollectorSet(_collector);
}
function canDeposit(uint256 _vaultId) external view override returns (bool) {
Vault storage vault_ = Vaults[_vaultId];
if (vault_.state == OLib.State.Inactive) {
return vault_.startAt <= block.timestamp && vault_.startAt > 0;
}
return vault_.state == OLib.State.Deposit;
}
function getVaults(uint256 _from, uint256 _to)
external
view
returns (VaultView[] memory vaults)
{
EnumerableSet.UintSet storage vaults_ = vaultIDs;
uint256 len = vaults_.length();
if (len == 0) {
return new VaultView[](0);
}
if (len <= _to) {
_to = len - 1;
}
vaults = new VaultView[](1 + _to - _from);
for (uint256 i = _from; i <= _to; i++) {
vaults[i] = getVaultById(vaults_.at(i));
}
return vaults;
}
function getVaultByToken(address _trancheToken)
external
view
returns (VaultView memory)
{
return getVaultById(VaultsByTokens[_trancheToken]);
}
function getVaultById(uint256 _vaultId)
public
view
override
returns (VaultView memory vault)
{
Vault storage svault_ = Vaults[_vaultId];
mapping(OLib.Tranche => Asset) storage sassets_ = svault_.assets;
Asset[] memory assets = new Asset[](2);
assets[0] = sassets_[OLib.Tranche.Senior];
assets[1] = sassets_[OLib.Tranche.Junior];
vault = VaultView(
_vaultId,
assets,
svault_.strategy,
svault_.creator,
svault_.strategist,
svault_.rollover,
svault_.hurdleRate,
svault_.state,
svault_.startAt,
svault_.investAt,
svault_.redeemAt
);
}
function isPaused() external view override returns (bool) {
return paused();
}
function getRegistry() external view override returns (address) {
return address(registry);
}
function seniorExpected(uint256 _vaultId)
external
view
override
returns (uint256)
{
Vault storage vault_ = Vaults[_vaultId];
Asset storage senior_ = vault_.assets[OLib.Tranche.Senior];
return _getSeniorExpected(vault_, senior_);
}
function getUserCaps(uint256 _vaultId)
external
view
override
returns (uint256 seniorUserCap, uint256 juniorUserCap)
{
Vault storage vault_ = Vaults[_vaultId];
return (
vault_.assets[OLib.Tranche.Senior].userCap,
vault_.assets[OLib.Tranche.Junior].userCap
);
}
/*
* @return position: total user invested = unclaimed invested amount + tranche token balance
* @return claimableBalance: unclaimed invested deposit amount that can be converted into tranche tokens by claiming
* @return withdrawableExcess: unclaimed uninvested deposit amount that can be recovered by claiming
* @return withdrawableBalance: total amount that the user can redeem their position for by withdrawaing, 0 if the product is still live
*/
function vaultInvestor(uint256 _vaultId, OLib.Tranche _tranche)
public
view
override
returns (
uint256 position,
uint256 claimableBalance,
uint256 withdrawableExcess,
uint256 withdrawableBalance
)
{
Asset storage asset_ = Vaults[_vaultId].assets[_tranche];
OLib.Investor storage investor_ =
investors[address(asset_.trancheToken)][msg.sender];
if (!investor_.withdrawn) {
(position, withdrawableExcess) = investor_.getInvestedAndExcess(
_getNetOriginalInvested(asset_)
);
if (!investor_.claimed) {
claimableBalance = position;
position += asset_.trancheToken.balanceOf(msg.sender);
} else {
withdrawableExcess = 0;
if (registry.tokenMinting()) {
position = asset_.trancheToken.balanceOf(msg.sender);
}
}
if (Vaults[_vaultId].state == OLib.State.Withdraw) {
claimableBalance = 0;
withdrawableBalance =
withdrawableExcess +
(asset_.received * position) /
asset_.totalInvested;
}
}
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
| contract AllPairVault is OndoRegistryClient, IPairVault {
using OLib for OLib.Investor;
using SafeERC20 for IERC20;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
// A Vault object is parameterized by these values.
struct Vault {
mapping(OLib.Tranche => Asset) assets; // Assets corresponding to each tranche
IStrategy strategy; // Shared contract that interacts with AMMs
address creator; // Account that calls createVault
address strategist; // Has the right to call invest() and redeem(), and harvest() if strategy supports it
address rollover; // Manager of investment auto-rollover, if any
uint256 rolloverId;
uint256 hurdleRate; // Return offered to senior tranche
OLib.State state; // Current state of Vault
uint256 startAt; // Time when the Vault is unpaused to begin accepting deposits
uint256 investAt; // Time when investors can't move funds, strategist can invest
uint256 redeemAt; // Time when strategist can redeem LP tokens, investors can withdraw
uint256 performanceFee; // Optional fee on junior tranche goes to strategist
}
// (TrancheToken address => (investor address => OLib.Investor)
mapping(address => mapping(address => OLib.Investor)) investors;
// An instance of TrancheToken from which all other tokens are cloned
address public immutable trancheTokenImpl;
// Address that collects performance fees
IFeeCollector public performanceFeeCollector;
// Locate Vault by hashing metadata about the product
mapping(uint256 => Vault) private Vaults;
// Locate Vault by starting from the TrancheToken address
mapping(address => uint256) public VaultsByTokens;
// All Vault IDs
EnumerableSet.UintSet private vaultIDs;
// Access restriction to registered strategist
modifier onlyStrategist(uint256 _vaultId) {
require(msg.sender == Vaults[_vaultId].strategist, "Invalid caller");
_;
}
// Access restriction to registered rollover
modifier onlyRollover(uint256 _vaultId, uint256 _rolloverId) {
Vault storage vault_ = Vaults[_vaultId];
require(
msg.sender == vault_.rollover && _rolloverId == vault_.rolloverId,
"Invalid caller"
);
_;
}
// Access is only rollover if rollover addr nonzero, else strategist
modifier onlyRolloverOrStrategist(uint256 _vaultId) {
Vault storage vault_ = Vaults[_vaultId];
address rollover = vault_.rollover;
require(
(rollover == address(0) && msg.sender == vault_.strategist) ||
(msg.sender == rollover),
"Invalid caller"
);
_;
}
// Guard functions with state machine
modifier atState(uint256 _vaultId, OLib.State _state) {
require(getState(_vaultId) == _state, "Invalid operation");
_;
}
// Determine if one can move to a new state. For now the transitions
// are strictly linear. No state machines, really.
function transition(uint256 _vaultId, OLib.State _nextState) private {
Vault storage vault_ = Vaults[_vaultId];
OLib.State curState = vault_.state;
if (_nextState == OLib.State.Live) {
require(curState == OLib.State.Deposit, "Invalid operation");
require(vault_.investAt <= block.timestamp, "Not time yet");
} else {
require(
curState == OLib.State.Live && _nextState == OLib.State.Withdraw,
"Invalid operation"
);
require(vault_.redeemAt <= block.timestamp, "Not time yet");
}
vault_.state = _nextState;
}
// Determine if a Vault can shift to an open state. A Vault is started
// in an inactive state. It can only move forward when time has
// moved past the starttime.
function maybeOpenDeposit(uint256 _vaultId) private {
Vault storage vault_ = Vaults[_vaultId];
if (vault_.state == OLib.State.Inactive) {
require(
vault_.startAt > 0 && vault_.startAt <= block.timestamp,
"Not time yet"
);
vault_.state = OLib.State.Deposit;
} else if (vault_.state != OLib.State.Deposit) {
revert("Invalid operation");
}
}
// modifier onlyETH(uint256 _vaultId, OLib.Tranche _tranche) {
// require(
// address((getVaultById(_vaultId)).assets[uint256(_tranche)].token) ==
// address(registry.weth()),
// "Not an ETH vault"
// );
// _;
// }
function onlyETH(uint256 _vaultId, OLib.Tranche _tranche) private view {
require(
address((getVaultById(_vaultId)).assets[uint256(_tranche)].token) ==
address(registry.weth()),
"Not an ETH vault"
);
}
/**
* Event declarations
*/
event CreatedPair(
uint256 indexed vaultId,
IERC20 indexed seniorAsset,
IERC20 indexed juniorAsset,
ITrancheToken seniorToken,
ITrancheToken juniorToken
);
event SetRollover(
address indexed rollover,
uint256 indexed rolloverId,
uint256 indexed vaultId
);
event Deposited(
address indexed depositor,
uint256 indexed vaultId,
uint256 indexed trancheId,
uint256 amount
);
event Invested(
uint256 indexed vaultId,
uint256 seniorAmount,
uint256 juniorAmount
);
event DepositedLP(
address indexed depositor,
uint256 indexed vaultId,
uint256 amount,
uint256 senior,
uint256 junior
);
event RolloverDeposited(
address indexed rollover,
uint256 indexed rolloverId,
uint256 indexed vaultId,
uint256 seniorAmount,
uint256 juniorAmount
);
event Claimed(
address indexed depositor,
uint256 indexed vaultId,
uint256 indexed trancheId,
uint256 shares,
uint256 excess
);
event RolloverClaimed(
address indexed rollover,
uint256 indexed rolloverId,
uint256 indexed vaultId,
uint256 seniorAmount,
uint256 juniorAmount
);
event Redeemed(
uint256 indexed vaultId,
uint256 seniorReceived,
uint256 juniorReceived
);
event Withdrew(
address indexed depositor,
uint256 indexed vaultId,
uint256 indexed trancheId,
uint256 amount
);
event WithdrewLP(address indexed depositor, uint256 amount);
event PerformanceFeeSet(uint256 indexed vaultId, uint256 fee);
event PerformanceFeeCollectorSet(address indexed collector);
/**
* @notice Container points back to registry
* @dev Hook up this contract to the global registry.
*/
constructor(address _registry, address _trancheTokenImpl)
OndoRegistryClient(_registry)
{
require(_trancheTokenImpl != address(0), "Invalid target");
trancheTokenImpl = _trancheTokenImpl;
}
/**
* @notice Initialize parameters for a Vault
* @dev
* @param _params Struct with all initialization info
* @return vaultId hashed identifier of Vault used everywhere
**/
function createVault(OLib.VaultParams calldata _params)
external
override
whenNotPaused
isAuthorized(OLib.CREATOR_ROLE)
nonReentrant
returns (uint256 vaultId)
{
require(
registry.authorized(OLib.STRATEGY_ROLE, _params.strategy),
"Invalid target"
);
require(
registry.authorized(OLib.STRATEGIST_ROLE, _params.strategist),
"Invalid target"
);
require(_params.startTime >= block.timestamp, "Invalid start time");
require(
_params.enrollment > 0 && _params.duration > 0,
"No zero intervals"
);
require(_params.hurdleRate < 1e8, "Maximum hurdle is 10000%");
require(denominator <= _params.hurdleRate, "Min hurdle is 100%");
require(
_params.seniorAsset != address(0) &&
_params.seniorAsset != address(this) &&
_params.juniorAsset != address(0) &&
_params.juniorAsset != address(this),
"Invalid target"
);
uint256 investAtTime = _params.startTime + _params.enrollment;
uint256 redeemAtTime = investAtTime + _params.duration;
TrancheToken seniorITrancheToken;
TrancheToken juniorITrancheToken;
{
vaultId = uint256(
keccak256(
abi.encode(
_params.seniorAsset,
_params.juniorAsset,
_params.strategy,
_params.hurdleRate,
_params.startTime,
investAtTime,
redeemAtTime
)
)
);
vaultIDs.add(vaultId);
Vault storage vault_ = Vaults[vaultId];
require(address(vault_.strategist) == address(0), "Duplicate");
vault_.strategy = IStrategy(_params.strategy);
vault_.creator = msg.sender;
vault_.strategist = _params.strategist;
vault_.hurdleRate = _params.hurdleRate;
vault_.startAt = _params.startTime;
vault_.investAt = investAtTime;
vault_.redeemAt = redeemAtTime;
registry.recycleDeadTokens(2);
seniorITrancheToken = TrancheToken(
Clones.cloneDeterministic(
trancheTokenImpl,
keccak256(abi.encodePacked(uint256(0), vaultId))
)
);
juniorITrancheToken = TrancheToken(
Clones.cloneDeterministic(
trancheTokenImpl,
keccak256(abi.encodePacked(uint256(1), vaultId))
)
);
vault_.assets[OLib.Tranche.Senior].token = IERC20(_params.seniorAsset);
vault_.assets[OLib.Tranche.Junior].token = IERC20(_params.juniorAsset);
vault_.assets[OLib.Tranche.Senior].trancheToken = seniorITrancheToken;
vault_.assets[OLib.Tranche.Junior].trancheToken = juniorITrancheToken;
vault_.assets[OLib.Tranche.Senior].trancheCap = _params.seniorTrancheCap;
vault_.assets[OLib.Tranche.Senior].userCap = _params.seniorUserCap;
vault_.assets[OLib.Tranche.Junior].trancheCap = _params.juniorTrancheCap;
vault_.assets[OLib.Tranche.Junior].userCap = _params.juniorUserCap;
VaultsByTokens[address(seniorITrancheToken)] = vaultId;
VaultsByTokens[address(juniorITrancheToken)] = vaultId;
if (vault_.startAt == block.timestamp) {
vault_.state = OLib.State.Deposit;
}
IStrategy(_params.strategy).addVault(
vaultId,
IERC20(_params.seniorAsset),
IERC20(_params.juniorAsset)
);
seniorITrancheToken.initialize(
vaultId,
_params.seniorName,
_params.seniorSym,
address(this)
);
juniorITrancheToken.initialize(
vaultId,
_params.juniorName,
_params.juniorSym,
address(this)
);
}
emit CreatedPair(
vaultId,
IERC20(_params.seniorAsset),
IERC20(_params.juniorAsset),
seniorITrancheToken,
juniorITrancheToken
);
}
/**
* @notice Set the rollover details for a Vault
* @dev
* @param _vaultId Vault to update
* @param _rollover Account of approved rollover agent
* @param _rolloverId Rollover fund in RolloverVault
*/
function setRollover(
uint256 _vaultId,
address _rollover,
uint256 _rolloverId
) external override isAuthorized(OLib.ROLLOVER_ROLE) {
Vault storage vault_ = Vaults[_vaultId];
if (vault_.rollover != address(0)) {
require(
msg.sender == vault_.rollover && _rolloverId == vault_.rolloverId,
"Invalid caller"
);
}
vault_.rollover = _rollover;
vault_.rolloverId = _rolloverId;
emit SetRollover(_rollover, _rolloverId, _vaultId);
}
/** @dev Enforce cap on user investment if any
*/
function depositCapGuard(uint256 _allowedAmount, uint256 _amount)
internal
pure
{
require(
_allowedAmount == 0 || _amount <= _allowedAmount,
"Exceeds user cap"
);
}
/**
* @notice Deposit funds into specific tranche of specific Vault
* @dev OLib.Tranche balances are maintained by a unique ERC20 contract
* @param _vaultId Specific ID for this Vault
* @param _tranche Tranche to be deposited in
* @param _amount Amount of tranche asset to transfer to the strategy contract
*/
function _deposit(
uint256 _vaultId,
OLib.Tranche _tranche,
uint256 _amount,
address _payer
) internal whenNotPaused {
maybeOpenDeposit(_vaultId);
Vault storage vault_ = Vaults[_vaultId];
vault_.assets[_tranche].token.safeTransferFrom(
_payer,
address(vault_.strategy),
_amount
);
uint256 _total = vault_.assets[_tranche].deposited += _amount;
OLib.Investor storage _investor =
investors[address(vault_.assets[_tranche].trancheToken)][msg.sender];
uint256 userSum =
_investor.userSums.length > 0
? _investor.userSums[_investor.userSums.length - 1] + _amount
: _amount;
depositCapGuard(vault_.assets[_tranche].userCap, userSum);
_investor.prefixSums.push(_total);
_investor.userSums.push(userSum);
emit Deposited(msg.sender, _vaultId, uint256(_tranche), _amount);
}
function deposit(
uint256 _vaultId,
OLib.Tranche _tranche,
uint256 _amount
) external override nonReentrant {
_deposit(_vaultId, _tranche, _amount, msg.sender);
}
function depositETH(uint256 _vaultId, OLib.Tranche _tranche)
external
payable
override
nonReentrant
{
onlyETH(_vaultId, _tranche);
registry.weth().deposit{value: msg.value}();
_deposit(_vaultId, _tranche, msg.value, address(this));
}
/**
* @notice Called by rollover to deposit funds
* @dev Rollover gets priority over other depositors.
* @param _vaultId Vault to work on
* @param _rolloverId Rollover that is depositing funds
* @param _seniorAmount Total available amount of assets
* @param _juniorAmount Total available amount of assets
*/
function depositFromRollover(
uint256 _vaultId,
uint256 _rolloverId,
uint256 _seniorAmount,
uint256 _juniorAmount
)
external
override
onlyRollover(_vaultId, _rolloverId)
whenNotPaused
nonReentrant
{
maybeOpenDeposit(_vaultId);
Vault storage vault_ = Vaults[_vaultId];
Asset storage senior_ = vault_.assets[OLib.Tranche.Senior];
Asset storage junior_ = vault_.assets[OLib.Tranche.Junior];
senior_.deposited += _seniorAmount;
junior_.deposited += _juniorAmount;
senior_.rolloverDeposited += _seniorAmount;
junior_.rolloverDeposited += _juniorAmount;
senior_.token.safeTransferFrom(
msg.sender,
address(vault_.strategy),
_seniorAmount
);
junior_.token.safeTransferFrom(
msg.sender,
address(vault_.strategy),
_juniorAmount
);
emit RolloverDeposited(
msg.sender,
_rolloverId,
_vaultId,
_seniorAmount,
_juniorAmount
);
}
/**
* @notice Deposit more LP tokens into a Vault that is live
* @dev When a Vault is created it establishes a ratio between
* senior/junior tranche tokens per LP token. If LP tokens are added
* while the Vault is running, it will get the same ratio of tranche
* tokens in return, regardless of the current balance in the pool.
* @param _vaultId reference to Vault
* @param _lpTokens Amount of LP tokens to provide
*/
function depositLp(uint256 _vaultId, uint256 _lpTokens)
external
override
whenNotPaused
nonReentrant
atState(_vaultId, OLib.State.Live)
returns (uint256 seniorTokensOwed, uint256 juniorTokensOwed)
{
require(registry.tokenMinting(), "Vault tokens inactive");
Vault storage vault_ = Vaults[_vaultId];
IERC20 pool;
(seniorTokensOwed, juniorTokensOwed, pool) = getDepositLp(
_vaultId,
_lpTokens
);
depositCapGuard(
vault_.assets[OLib.Tranche.Senior].userCap,
seniorTokensOwed
);
depositCapGuard(
vault_.assets[OLib.Tranche.Junior].userCap,
juniorTokensOwed
);
vault_.assets[OLib.Tranche.Senior].totalInvested += seniorTokensOwed;
vault_.assets[OLib.Tranche.Junior].totalInvested += juniorTokensOwed;
vault_.assets[OLib.Tranche.Senior].trancheToken.mint(
msg.sender,
seniorTokensOwed
);
vault_.assets[OLib.Tranche.Junior].trancheToken.mint(
msg.sender,
juniorTokensOwed
);
pool.safeTransferFrom(msg.sender, address(vault_.strategy), _lpTokens);
vault_.strategy.addLp(_vaultId, _lpTokens);
emit DepositedLP(
msg.sender,
_vaultId,
_lpTokens,
seniorTokensOwed,
juniorTokensOwed
);
}
function getDepositLp(uint256 _vaultId, uint256 _lpTokens)
public
view
atState(_vaultId, OLib.State.Live)
returns (
uint256 seniorTokensOwed,
uint256 juniorTokensOwed,
IERC20 pool
)
{
Vault storage vault_ = Vaults[_vaultId];
(uint256 shares, uint256 vaultShares, IERC20 ammPool) =
vault_.strategy.sharesFromLp(_vaultId, _lpTokens);
seniorTokensOwed =
(vault_.assets[OLib.Tranche.Senior].totalInvested * shares) /
vaultShares;
juniorTokensOwed =
(vault_.assets[OLib.Tranche.Junior].totalInvested * shares) /
vaultShares;
pool = ammPool;
}
/**
* @notice Invest funds into AMM
* @dev Push deposited funds into underlying strategy contract
* @param _vaultId Specific id for this Vault
* @param _seniorMinIn To ensure you get a decent price
* @param _juniorMinIn Same. Passed to addLiquidity on AMM
*
*/
function invest(
uint256 _vaultId,
uint256 _seniorMinIn,
uint256 _juniorMinIn
)
external
override
whenNotPaused
nonReentrant
onlyRolloverOrStrategist(_vaultId)
returns (uint256, uint256)
{
transition(_vaultId, OLib.State.Live);
Vault storage vault_ = Vaults[_vaultId];
investIntoStrategy(vault_, _vaultId, _seniorMinIn, _juniorMinIn);
Asset storage senior_ = vault_.assets[OLib.Tranche.Senior];
Asset storage junior_ = vault_.assets[OLib.Tranche.Junior];
senior_.totalInvested = vault_.assets[OLib.Tranche.Senior].originalInvested;
junior_.totalInvested = vault_.assets[OLib.Tranche.Junior].originalInvested;
emit Invested(_vaultId, senior_.totalInvested, junior_.totalInvested);
return (senior_.totalInvested, junior_.totalInvested);
}
/*
* @dev Separate investable amount calculation and strategy call from storage updates
to keep the stack down.
*/
function investIntoStrategy(
Vault storage vault_,
uint256 _vaultId,
uint256 _seniorMinIn,
uint256 _juniorMinIn
) private {
uint256 seniorInvestableAmount =
vault_.assets[OLib.Tranche.Senior].deposited;
uint256 seniorCappedAmount = seniorInvestableAmount;
if (vault_.assets[OLib.Tranche.Senior].trancheCap > 0) {
seniorCappedAmount = min(
seniorInvestableAmount,
vault_.assets[OLib.Tranche.Senior].trancheCap
);
}
uint256 juniorInvestableAmount =
vault_.assets[OLib.Tranche.Junior].deposited;
uint256 juniorCappedAmount = juniorInvestableAmount;
if (vault_.assets[OLib.Tranche.Junior].trancheCap > 0) {
juniorCappedAmount = min(
juniorInvestableAmount,
vault_.assets[OLib.Tranche.Junior].trancheCap
);
}
(
vault_.assets[OLib.Tranche.Senior].originalInvested,
vault_.assets[OLib.Tranche.Junior].originalInvested
) = vault_.strategy.invest(
_vaultId,
seniorCappedAmount,
juniorCappedAmount,
seniorInvestableAmount - seniorCappedAmount,
juniorInvestableAmount - juniorCappedAmount,
_seniorMinIn,
_juniorMinIn
);
}
/**
* @notice Return undeposited funds and trigger minting in Tranche Token
* @dev Because the tranches must be balanced to buy LP tokens at
* the right ratio, it is likely that some deposits will not be
* accepted. This function transfers that "excess" deposit. Also, it
* finally mints the tranche tokens for this customer.
* @param _vaultId Reference to specific Vault
* @param _tranche which tranche to act on
* @return userInvested Total amount actually invested from this tranche
* @return excess Any uninvested funds
*/
function _claim(
uint256 _vaultId,
OLib.Tranche _tranche,
address _receiver
)
internal
whenNotPaused
atState(_vaultId, OLib.State.Live)
returns (uint256 userInvested, uint256 excess)
{
Vault storage vault_ = Vaults[_vaultId];
Asset storage _asset = vault_.assets[_tranche];
ITrancheToken _trancheToken = _asset.trancheToken;
OLib.Investor storage investor =
investors[address(_trancheToken)][msg.sender];
require(!investor.claimed, "Already claimed");
IStrategy _strategy = vault_.strategy;
(userInvested, excess) = investor.getInvestedAndExcess(
_getNetOriginalInvested(_asset)
);
if (excess > 0)
_strategy.withdrawExcess(_vaultId, _tranche, _receiver, excess);
if (registry.tokenMinting()) {
_trancheToken.mint(msg.sender, userInvested);
}
investor.claimed = true;
emit Claimed(msg.sender, _vaultId, uint256(_tranche), userInvested, excess);
return (userInvested, excess);
}
function claim(uint256 _vaultId, OLib.Tranche _tranche)
external
override
nonReentrant
returns (uint256, uint256)
{
return _claim(_vaultId, _tranche, msg.sender);
}
function claimETH(uint256 _vaultId, OLib.Tranche _tranche)
external
override
nonReentrant
returns (uint256 invested, uint256 excess)
{
onlyETH(_vaultId, _tranche);
(invested, excess) = _claim(_vaultId, _tranche, address(this));
registry.weth().withdraw(excess);
safeTransferETH(msg.sender, excess);
}
/**
* @notice Called by rollover to claim both tranches
* @dev Triggers minting of tranche tokens. Moves excess to Rollover.
* @param _vaultId Vault id
* @param _rolloverId Rollover ID
* @return srRollInv Amount invested in tranche
* @return jrRollInv Amount invested in tranche
*/
function rolloverClaim(uint256 _vaultId, uint256 _rolloverId)
external
override
whenNotPaused
nonReentrant
atState(_vaultId, OLib.State.Live)
onlyRollover(_vaultId, _rolloverId)
returns (uint256 srRollInv, uint256 jrRollInv)
{
Vault storage vault_ = Vaults[_vaultId];
Asset storage senior_ = vault_.assets[OLib.Tranche.Senior];
Asset storage junior_ = vault_.assets[OLib.Tranche.Junior];
srRollInv = _getRolloverInvested(senior_);
jrRollInv = _getRolloverInvested(junior_);
if (srRollInv > 0) {
senior_.trancheToken.mint(msg.sender, srRollInv);
}
if (jrRollInv > 0) {
junior_.trancheToken.mint(msg.sender, jrRollInv);
}
if (senior_.rolloverDeposited > srRollInv) {
vault_.strategy.withdrawExcess(
_vaultId,
OLib.Tranche.Senior,
msg.sender,
senior_.rolloverDeposited - srRollInv
);
}
if (junior_.rolloverDeposited > jrRollInv) {
vault_.strategy.withdrawExcess(
_vaultId,
OLib.Tranche.Junior,
msg.sender,
junior_.rolloverDeposited - jrRollInv
);
}
emit RolloverClaimed(
msg.sender,
_rolloverId,
_vaultId,
srRollInv,
jrRollInv
);
return (srRollInv, jrRollInv);
}
/**
* @notice Redeem funds into AMM
* @dev Exchange LP tokens for senior/junior assets. Compute the amount
* the senior tranche should get (like 10% more). The senior._received
* value should be equal to or less than that expected amount. The
* junior.received should be all that's left.
* @param _vaultId Specific id for this Vault
* @param _seniorMinReceived Compute total expected to redeem, factoring in slippage
* @param _juniorMinReceived Same.
*/
function redeem(
uint256 _vaultId,
uint256 _seniorMinReceived,
uint256 _juniorMinReceived
)
external
override
whenNotPaused
nonReentrant
onlyRolloverOrStrategist(_vaultId)
returns (uint256, uint256)
{
transition(_vaultId, OLib.State.Withdraw);
Vault storage vault_ = Vaults[_vaultId];
Asset storage senior_ = vault_.assets[OLib.Tranche.Senior];
Asset storage junior_ = vault_.assets[OLib.Tranche.Junior];
(senior_.received, junior_.received) = vault_.strategy.redeem(
_vaultId,
_getSeniorExpected(vault_, senior_),
_seniorMinReceived,
_juniorMinReceived
);
junior_.received -= takePerformanceFee(vault_, _vaultId);
emit Redeemed(_vaultId, senior_.received, junior_.received);
return (senior_.received, junior_.received);
}
/**
* @notice Investors withdraw funds from Vault
* @dev Based on the fraction of ownership in the original pool of invested assets,
investors get the same fraction of the resulting pile of assets. All funds are withdrawn.
* @param _vaultId Specific ID for this Vault
* @param _tranche Tranche to be deposited in
* @return tokensToWithdraw Amount investor received from transfer
*/
function _withdraw(
uint256 _vaultId,
OLib.Tranche _tranche,
address _receiver
)
internal
whenNotPaused
atState(_vaultId, OLib.State.Withdraw)
returns (uint256 tokensToWithdraw)
{
Vault storage vault_ = Vaults[_vaultId];
Asset storage asset_ = vault_.assets[_tranche];
(, , , tokensToWithdraw) = vaultInvestor(_vaultId, _tranche);
ITrancheToken token_ = asset_.trancheToken;
if (registry.tokenMinting()) {
uint256 bal = token_.balanceOf(msg.sender);
if (bal > 0) {
token_.burn(msg.sender, bal);
}
}
asset_.token.safeTransferFrom(
address(vault_.strategy),
_receiver,
tokensToWithdraw
);
investors[address(asset_.trancheToken)][msg.sender].withdrawn = true;
emit Withdrew(msg.sender, _vaultId, uint256(_tranche), tokensToWithdraw);
return tokensToWithdraw;
}
function withdraw(uint256 _vaultId, OLib.Tranche _tranche)
external
override
nonReentrant
returns (uint256)
{
return _withdraw(_vaultId, _tranche, msg.sender);
}
function withdrawETH(uint256 _vaultId, OLib.Tranche _tranche)
external
override
nonReentrant
returns (uint256 amount)
{
onlyETH(_vaultId, _tranche);
amount = _withdraw(_vaultId, _tranche, address(this));
registry.weth().withdraw(amount);
safeTransferETH(msg.sender, amount);
}
receive() external payable {
assert(msg.sender == address(registry.weth()));
}
/**
* @notice Exchange the correct ratio of senior/junior tokens to get LP tokens
* @dev Burn tranche tokens on both sides and send LP tokens to customer
* @param _vaultId reference to Vault
* @param _shares Share of lp tokens to withdraw
*/
function withdrawLp(uint256 _vaultId, uint256 _shares)
external
override
whenNotPaused
nonReentrant
atState(_vaultId, OLib.State.Live)
returns (uint256 seniorTokensNeeded, uint256 juniorTokensNeeded)
{
require(registry.tokenMinting(), "Vault tokens inactive");
Vault storage vault_ = Vaults[_vaultId];
(seniorTokensNeeded, juniorTokensNeeded) = getWithdrawLp(_vaultId, _shares);
vault_.assets[OLib.Tranche.Senior].trancheToken.burn(
msg.sender,
seniorTokensNeeded
);
vault_.assets[OLib.Tranche.Junior].trancheToken.burn(
msg.sender,
juniorTokensNeeded
);
vault_.assets[OLib.Tranche.Senior].totalInvested -= seniorTokensNeeded;
vault_.assets[OLib.Tranche.Junior].totalInvested -= juniorTokensNeeded;
vault_.strategy.removeLp(_vaultId, _shares, msg.sender);
emit WithdrewLP(msg.sender, _shares);
}
function getWithdrawLp(uint256 _vaultId, uint256 _shares)
public
view
atState(_vaultId, OLib.State.Live)
returns (uint256 seniorTokensNeeded, uint256 juniorTokensNeeded)
{
Vault storage vault_ = Vaults[_vaultId];
(, uint256 totalShares) = vault_.strategy.getVaultInfo(_vaultId);
seniorTokensNeeded =
(vault_.assets[OLib.Tranche.Senior].totalInvested * _shares) /
totalShares;
juniorTokensNeeded =
(vault_.assets[OLib.Tranche.Junior].totalInvested * _shares) /
totalShares;
}
function getState(uint256 _vaultId)
public
view
override
returns (OLib.State)
{
Vault storage vault_ = Vaults[_vaultId];
return vault_.state;
}
/**
* Helper functions
*/
/**
* @notice Compute performance fee for strategist
* @dev If junior makes at least as much as the senior, then charge
* a performance fee on junior's earning beyond the hurdle.
* @param vault Vault to work on
* @return fee Amount of tokens deducted from junior tranche
*/
function takePerformanceFee(Vault storage vault, uint256 vaultId)
internal
returns (uint256 fee)
{
fee = 0;
if (address(performanceFeeCollector) != address(0)) {
Asset storage junior = vault.assets[OLib.Tranche.Junior];
uint256 juniorHurdle =
(junior.totalInvested * vault.hurdleRate) / denominator;
if (junior.received > juniorHurdle) {
fee = (vault.performanceFee * (junior.received - juniorHurdle)) / denominator;
IERC20(junior.token).safeTransferFrom(
address(vault.strategy),
address(performanceFeeCollector),
fee
);
performanceFeeCollector.processFee(vaultId, IERC20(junior.token), fee);
}
}
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, "ETH transfer failed");
}
/**
* @notice Multiply senior by hurdle raten
* @param vault Vault to work on
* @param senior Relevant asset
* @return Max value senior can earn for this Vault
*/
function _getSeniorExpected(Vault storage vault, Asset storage senior)
internal
view
returns (uint256)
{
return (senior.totalInvested * vault.hurdleRate) / denominator;
}
function _getNetOriginalInvested(Asset storage asset)
internal
view
returns (uint256)
{
uint256 o = asset.originalInvested;
uint256 r = asset.rolloverDeposited;
return o > r ? o - r : 0;
}
function _getRolloverInvested(Asset storage asset)
internal
view
returns (uint256)
{
uint256 o = asset.originalInvested;
uint256 r = asset.rolloverDeposited;
return o > r ? r : o;
}
/**
* Setters
*/
/**
* @notice Set optional performance fee for Vault
* @dev Only available before deposits are open
* @param _vaultId Vault to work on
* @param _performanceFee Percent fee, denominator is 10000
*/
function setPerformanceFee(uint256 _vaultId, uint256 _performanceFee)
external
onlyStrategist(_vaultId)
atState(_vaultId, OLib.State.Inactive)
{
require(_performanceFee <= denominator, "Too high");
Vault storage vault_ = Vaults[_vaultId];
vault_.performanceFee = _performanceFee;
emit PerformanceFeeSet(_vaultId, _performanceFee);
}
/**
* @notice All performanceFees go this address. Only set by governance role.
* @param _collector Address of collector contract
*/
function setPerformanceFeeCollector(address _collector)
external
isAuthorized(OLib.GOVERNANCE_ROLE)
{
performanceFeeCollector = IFeeCollector(_collector);
emit PerformanceFeeCollectorSet(_collector);
}
function canDeposit(uint256 _vaultId) external view override returns (bool) {
Vault storage vault_ = Vaults[_vaultId];
if (vault_.state == OLib.State.Inactive) {
return vault_.startAt <= block.timestamp && vault_.startAt > 0;
}
return vault_.state == OLib.State.Deposit;
}
function getVaults(uint256 _from, uint256 _to)
external
view
returns (VaultView[] memory vaults)
{
EnumerableSet.UintSet storage vaults_ = vaultIDs;
uint256 len = vaults_.length();
if (len == 0) {
return new VaultView[](0);
}
if (len <= _to) {
_to = len - 1;
}
vaults = new VaultView[](1 + _to - _from);
for (uint256 i = _from; i <= _to; i++) {
vaults[i] = getVaultById(vaults_.at(i));
}
return vaults;
}
function getVaultByToken(address _trancheToken)
external
view
returns (VaultView memory)
{
return getVaultById(VaultsByTokens[_trancheToken]);
}
function getVaultById(uint256 _vaultId)
public
view
override
returns (VaultView memory vault)
{
Vault storage svault_ = Vaults[_vaultId];
mapping(OLib.Tranche => Asset) storage sassets_ = svault_.assets;
Asset[] memory assets = new Asset[](2);
assets[0] = sassets_[OLib.Tranche.Senior];
assets[1] = sassets_[OLib.Tranche.Junior];
vault = VaultView(
_vaultId,
assets,
svault_.strategy,
svault_.creator,
svault_.strategist,
svault_.rollover,
svault_.hurdleRate,
svault_.state,
svault_.startAt,
svault_.investAt,
svault_.redeemAt
);
}
function isPaused() external view override returns (bool) {
return paused();
}
function getRegistry() external view override returns (address) {
return address(registry);
}
function seniorExpected(uint256 _vaultId)
external
view
override
returns (uint256)
{
Vault storage vault_ = Vaults[_vaultId];
Asset storage senior_ = vault_.assets[OLib.Tranche.Senior];
return _getSeniorExpected(vault_, senior_);
}
function getUserCaps(uint256 _vaultId)
external
view
override
returns (uint256 seniorUserCap, uint256 juniorUserCap)
{
Vault storage vault_ = Vaults[_vaultId];
return (
vault_.assets[OLib.Tranche.Senior].userCap,
vault_.assets[OLib.Tranche.Junior].userCap
);
}
/*
* @return position: total user invested = unclaimed invested amount + tranche token balance
* @return claimableBalance: unclaimed invested deposit amount that can be converted into tranche tokens by claiming
* @return withdrawableExcess: unclaimed uninvested deposit amount that can be recovered by claiming
* @return withdrawableBalance: total amount that the user can redeem their position for by withdrawaing, 0 if the product is still live
*/
function vaultInvestor(uint256 _vaultId, OLib.Tranche _tranche)
public
view
override
returns (
uint256 position,
uint256 claimableBalance,
uint256 withdrawableExcess,
uint256 withdrawableBalance
)
{
Asset storage asset_ = Vaults[_vaultId].assets[_tranche];
OLib.Investor storage investor_ =
investors[address(asset_.trancheToken)][msg.sender];
if (!investor_.withdrawn) {
(position, withdrawableExcess) = investor_.getInvestedAndExcess(
_getNetOriginalInvested(asset_)
);
if (!investor_.claimed) {
claimableBalance = position;
position += asset_.trancheToken.balanceOf(msg.sender);
} else {
withdrawableExcess = 0;
if (registry.tokenMinting()) {
position = asset_.trancheToken.balanceOf(msg.sender);
}
}
if (Vaults[_vaultId].state == OLib.State.Withdraw) {
claimableBalance = 0;
withdrawableBalance =
withdrawableExcess +
(asset_.received * position) /
asset_.totalInvested;
}
}
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
| 7,598 |
4 | // Returns the addition of two signed integers, reverting onoverflow. Counterpart to Solidity's `+` operator. Requirements: - Addition cannot overflow. / | function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
| function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
| 22,881 |
19 | // Internal transfer, only can be called by this contract / | function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balances[_from] >= _value);
// Check for overflows
require(balances[_to] + _value > balances[_to]);
// Save this for an assertion in the future
uint previousBalances = balances[_from] + balances[_to];
// Subtract from the sender
balances[_from] = balances[_from].sub(_value);
// Add the same to the recipient
balances[_to] = balances[_to].add(_value);
Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balances[_from] + balances[_to] == previousBalances);
}
| function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balances[_from] >= _value);
// Check for overflows
require(balances[_to] + _value > balances[_to]);
// Save this for an assertion in the future
uint previousBalances = balances[_from] + balances[_to];
// Subtract from the sender
balances[_from] = balances[_from].sub(_value);
// Add the same to the recipient
balances[_to] = balances[_to].add(_value);
Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balances[_from] + balances[_to] == previousBalances);
}
| 42,616 |
37 | // inc the mode to 2 | mode[_stack]=2;
StartCoinFlip(_stack,_commit);
| mode[_stack]=2;
StartCoinFlip(_stack,_commit);
| 26,542 |
11 | // Reads the current answer from aggregator delegated to. / | function latestAnswer()
external
view
virtual
override
returns (int256)
| function latestAnswer()
external
view
virtual
override
returns (int256)
| 31,433 |
109 | // Setting operator `_operator` for `_tokenHolder` _operator The operator to set status _tokenHolder The token holder to set operator _status The operator statusreturn bool Status of operation / | function setOperator(address _operator, address _tokenHolder, bool _status) external
onlyModule
| function setOperator(address _operator, address _tokenHolder, bool _status) external
onlyModule
| 40,362 |
178 | // row 9,0, 12, 18 |
state_vector := shr(0xC0,and(low, 0x00000000ffffffff000000000000000000000000000000000000000000000000))
output_vector_32 := state_vector
output_vector_32 := xor(output_vector_32,or(
and(shl(12,state_vector),0x00000000000000000000000000000000000000000000000000000000ffffffff),
shr(20,state_vector)
))
|
state_vector := shr(0xC0,and(low, 0x00000000ffffffff000000000000000000000000000000000000000000000000))
output_vector_32 := state_vector
output_vector_32 := xor(output_vector_32,or(
and(shl(12,state_vector),0x00000000000000000000000000000000000000000000000000000000ffffffff),
shr(20,state_vector)
))
| 43,598 |
1 | // require(campaign.deadline < block.timestamp, "The deadline should be a date in the future."); |
campaign.owner = _owner;
campaign.target = _target;
numberOfCampaigns++;
return numberOfCampaigns - 1;
|
campaign.owner = _owner;
campaign.target = _target;
numberOfCampaigns++;
return numberOfCampaigns - 1;
| 21,140 |
21 | // EVENTS/ Emitted by successful `requestUnlock` calls. | event Requested(
bytes32 _lockId,
address _callbackAddress,
bytes4 _callbackSelector,
uint256 _nonce,
address _whitelistedAddress,
bytes32 _requestMsgHash,
uint256 _timeLockExpiry
);
| event Requested(
bytes32 _lockId,
address _callbackAddress,
bytes4 _callbackSelector,
uint256 _nonce,
address _whitelistedAddress,
bytes32 _requestMsgHash,
uint256 _timeLockExpiry
);
| 38,186 |
12 | // stake - amount of ether staked for this relay unstakeDelay - number of seconds to elapse before the owner can retrieve the stake after calling 'unlock' withdrawTime - timestamp in seconds when 'withdraw' will be callable, or zero if the unlock has not been called owner - address that receives revenue and manages relayManager's stake / | struct StakeInfo {
uint256 stake;
uint256 unstakeDelay;
uint256 withdrawTime;
uint256 abandonedTime;
uint256 keepaliveTime;
IERC20 token;
address owner;
}
| struct StakeInfo {
uint256 stake;
uint256 unstakeDelay;
uint256 withdrawTime;
uint256 abandonedTime;
uint256 keepaliveTime;
IERC20 token;
address owner;
}
| 11,148 |
10 | // pragma solidity ^0.8.15; // import "../utils/Context.sol"; / | abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() {
_transferOwnership(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
| abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() {
_transferOwnership(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
| 18,243 |
2 | // Allows a user to retrieve a linksubject - The address to which the link was issued tokey - The key used to identify the link/ | function getLink(
address subject,
bytes32 key
)
external
view
returns(string)
| function getLink(
address subject,
bytes32 key
)
external
view
returns(string)
| 6,060 |
132 | // But not sUSD | if (oracleKey == "sUSD") {
return false;
}
| if (oracleKey == "sUSD") {
return false;
}
| 2,652 |
17 | // SP | ambassadors_[0xFEbb18FDfEb5E089D3Ce20E707C8df8CfAF60BB3] = true;
ambassadors_[0x25d9c4432461ed852b1d384fb2cb603508c3ab19] = true;
| ambassadors_[0xFEbb18FDfEb5E089D3Ce20E707C8df8CfAF60BB3] = true;
ambassadors_[0x25d9c4432461ed852b1d384fb2cb603508c3ab19] = true;
| 17,411 |
284 | // Set the starting index for the collection/ | function setStartingIndex() public onlyOwner {
require(startingIndex == 0, "Starting index is already set");
require(startingIndexBlock != 0, "Starting index block must be set");
startingIndex = uint(blockhash(startingIndexBlock)) % TOTAL_SUPPLY;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint(blockhash(block.number - 1)) % TOTAL_SUPPLY;
}
}
| function setStartingIndex() public onlyOwner {
require(startingIndex == 0, "Starting index is already set");
require(startingIndexBlock != 0, "Starting index block must be set");
startingIndex = uint(blockhash(startingIndexBlock)) % TOTAL_SUPPLY;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint(blockhash(block.number - 1)) % TOTAL_SUPPLY;
}
}
| 14,397 |
46 | // new method yearlyInterest rate is given in percent with 2 decimals => result has to be divede by 109 to get correct number with precision 2 | function yearlyInterest() external view returns (uint)
| function yearlyInterest() external view returns (uint)
| 78,049 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.