Transaction Hash:
Block:
11636584 at Jan-11-2021 11:22:11 PM +UTC
Transaction Fee:
0.00969213 ETH
$23.71
Gas Used:
92,306 Gas / 105 Gwei
Emitted Events:
144 |
ValueGovernanceVault.Withdraw( user=[Sender] 0xfc2d5db8f417b442428eaf49eb26d99bfc0ff9c6, amount=0 )
|
145 |
ValueGovernanceVault.Transfer( from=[Sender] 0xfc2d5db8f417b442428eaf49eb26d99bfc0ff9c6, to=0x0000000000000000000000000000000000000000, value=981183301720463962790 )
|
146 |
ValueLiquidityToken.Transfer( from=[Receiver] ValueGovernanceVault, to=[Sender] 0xfc2d5db8f417b442428eaf49eb26d99bfc0ff9c6, value=1047453596482110974074 )
|
Account State Difference:
Address | Before | After | State Difference | ||
---|---|---|---|---|---|
0x00192Fb1...d1BF599E8
Miner
| (2Miners: PPLNS) | 306.341278789704234566 Eth | 306.350970919704234566 Eth | 0.00969213 | |
0x49E83333...029218E5c | |||||
0xceC03a96...07B22D875 | |||||
0xFc2D5dB8...bFc0FF9c6 |
0.20851085013687946 Eth
Nonce: 208
|
0.19881872013687946 Eth
Nonce: 209
| 0.00969213 |
Execution Trace
ValueGovernanceVault.withdrawAll( _flag=0 )

-
ValueLiquidityToken.balanceOf( account=0xceC03a960Ea678A2B6EA350fe0DbD1807B22D875 ) => ( 3827216662790681835967154 )
-
ValueLiquidityToken.balanceOf( account=0xceC03a960Ea678A2B6EA350fe0DbD1807B22D875 ) => ( 3827216662790681835967154 )
-
ValueLiquidityToken.transfer( recipient=0xFc2D5dB8f417B442428EAF49eb26d99bFc0FF9c6, amount=1047453596482110974074 ) => ( True )
withdrawAll[ValueGovernanceVault (ln:1120)]
sub[ValueGovernanceVault (ln:1127)]
unstake[ValueGovernanceVault (ln:1130)]
updateReward[ValueGovernanceVault (ln:1142)]
balanceOf[ValueGovernanceVault (ln:1073)]
sub[ValueGovernanceVault (ln:1078)]
add[ValueGovernanceVault (ln:1079)]
div[ValueGovernanceVault (ln:1079)]
mul[ValueGovernanceVault (ln:1079)]
mul[ValueGovernanceVault (ln:1079)]
add[ValueGovernanceVault (ln:1080)]
div[ValueGovernanceVault (ln:1080)]
mul[ValueGovernanceVault (ln:1080)]
mul[ValueGovernanceVault (ln:1080)]
_getReward[ValueGovernanceVault (ln:1143)]
sub[ValueGovernanceVault (ln:1086)]
div[ValueGovernanceVault (ln:1086)]
mul[ValueGovernanceVault (ln:1086)]
div[ValueGovernanceVault (ln:1092)]
mul[ValueGovernanceVault (ln:1092)]
div[ValueGovernanceVault (ln:1092)]
mul[ValueGovernanceVault (ln:1092)]
div[ValueGovernanceVault (ln:1093)]
mul[ValueGovernanceVault (ln:1093)]
add[ValueGovernanceVault (ln:1095)]
add[ValueGovernanceVault (ln:1098)]
div[ValueGovernanceVault (ln:1099)]
mul[ValueGovernanceVault (ln:1099)]
safeValueMint[ValueGovernanceVault (ln:1101)]
minters[ValueGovernanceVault (ln:1234)]
totalSupply[ValueGovernanceVault (ln:1235)]
add[ValueGovernanceVault (ln:1236)]
cap[ValueGovernanceVault (ln:1236)]
yfvLockedBalance[ValueGovernanceVault (ln:1236)]
add[ValueGovernanceVault (ln:1237)]
mint[ValueGovernanceVault (ln:1238)]
sub[ValueGovernanceVault (ln:1238)]
mint[ValueGovernanceVault (ln:1240)]
getReferrer[ValueGovernanceVault (ln:1104)]
safeValueMint[ValueGovernanceVault (ln:1107)]
minters[ValueGovernanceVault (ln:1234)]
totalSupply[ValueGovernanceVault (ln:1235)]
add[ValueGovernanceVault (ln:1236)]
cap[ValueGovernanceVault (ln:1236)]
yfvLockedBalance[ValueGovernanceVault (ln:1236)]
add[ValueGovernanceVault (ln:1237)]
mint[ValueGovernanceVault (ln:1238)]
sub[ValueGovernanceVault (ln:1238)]
mint[ValueGovernanceVault (ln:1240)]
CommissionPaid[ValueGovernanceVault (ln:1108)]
safeValueMint[ValueGovernanceVault (ln:1110)]
minters[ValueGovernanceVault (ln:1234)]
totalSupply[ValueGovernanceVault (ln:1235)]
add[ValueGovernanceVault (ln:1236)]
cap[ValueGovernanceVault (ln:1236)]
yfvLockedBalance[ValueGovernanceVault (ln:1236)]
add[ValueGovernanceVault (ln:1237)]
mint[ValueGovernanceVault (ln:1238)]
sub[ValueGovernanceVault (ln:1238)]
mint[ValueGovernanceVault (ln:1240)]
CommissionPaid[ValueGovernanceVault (ln:1111)]
sub[ValueGovernanceVault (ln:1114)]
div[ValueGovernanceVault (ln:1114)]
mul[ValueGovernanceVault (ln:1114)]
sub[ValueGovernanceVault (ln:1152)]
sub[ValueGovernanceVault (ln:1155)]
add[ValueGovernanceVault (ln:1157)]
revert[ValueGovernanceVault (ln:1159)]
div[ValueGovernanceVault (ln:1162)]
mul[ValueGovernanceVault (ln:1162)]
sub[ValueGovernanceVault (ln:1163)]
sub[ValueGovernanceVault (ln:1165)]
transfer[ValueGovernanceVault (ln:1167)]
RewardPaid[ValueGovernanceVault (ln:1168)]
transfer[ValueGovernanceVault (ln:1172)]
div[ValueGovernanceVault (ln:1174)]
mul[ValueGovernanceVault (ln:1174)]
div[ValueGovernanceVault (ln:1175)]
mul[ValueGovernanceVault (ln:1175)]
Withdraw[ValueGovernanceVault (ln:1176)]
withdraw[ValueGovernanceVault (ln:1131)]
balanceOf[ValueGovernanceVault (ln:1181)]
sub[ValueGovernanceVault (ln:1183)]
unstake[ValueGovernanceVault (ln:1185)]
updateReward[ValueGovernanceVault (ln:1142)]
balanceOf[ValueGovernanceVault (ln:1073)]
sub[ValueGovernanceVault (ln:1078)]
add[ValueGovernanceVault (ln:1079)]
div[ValueGovernanceVault (ln:1079)]
mul[ValueGovernanceVault (ln:1079)]
mul[ValueGovernanceVault (ln:1079)]
add[ValueGovernanceVault (ln:1080)]
div[ValueGovernanceVault (ln:1080)]
mul[ValueGovernanceVault (ln:1080)]
mul[ValueGovernanceVault (ln:1080)]
_getReward[ValueGovernanceVault (ln:1143)]
sub[ValueGovernanceVault (ln:1086)]
div[ValueGovernanceVault (ln:1086)]
mul[ValueGovernanceVault (ln:1086)]
div[ValueGovernanceVault (ln:1092)]
mul[ValueGovernanceVault (ln:1092)]
div[ValueGovernanceVault (ln:1092)]
mul[ValueGovernanceVault (ln:1092)]
div[ValueGovernanceVault (ln:1093)]
mul[ValueGovernanceVault (ln:1093)]
add[ValueGovernanceVault (ln:1095)]
add[ValueGovernanceVault (ln:1098)]
div[ValueGovernanceVault (ln:1099)]
mul[ValueGovernanceVault (ln:1099)]
safeValueMint[ValueGovernanceVault (ln:1101)]
minters[ValueGovernanceVault (ln:1234)]
totalSupply[ValueGovernanceVault (ln:1235)]
add[ValueGovernanceVault (ln:1236)]
cap[ValueGovernanceVault (ln:1236)]
yfvLockedBalance[ValueGovernanceVault (ln:1236)]
add[ValueGovernanceVault (ln:1237)]
mint[ValueGovernanceVault (ln:1238)]
sub[ValueGovernanceVault (ln:1238)]
mint[ValueGovernanceVault (ln:1240)]
getReferrer[ValueGovernanceVault (ln:1104)]
safeValueMint[ValueGovernanceVault (ln:1107)]
minters[ValueGovernanceVault (ln:1234)]
totalSupply[ValueGovernanceVault (ln:1235)]
add[ValueGovernanceVault (ln:1236)]
cap[ValueGovernanceVault (ln:1236)]
yfvLockedBalance[ValueGovernanceVault (ln:1236)]
add[ValueGovernanceVault (ln:1237)]
mint[ValueGovernanceVault (ln:1238)]
sub[ValueGovernanceVault (ln:1238)]
mint[ValueGovernanceVault (ln:1240)]
CommissionPaid[ValueGovernanceVault (ln:1108)]
safeValueMint[ValueGovernanceVault (ln:1110)]
minters[ValueGovernanceVault (ln:1234)]
totalSupply[ValueGovernanceVault (ln:1235)]
add[ValueGovernanceVault (ln:1236)]
cap[ValueGovernanceVault (ln:1236)]
yfvLockedBalance[ValueGovernanceVault (ln:1236)]
add[ValueGovernanceVault (ln:1237)]
mint[ValueGovernanceVault (ln:1238)]
sub[ValueGovernanceVault (ln:1238)]
mint[ValueGovernanceVault (ln:1240)]
CommissionPaid[ValueGovernanceVault (ln:1111)]
sub[ValueGovernanceVault (ln:1114)]
div[ValueGovernanceVault (ln:1114)]
mul[ValueGovernanceVault (ln:1114)]
sub[ValueGovernanceVault (ln:1152)]
sub[ValueGovernanceVault (ln:1155)]
add[ValueGovernanceVault (ln:1157)]
revert[ValueGovernanceVault (ln:1159)]
div[ValueGovernanceVault (ln:1162)]
mul[ValueGovernanceVault (ln:1162)]
sub[ValueGovernanceVault (ln:1163)]
sub[ValueGovernanceVault (ln:1165)]
transfer[ValueGovernanceVault (ln:1167)]
RewardPaid[ValueGovernanceVault (ln:1168)]
transfer[ValueGovernanceVault (ln:1172)]
div[ValueGovernanceVault (ln:1174)]
mul[ValueGovernanceVault (ln:1174)]
div[ValueGovernanceVault (ln:1175)]
mul[ValueGovernanceVault (ln:1175)]
Withdraw[ValueGovernanceVault (ln:1176)]
add[ValueGovernanceVault (ln:1186)]
div[ValueGovernanceVault (ln:1188)]
mul[ValueGovernanceVault (ln:1188)]
totalSupply[ValueGovernanceVault (ln:1188)]
_burn[ValueGovernanceVault (ln:1189)]
balanceOf[ValueGovernanceVault (ln:1192)]
sub[ValueGovernanceVault (ln:1194)]
withdraw[ValueGovernanceVault (ln:1196)]
balanceOf[ValueGovernanceVault (ln:1198)]
sub[ValueGovernanceVault (ln:1199)]
add[ValueGovernanceVault (ln:1201)]
transfer[ValueGovernanceVault (ln:1205)]
balanceOf[ValueGovernanceVault (ln:1131)]
File 1 of 2: ValueGovernanceVault
File 2 of 2: ValueLiquidityToken
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * 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); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.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); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } interface IController { function vaults(address) external view returns (address); function rewards() external view returns (address); function want(address) external view returns (address); function balanceOf(address) external view returns (uint); function withdraw(address, uint) external; function maxAcceptAmount(address) external view returns (uint256); function earn(address, uint) external; function getStrategyCount(address _vault) external view returns(uint256); function depositAvailable(address _vault) external view returns(bool); function harvestAllStrategies(address _vault) external; function harvestStrategy(address _vault, address _strategy) external; } interface ITokenInterface is IERC20 { /** VALUE, YFV, vUSD, vETH has minters **/ function minters(address account) external view returns (bool); function mint(address _to, uint _amount) external; /** YFV <-> VALUE **/ function deposit(uint _amount) external; function withdraw(uint _amount) external; function cap() external returns (uint); function yfvLockedBalance() external returns (uint); } interface IYFVReferral { function setReferrer(address farmer, address referrer) external; function getReferrer(address farmer) external view returns (address); } interface IFreeFromUpTo { function freeFromUpTo(address from, uint valueToken) external returns (uint freed); } contract ValueGovernanceVault is ERC20 { using Address for address; using SafeMath for uint; IFreeFromUpTo public constant chi = IFreeFromUpTo(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c); modifier discountCHI(uint8 _flag) { if ((_flag & 0x1) == 0) { _; } else { uint gasStart = gasleft(); _; uint gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length; chi.freeFromUpTo(msg.sender, (gasSpent + 14154) / 41130); } } ITokenInterface public yfvToken; // stake and wrap to VALUE ITokenInterface public valueToken; // stake and reward token ITokenInterface public vUSD; // reward token ITokenInterface public vETH; // reward token uint public fundCap = 9500; // use up to 95% of fund (to keep small withdrawals cheap) uint public constant FUND_CAP_DENOMINATOR = 10000; uint public earnLowerlimit; address public governance; address public controller; address public rewardReferral; // Info of each user. struct UserInfo { uint amount; uint valueRewardDebt; uint vusdRewardDebt; uint lastStakeTime; uint accumulatedStakingPower; // will accumulate every time user harvest uint lockedAmount; uint lockedDays; // 7 days -> 150 days (5 months) uint boostedExtra; // times 1e12 (285200000000 -> +28.52%). See below. uint unlockedTime; } uint maxLockedDays = 150; uint lastRewardBlock; // Last block number that reward distribution occurs. uint accValuePerShare; // Accumulated VALUEs per share, times 1e12. See below. uint accVusdPerShare; // Accumulated vUSD per share, times 1e12. See below. uint public valuePerBlock; // 0.2 VALUE/block at start uint public vusdPerBlock; // 5 vUSD/block at start mapping(address => UserInfo) public userInfo; uint public totalDepositCap; uint public constant vETH_REWARD_FRACTION_RATE = 1000; uint public minStakingAmount = 0 ether; uint public unstakingFrozenTime = 40 hours; // ** unlockWithdrawFee = 1.92%: stakers will need to pay 1.92% (sent to insurance fund) of amount they want to withdraw if the coin still frozen uint public unlockWithdrawFee = 192; // per ten thousand (eg. 15 -> 0.15%) address public valueInsuranceFund = 0xb7b2Ea8A1198368f950834875047aA7294A2bDAa; // set to Governance Multisig at start event Deposit(address indexed user, uint amount); event Withdraw(address indexed user, uint amount); event RewardPaid(address indexed user, uint reward); event CommissionPaid(address indexed user, uint reward); event Locked(address indexed user, uint amount, uint _days); event EmergencyWithdraw(address indexed user, uint amount); constructor (ITokenInterface _yfvToken, ITokenInterface _valueToken, ITokenInterface _vUSD, ITokenInterface _vETH, uint _valuePerBlock, uint _vusdPerBlock, uint _startBlock) public ERC20("GovVault:ValueLiquidity", "gvVALUE") { yfvToken = _yfvToken; valueToken = _valueToken; vUSD = _vUSD; vETH = _vETH; valuePerBlock = _valuePerBlock; vusdPerBlock = _vusdPerBlock; lastRewardBlock = _startBlock; governance = msg.sender; } function balance() public view returns (uint) { uint bal = valueToken.balanceOf(address(this)); if (controller != address(0)) bal = bal.add(IController(controller).balanceOf(address(valueToken))); return bal; } function setFundCap(uint _fundCap) external { require(msg.sender == governance, "!governance"); fundCap = _fundCap; } function setTotalDepositCap(uint _totalDepositCap) external { require(msg.sender == governance, "!governance"); totalDepositCap = _totalDepositCap; } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function setController(address _controller) public { require(msg.sender == governance, "!governance"); controller = _controller; } function setRewardReferral(address _rewardReferral) external { require(msg.sender == governance, "!governance"); rewardReferral = _rewardReferral; } function setEarnLowerlimit(uint _earnLowerlimit) public { require(msg.sender == governance, "!governance"); earnLowerlimit = _earnLowerlimit; } function setMaxLockedDays(uint _maxLockedDays) public { require(msg.sender == governance, "!governance"); maxLockedDays = _maxLockedDays; } function setValuePerBlock(uint _valuePerBlock) public { require(msg.sender == governance, "!governance"); require(_valuePerBlock <= 10 ether, "Too big _valuePerBlock"); // <= 10 VALUE updateReward(); valuePerBlock = _valuePerBlock; } function setVusdPerBlock(uint _vusdPerBlock) public { require(msg.sender == governance, "!governance"); require(_vusdPerBlock <= 200 * (10 ** 9), "Too big _vusdPerBlock"); // <= 200 vUSD updateReward(); vusdPerBlock = _vusdPerBlock; } function setMinStakingAmount(uint _minStakingAmount) public { require(msg.sender == governance, "!governance"); minStakingAmount = _minStakingAmount; } function setUnstakingFrozenTime(uint _unstakingFrozenTime) public { require(msg.sender == governance, "!governance"); unstakingFrozenTime = _unstakingFrozenTime; } function setUnlockWithdrawFee(uint _unlockWithdrawFee) public { require(msg.sender == governance, "!governance"); require(_unlockWithdrawFee <= 1000, "Dont be too greedy"); // <= 10% unlockWithdrawFee = _unlockWithdrawFee; } function setValueInsuranceFund(address _valueInsuranceFund) public { require(msg.sender == governance, "!governance"); valueInsuranceFund = _valueInsuranceFund; } // To upgrade vUSD contract (v1 is still experimental, we may need vUSDv2 with rebase() function working soon - then governance will call this upgrade) function upgradeVUSDContract(address _vUSDContract) public { require(msg.sender == governance, "!governance"); vUSD = ITokenInterface(_vUSDContract); } // To upgrade vETH contract (v1 is still experimental, we may need vETHv2 with rebase() function working soon - then governance will call this upgrade) function upgradeVETHContract(address _vETHContract) public { require(msg.sender == governance, "!governance"); vETH = ITokenInterface(_vETHContract); } // Custom logic in here for how much the vault allows to be borrowed // Sets minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint) { return valueToken.balanceOf(address(this)).mul(fundCap).div(FUND_CAP_DENOMINATOR); } function earn(uint8 _flag) public discountCHI(_flag) { if (controller != address(0)) { uint _amount = available(); uint _accepted = IController(controller).maxAcceptAmount(address(valueToken)); if (_amount > _accepted) _amount = _accepted; if (_amount > 0) { yfvToken.transfer(controller, _amount); IController(controller).earn(address(yfvToken), _amount); } } } function getRewardAndDepositAll(uint8 _flag) external discountCHI(_flag) { unstake(0, 0x0); depositAll(address(0), 0x0); } function depositAll(address _referrer, uint8 _flag) public discountCHI(_flag) { deposit(valueToken.balanceOf(msg.sender), _referrer, 0x0); } function deposit(uint _amount, address _referrer, uint8 _flag) public discountCHI(_flag) { uint _pool = balance(); uint _before = valueToken.balanceOf(address(this)); valueToken.transferFrom(msg.sender, address(this), _amount); uint _after = valueToken.balanceOf(address(this)); require(totalDepositCap == 0 || _after <= totalDepositCap, ">totalDepositCap"); _amount = _after.sub(_before); // Additional check for deflationary tokens uint _shares = _deposit(address(this), _pool, _amount); _stakeShares(msg.sender, _shares, _referrer); } function depositYFV(uint _amount, address _referrer, uint8 _flag) public discountCHI(_flag) { uint _pool = balance(); yfvToken.transferFrom(msg.sender, address(this), _amount); uint _before = valueToken.balanceOf(address(this)); yfvToken.approve(address(valueToken), 0); yfvToken.approve(address(valueToken), _amount); valueToken.deposit(_amount); uint _after = valueToken.balanceOf(address(this)); require(totalDepositCap == 0 || _after <= totalDepositCap, ">totalDepositCap"); _amount = _after.sub(_before); // Additional check for deflationary tokens uint _shares = _deposit(address(this), _pool, _amount); _stakeShares(msg.sender, _shares, _referrer); } function buyShares(uint _amount, uint8 _flag) public discountCHI(_flag) { uint _pool = balance(); uint _before = valueToken.balanceOf(address(this)); valueToken.transferFrom(msg.sender, address(this), _amount); uint _after = valueToken.balanceOf(address(this)); require(totalDepositCap == 0 || _after <= totalDepositCap, ">totalDepositCap"); _amount = _after.sub(_before); // Additional check for deflationary tokens _deposit(msg.sender, _pool, _amount); } function depositShares(uint _shares, address _referrer, uint8 _flag) public discountCHI(_flag) { require(totalDepositCap == 0 || balance().add(_shares) <= totalDepositCap, ">totalDepositCap"); uint _before = balanceOf(address(this)); IERC20(address(this)).transferFrom(msg.sender, address(this), _shares); uint _after = balanceOf(address(this)); _shares = _after.sub(_before); // Additional check for deflationary tokens _stakeShares(msg.sender, _shares, _referrer); } function lockShares(uint _locked, uint _days, uint8 _flag) external discountCHI(_flag) { require(_days >= 7 && _days <= maxLockedDays, "_days out-of-range"); UserInfo storage user = userInfo[msg.sender]; if (user.unlockedTime < block.timestamp) { user.lockedAmount = 0; } else { require(_days >= user.lockedDays, "Extra days should not less than current locked days"); } user.lockedAmount = user.lockedAmount.add(_locked); require(user.lockedAmount <= user.amount, "lockedAmount > amount"); user.unlockedTime = block.timestamp.add(_days * 86400); // (%) = 5 + (lockedDays - 7) * 0.15 user.boostedExtra = 50000000000 + (_days - 7) * 1500000000; emit Locked(msg.sender, user.lockedAmount, _days); } function _deposit(address _mintTo, uint _pool, uint _amount) internal returns (uint _shares) { _shares = 0; if (totalSupply() == 0) { _shares = _amount; } else { _shares = (_amount.mul(totalSupply())).div(_pool); } if (_shares > 0) { if (valueToken.balanceOf(address(this)) > earnLowerlimit) { earn(0x0); } _mint(_mintTo, _shares); } } function _stakeShares(address _account, uint _shares, address _referrer) internal { UserInfo storage user = userInfo[_account]; require(minStakingAmount == 0 || user.amount.add(_shares) >= minStakingAmount, "<minStakingAmount"); updateReward(); _getReward(); user.amount = user.amount.add(_shares); if (user.lockedAmount > 0 && user.unlockedTime < block.timestamp) { user.lockedAmount = 0; } user.valueRewardDebt = user.amount.mul(accValuePerShare).div(1e12); user.vusdRewardDebt = user.amount.mul(accVusdPerShare).div(1e12); user.lastStakeTime = block.timestamp; emit Deposit(_account, _shares); if (rewardReferral != address(0) && _account != address(0)) { IYFVReferral(rewardReferral).setReferrer(_account, _referrer); } } function unfrozenStakeTime(address _account) public view returns (uint) { return userInfo[_account].lastStakeTime + unstakingFrozenTime; } // View function to see pending VALUEs on frontend. function pendingValue(address _account) public view returns (uint _pending) { UserInfo storage user = userInfo[_account]; uint _accValuePerShare = accValuePerShare; uint lpSupply = balanceOf(address(this)); if (block.number > lastRewardBlock && lpSupply != 0) { uint numBlocks = block.number.sub(lastRewardBlock); _accValuePerShare = accValuePerShare.add(numBlocks.mul(valuePerBlock).mul(1e12).div(lpSupply)); } _pending = user.amount.mul(_accValuePerShare).div(1e12).sub(user.valueRewardDebt); if (user.lockedAmount > 0 && user.unlockedTime >= block.timestamp) { uint _bonus = _pending.mul(user.lockedAmount.mul(user.boostedExtra).div(1e12)).div(user.amount); uint _ceilingBonus = _pending.mul(33).div(100); // 33% if (_bonus > _ceilingBonus) _bonus = _ceilingBonus; // Additional check to avoid insanely high bonus! _pending = _pending.add(_bonus); } } // View function to see pending vUSDs on frontend. function pendingVusd(address _account) public view returns (uint) { UserInfo storage user = userInfo[_account]; uint _accVusdPerShare = accVusdPerShare; uint lpSupply = balanceOf(address(this)); if (block.number > lastRewardBlock && lpSupply != 0) { uint numBlocks = block.number.sub(lastRewardBlock); _accVusdPerShare = accVusdPerShare.add(numBlocks.mul(vusdPerBlock).mul(1e12).div(lpSupply)); } return user.amount.mul(_accVusdPerShare).div(1e12).sub(user.vusdRewardDebt); } // View function to see pending vETHs on frontend. function pendingVeth(address _account) public view returns (uint) { return pendingVusd(_account).div(vETH_REWARD_FRACTION_RATE); } function stakingPower(address _account) public view returns (uint) { return userInfo[_account].accumulatedStakingPower.add(pendingValue(_account)); } function updateReward() public { if (block.number <= lastRewardBlock) { return; } uint lpSupply = balanceOf(address(this)); if (lpSupply == 0) { lastRewardBlock = block.number; return; } uint _numBlocks = block.number.sub(lastRewardBlock); accValuePerShare = accValuePerShare.add(_numBlocks.mul(valuePerBlock).mul(1e12).div(lpSupply)); accVusdPerShare = accVusdPerShare.add(_numBlocks.mul(vusdPerBlock).mul(1e12).div(lpSupply)); lastRewardBlock = block.number; } function _getReward() internal { UserInfo storage user = userInfo[msg.sender]; uint _pendingValue = user.amount.mul(accValuePerShare).div(1e12).sub(user.valueRewardDebt); if (_pendingValue > 0) { if (user.lockedAmount > 0) { if (user.unlockedTime < block.timestamp) { user.lockedAmount = 0; } else { uint _bonus = _pendingValue.mul(user.lockedAmount.mul(user.boostedExtra).div(1e12)).div(user.amount); uint _ceilingBonus = _pendingValue.mul(33).div(100); // 33% if (_bonus > _ceilingBonus) _bonus = _ceilingBonus; // Additional check to avoid insanely high bonus! _pendingValue = _pendingValue.add(_bonus); } } user.accumulatedStakingPower = user.accumulatedStakingPower.add(_pendingValue); uint actualPaid = _pendingValue.mul(99).div(100); // 99% uint commission = _pendingValue - actualPaid; // 1% safeValueMint(msg.sender, actualPaid); address _referrer = address(0); if (rewardReferral != address(0)) { _referrer = IYFVReferral(rewardReferral).getReferrer(msg.sender); } if (_referrer != address(0)) { // send commission to referrer safeValueMint(_referrer, commission); CommissionPaid(_referrer, commission); } else { // send commission to valueInsuranceFund safeValueMint(valueInsuranceFund, commission); CommissionPaid(valueInsuranceFund, commission); } } uint _pendingVusd = user.amount.mul(accVusdPerShare).div(1e12).sub(user.vusdRewardDebt); if (_pendingVusd > 0) { safeVusdMint(msg.sender, _pendingVusd); } } function withdrawAll(uint8 _flag) public discountCHI(_flag) { UserInfo storage user = userInfo[msg.sender]; uint _amount = user.amount; if (user.lockedAmount > 0) { if (user.unlockedTime < block.timestamp) { user.lockedAmount = 0; } else { _amount = user.amount.sub(user.lockedAmount); } } unstake(_amount, 0x0); withdraw(balanceOf(msg.sender), 0x0); } // Used to swap any borrowed reserve over the debt limit to liquidate to 'token' function harvest(address reserve, uint amount) external { require(msg.sender == controller, "!controller"); require(reserve != address(valueToken), "token"); ITokenInterface(reserve).transfer(controller, amount); } function unstake(uint _amount, uint8 _flag) public discountCHI(_flag) returns (uint _actualWithdraw) { updateReward(); _getReward(); UserInfo storage user = userInfo[msg.sender]; _actualWithdraw = _amount; if (_amount > 0) { require(user.amount >= _amount, "stakedBal < _amount"); if (user.lockedAmount > 0) { if (user.unlockedTime < block.timestamp) { user.lockedAmount = 0; } else { require(user.amount.sub(user.lockedAmount) >= _amount, "stakedBal-locked < _amount"); } } user.amount = user.amount.sub(_amount); if (block.timestamp < user.lastStakeTime.add(unstakingFrozenTime)) { // if coin is still frozen and governance does not allow stakers to unstake before timer ends if (unlockWithdrawFee == 0 || valueInsuranceFund == address(0)) revert("Coin is still frozen"); // otherwise withdrawFee will be calculated based on the rate uint _withdrawFee = _amount.mul(unlockWithdrawFee).div(10000); uint r = _amount.sub(_withdrawFee); if (_amount > r) { _withdrawFee = _amount.sub(r); _actualWithdraw = r; IERC20(address(this)).transfer(valueInsuranceFund, _withdrawFee); emit RewardPaid(valueInsuranceFund, _withdrawFee); } } IERC20(address(this)).transfer(msg.sender, _actualWithdraw); } user.valueRewardDebt = user.amount.mul(accValuePerShare).div(1e12); user.vusdRewardDebt = user.amount.mul(accVusdPerShare).div(1e12); emit Withdraw(msg.sender, _amount); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint _shares, uint8 _flag) public discountCHI(_flag) { uint _userBal = balanceOf(msg.sender); if (_shares > _userBal) { uint _need = _shares.sub(_userBal); require(_need <= userInfo[msg.sender].amount, "_userBal+staked < _shares"); uint _actualWithdraw = unstake(_need, 0x0); _shares = _userBal.add(_actualWithdraw); // may be less than expected due to unlockWithdrawFee } uint r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); // Check balance uint b = valueToken.balanceOf(address(this)); if (b < r) { uint _withdraw = r.sub(b); if (controller != address(0)) { IController(controller).withdraw(address(valueToken), _withdraw); } uint _after = valueToken.balanceOf(address(this)); uint _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } valueToken.transfer(msg.sender, r); } function getPricePerFullShare() public view returns (uint) { return balance().mul(1e18).div(totalSupply()); } function getStrategyCount() external view returns (uint) { return (controller != address(0)) ? IController(controller).getStrategyCount(address(this)) : 0; } function depositAvailable() external view returns (bool) { return (controller != address(0)) ? IController(controller).depositAvailable(address(this)) : false; } function harvestAllStrategies(uint8 _flag) public discountCHI(_flag) { if (controller != address(0)) { IController(controller).harvestAllStrategies(address(this)); } } function harvestStrategy(address _strategy, uint8 _flag) public discountCHI(_flag) { if (controller != address(0)) { IController(controller).harvestStrategy(address(this), _strategy); } } // Safe valueToken mint, ensure it is never over cap and we are the current owner. function safeValueMint(address _to, uint _amount) internal { if (valueToken.minters(address(this)) && _to != address(0)) { uint totalSupply = valueToken.totalSupply(); uint realCap = valueToken.cap().add(valueToken.yfvLockedBalance()); if (totalSupply.add(_amount) > realCap) { valueToken.mint(_to, realCap.sub(totalSupply)); } else { valueToken.mint(_to, _amount); } } } // Safe vUSD mint, ensure we are the current owner. // vETH will be minted together with fixed rate. function safeVusdMint(address _to, uint _amount) internal { if (vUSD.minters(address(this)) && _to != address(0)) { vUSD.mint(_to, _amount); } if (vETH.minters(address(this)) && _to != address(0)) { vETH.mint(_to, _amount.div(vETH_REWARD_FRACTION_RATE)); } } // This is for governance in some emergency circumstances to release lock immediately for an account function governanceResetLocked(address _account) external { require(msg.sender == governance, "!governance"); UserInfo storage user = userInfo[_account]; user.lockedAmount = 0; user.lockedDays = 0; user.boostedExtra = 0; user.unlockedTime = 0; } // This function allows governance to take unsupported tokens out of the contract, since this pool exists longer than the others. // This is in an effort to make someone whole, should they seriously mess up. // There is no guarantee governance will vote to return these. // It also allows for removal of airdropped tokens. function governanceRecoverUnsupported(IERC20 _token, uint _amount, address _to) external { require(msg.sender == governance, "!governance"); require(address(_token) != address(valueToken) || balance().sub(_amount) >= totalSupply(), "cant withdraw VALUE more than gvVALUE supply"); _token.transfer(_to, _amount); } }
File 2 of 2: ValueLiquidityToken
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; // File: @openzeppelin/contracts/GSN/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * 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); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.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); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/VALUE/ValueLiquidityToken.sol /** * @notice Value Liquidity (VALUE) with Governance Alpha */ contract ValueLiquidityToken is ERC20 { using SafeERC20 for IERC20; using SafeMath for uint256; IERC20 public yfv; address public governance; uint256 public cap; uint256 public yfvLockedBalance; mapping(address => bool) public minters; event Deposit(address indexed dst, uint amount); event Withdrawal(address indexed src, uint amount); constructor (IERC20 _yfv, uint256 _cap) public ERC20("Value Liquidity", "VALUE") { governance = msg.sender; yfv = _yfv; cap = _cap; } function mint(address _to, uint256 _amount) public { require(msg.sender == governance || minters[msg.sender], "!governance && !minter"); _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } function burn(uint256 _amount) public { _burn(msg.sender, _amount); _moveDelegates(_delegates[msg.sender], address(0), _amount); } function burnFrom(address _account, uint256 _amount) public { uint256 decreasedAllowance = allowance(_account, msg.sender).sub(_amount, "ERC20: burn amount exceeds allowance"); _approve(_account, msg.sender, decreasedAllowance); _burn(_account, _amount); _moveDelegates(_delegates[_account], address(0), _amount); } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function addMinter(address _minter) public { require(msg.sender == governance, "!governance"); minters[_minter] = true; } function removeMinter(address _minter) public { require(msg.sender == governance, "!governance"); minters[_minter] = false; } function setCap(uint256 _cap) public { require(msg.sender == governance, "!governance"); require(_cap.add(yfvLockedBalance) >= totalSupply(), "_cap (plus yfvLockedBalance) is below current supply"); cap = _cap; } function deposit(uint256 _amount) public { yfv.safeTransferFrom(msg.sender, address(this), _amount); yfvLockedBalance = yfvLockedBalance.add(_amount); _mint(msg.sender, _amount); _moveDelegates(address(0), _delegates[msg.sender], _amount); Deposit(msg.sender, _amount); } function withdraw(uint256 _amount) public { yfvLockedBalance = yfvLockedBalance.sub(_amount, "There is not enough locked YFV to withdraw"); yfv.safeTransfer(msg.sender, _amount); _burn(msg.sender, _amount); _moveDelegates(_delegates[msg.sender], address(0), _amount); Withdrawal(msg.sender, _amount); } // This function allows governance to take unsupported tokens out of the contract. // This is in an effort to make someone whole, should they seriously mess up. // There is no guarantee governance will vote to return these. // It also allows for removal of airdropped tokens. function governanceRecoverUnsupported(IERC20 _token, address _to, uint256 _amount) external { require(msg.sender == governance, "!governance"); if (_token == yfv) { uint256 yfvBalance = yfv.balanceOf(address(this)); require(_amount <= yfvBalance.sub(yfvLockedBalance), "cant withdraw more then stuck amount"); } _token.safeTransfer(_to, _amount); } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - minted tokens must not cause the total supply to go over the cap. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) {// When minting tokens require(totalSupply().add(amount) <= cap.add(yfvLockedBalance), "ERC20Capped: cap exceeded"); } } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev A record of each accounts delegate mapping(address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping(address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "VALUE::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "VALUE::delegateBySig: invalid nonce"); require(now <= expiry, "VALUE::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "VALUE::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying VALUEs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "VALUE::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2 ** 32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly {chainId := chainid()} return chainId; } }