file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
./full_match/42/0x4063270362F942C265CCcB257c616852b1759AE2/sources/contracts/UniswapV2Router2.sol | charge 0.3% fee on trading of pair(weth, dai, usdt, wbtc, usdc) | function chargeTransactionFeeIn(uint amountIn, address[] memory path) internal returns (uint) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
address pair = UniswapV2Library.pairFor(factory, path[0], path[1]);
address token1 = IUniswapV2Pair(pair).token1();
address token0 = IUniswapV2Pair(pair).token0();
uint256 chargeFee = (amountIn.mul(feePercent)) / 1000;
if((token1 == WETH || token0 == WETH) && path[0] == WETH) {
return (amountIn.sub(chargeFee));
return (amountIn.sub(chargeFee));
return (amountIn.sub(chargeFee));
}
return amountIn;
}
| 16,278,792 |
pragma solidity ^0.8.2;
// SPDX-License-Identifier: MIT
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return payable(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 Interface of the BEP20 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) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract SHIKO is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcluded;
mapping (address => bool) private _isCharity;
address[] private _excluded;
string private constant _NAME = 'Shikoku Inu';
string private constant _SYMBOL = 'SHIKO';
uint8 private constant _DECIMALS = 9;
uint256 private constant _MAX = ~uint256(0);
uint256 private constant _DECIMALFACTOR = 10 ** uint256(_DECIMALS);
uint256 private constant _GRANULARITY = 100;
uint256 private _tTotal = 100000000000 * _DECIMALFACTOR;
uint256 private _rTotal = (_MAX - (_MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _tBurnTotal;
uint256 private _tCharityTotal;
uint256 private _TAX_FEE = 200; // 2% back to the holders
uint256 private _BURN_FEE = 200; // 2% will be burned
uint256 private _CHARITY_FEE = 0;
uint256 private constant _MAX_TX_SIZE = 100000000000 * _DECIMALFACTOR;
// Track original fees to bypass fees for charity account
uint256 private ORIG_TAX_FEE = _TAX_FEE;
uint256 private ORIG_BURN_FEE = _BURN_FEE;
uint256 private ORIG_CHARITY_FEE = _CHARITY_FEE;
constructor () {
_rOwned[_msgSender()] = _rTotal;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _NAME;
}
function symbol() public pure returns (string memory) {
return _SYMBOL;
}
function decimals() public pure returns (uint8) {
return _DECIMALS;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero"));
return true;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function totalBurn() public view returns (uint256) {
return _tBurnTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "BEP20: approve from the zero address");
require(spender != address(0), "BEP20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "BEP20: transfer from the zero address");
require(recipient != address(0), "BEP20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
// Remove fees for transfers to and from charity account or to excluded account
bool takeFee = true;
if (_isCharity[sender] || _isCharity[recipient] || _isExcluded[recipient]) {
takeFee = false;
}
if (!takeFee) removeAllFee();
if (sender != owner() && recipient != owner())
require(amount <= _MAX_TX_SIZE, "Transfer amount exceeds the maxTxAmount.");
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if (!takeFee) restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tCharity) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
uint256 rCharity = tCharity.mul(currentRate);
_standardTransferContent(sender, recipient, rAmount, rTransferAmount);
//_sendToCharity(tCharity, sender);
_reflectFee(rFee, rBurn, rCharity, tFee, tBurn, tCharity);
emit Transfer(sender, recipient, tTransferAmount);
}
function _standardTransferContent(address sender, address recipient, uint256 rAmount, uint256 rTransferAmount) private {
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tCharity) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
uint256 rCharity = tCharity.mul(currentRate);
_excludedFromTransferContent(sender, recipient, tTransferAmount, rAmount, rTransferAmount);
//_sendToCharity(tCharity, sender);
_reflectFee(rFee, rBurn, rCharity, tFee, tBurn, tCharity);
emit Transfer(sender, recipient, tTransferAmount);
}
function _excludedFromTransferContent(address sender, address recipient, uint256 tTransferAmount, uint256 rAmount, uint256 rTransferAmount) private {
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tCharity) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
uint256 rCharity = tCharity.mul(currentRate);
_excludedToTransferContent(sender, recipient, tAmount, rAmount, rTransferAmount);
//_sendToCharity(tCharity, sender);
_reflectFee(rFee, rBurn, rCharity, tFee, tBurn, tCharity);
emit Transfer(sender, recipient, tTransferAmount);
}
function _excludedToTransferContent(address sender, address recipient, uint256 tAmount, uint256 rAmount, uint256 rTransferAmount) private {
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tCharity) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
uint256 rCharity = tCharity.mul(currentRate);
_bothTransferContent(sender, recipient, tAmount, rAmount, tTransferAmount, rTransferAmount);
//_sendToCharity(tCharity, sender);
_reflectFee(rFee, rBurn, rCharity, tFee, tBurn, tCharity);
emit Transfer(sender, recipient, tTransferAmount);
}
function _bothTransferContent(address sender, address recipient, uint256 tAmount, uint256 rAmount, uint256 tTransferAmount, uint256 rTransferAmount) private {
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
}
function _reflectFee(uint256 rFee, uint256 rBurn, uint256 rCharity, uint256 tFee, uint256 tBurn, uint256 tCharity) private {
_rTotal = _rTotal.sub(rFee).sub(rBurn).sub(rCharity);
_tFeeTotal = _tFeeTotal.add(tFee);
_tBurnTotal = _tBurnTotal.add(tBurn);
_tCharityTotal = _tCharityTotal.add(tCharity);
_tTotal = _tTotal.sub(tBurn);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tFee, uint256 tBurn, uint256 tCharity) = _getTBasics(tAmount, _TAX_FEE, _BURN_FEE, _CHARITY_FEE);
uint256 tTransferAmount = getTTransferAmount(tAmount, tFee, tBurn, tCharity);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rFee) = _getRBasics(tAmount, tFee, currentRate);
uint256 rTransferAmount = _getRTransferAmount(rAmount, rFee, tBurn, tCharity, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tBurn, tCharity);
}
function _getTBasics(uint256 tAmount, uint256 taxFee, uint256 burnFee, uint256 charityFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = ((tAmount.mul(taxFee)).div(_GRANULARITY)).div(100);
uint256 tBurn = ((tAmount.mul(burnFee)).div(_GRANULARITY)).div(100);
uint256 tCharity = ((tAmount.mul(charityFee)).div(_GRANULARITY)).div(100);
return (tFee, tBurn, tCharity);
}
function getTTransferAmount(uint256 tAmount, uint256 tFee, uint256 tBurn, uint256 tCharity) private pure returns (uint256) {
return tAmount.sub(tFee).sub(tBurn).sub(tCharity);
}
function _getRBasics(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
return (rAmount, rFee);
}
function _getRTransferAmount(uint256 rAmount, uint256 rFee, uint256 tBurn, uint256 tCharity, uint256 currentRate) private pure returns (uint256) {
uint256 rBurn = tBurn.mul(currentRate);
uint256 rCharity = tCharity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rBurn).sub(rCharity);
return rTransferAmount;
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function removeAllFee() private {
if(_TAX_FEE == 0 && _BURN_FEE == 0 && _CHARITY_FEE == 0) return;
ORIG_TAX_FEE = _TAX_FEE;
ORIG_BURN_FEE = _BURN_FEE;
ORIG_CHARITY_FEE = _CHARITY_FEE;
_TAX_FEE = 0;
_BURN_FEE = 0;
_CHARITY_FEE = 0;
}
function restoreAllFee() private {
_TAX_FEE = ORIG_TAX_FEE;
_BURN_FEE = ORIG_BURN_FEE;
_CHARITY_FEE = ORIG_CHARITY_FEE;
}
function _getTaxFee() public view returns(uint256) {
return _TAX_FEE;
}
function _getMaxTxAmount() private pure returns(uint256) {
return _MAX_TX_SIZE;
}
} | _sendToCharity(tCharity, sender); | function _transferStandard(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tCharity) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
uint256 rCharity = tCharity.mul(currentRate);
_standardTransferContent(sender, recipient, rAmount, rTransferAmount);
_reflectFee(rFee, rBurn, rCharity, tFee, tBurn, tCharity);
emit Transfer(sender, recipient, tTransferAmount);
}
| 6,038,208 |
./full_match/1/0xBBecdE7bea79d456a203fD9cF13e1209D6458809/sources/RUSHLABSX.sol | exclude from paying fees or having max transaction amount | constructor() ERC20("RushLabs.XYZ", "RUSHLABS") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 buyMarketingFee = 1;
uint256 buyLiquidityFee = 1;
uint256 buyDevFee = 10;
uint256 sellMarketingFee = 1;
uint256 sellLiquidityFee = 1;
uint256 sellDevFee = 10;
uint256 totalSupply = 1e18 * 1e9;
_buyMarketingFee = buyMarketingFee;
_buyLiquidityFee = buyLiquidityFee;
_buyDevFee = buyDevFee;
buyTotalFees = _buyMarketingFee + _buyLiquidityFee + _buyDevFee;
_sellMarketingFee = sellMarketingFee;
_sellLiquidityFee = sellLiquidityFee;
_sellDevFee = sellDevFee;
sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 4,843,767 |
./full_match/1/0x09c78EB6A65CbF17a589A387A6752316A65b4D3f/sources/contracts/strategies/compound/CompoundStrategy.sol | Approve all required tokens | function _approveToken(uint256 _amount) internal override {
collateralToken.approve(pool, _amount);
collateralToken.approve(address(cToken), _amount);
for (uint256 i = 0; i < swapManager.N_DEX(); i++) {
IERC20(COMP).approve(address(swapManager.ROUTERS(i)), _amount);
}
}
| 17,066,709 |
//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
contract ORAcURLCaller {
//dispatcher proxy contract address
DispatcherInterface public dispatcher = DispatcherInterface(0x9565B24fbe3E386191B61f56cC6249ECFF3ab489);
address dispatcherAddress = 0x9565B24fbe3E386191B61f56cC6249ECFF3ab489;
//DispatcherInterface public dispatcher;
bool internal useLocalQueueFeatures = true;
//internal queue
mapping(bytes32 => uint) localQueueMap;
bytes32[] localQueueArray;
event CalledBack(
bytes32 callID,
bytes32 response
);
/*
* cURL receives the endpointID, the name of the callback function, and vars to be sent in the cURL
*
* You can optionally specify the wei to send for the trip back + tip as a parameter, otherwise it will send all of msg.value
*/
function cURL(uint128 _endpointID, bytes32 _callback, bytes32 _calldata, uint _value) internal returns(bytes32, uint) {
//todo: verify
//nonce to be able to re-try or unstick a call with insufficient funds
uint _nonce = 0;
//create callID using hash of this contract's address + timestamp
bytes32 _callID = keccak256(abi.encodePacked(
_endpointID, _callback, _calldata, _nonce, block.timestamp));
//change state
if(useLocalQueueFeatures){
localQueueMap[_callID] = _nonce;
localQueueArray.push(_callID);
}
if(_value == 0){
_value = msg.value;
}
require(_value > 0, "Insufficient funds.");
//require(
dispatcher.cURL{value: _value}(
_endpointID, _callID, _callback, _nonce, _calldata
);
//);
return (_callID, _nonce);
}
function cURL(uint128 _endpointID, bytes32 _callback, bytes32 _calldata) internal returns(bytes32, uint) {
uint _value = 0;
return cURL(_endpointID, _callback, _calldata, _value);
}
function cURL(uint128 _endpointID, bytes32 _callback) internal returns(bytes32, uint){
uint _value = 0;
bytes32 _calldata;
return cURL(_endpointID, _callback, _calldata, _value);
}
modifier handlesCallback(bytes32 _callID, bytes32 _response){
//callback can only be called by the proxy contract address
require(msg.sender == dispatcherAddress);
emit CalledBack(_callID, _response);
_;
}
function recoverTip() internal{
//call collectGarbage to recover remaining gwei (including tip)
}
function nudge() public payable {
//send additional funds to a curl that is stuck
// https://www.quiknode.io/guides/web3-sdks/how-to-re-send-a-transaction-with-higher-gas-price-using-ethers-js
}
function splitSignature(bytes memory sig)
internal
pure
returns (uint8 v, bytes32 r, bytes32 s)
{
require(sig.length == 65);
assembly {
// first 32 bytes, after the length prefix.
r := mload(add(sig, 32))
// second 32 bytes.
s := mload(add(sig, 64))
// final byte (first byte of the next 32 bytes).
v := byte(0, mload(add(sig, 96)))
}
return (v, r, s);
}
}
contract DispatcherInterface {
event addedToQueue(
//endpointID
uint128 endpointID,
//callID
bytes32 callID,
//nonce
uint nonce,
//callback
bytes32 callback,
//parameters should be sent, but not indexed
bytes32 payload
);
uint128 minimumTip;
uint48 timeoutInSeconds;
address public authorizer;
mapping(bytes32 => uint) queue;
constructor() {}
function cURL(
uint128 _endpointID, bytes32 _callID, bytes32 _callback,
uint _nonce, bytes32 payload)
public payable {}
} | cURL receives the endpointID, the name of the callback function, and vars to be sent in the cURL You can optionally specify the wei to send for the trip back + tip as a parameter, otherwise it will send all of msg.value/todo: verifynonce to be able to re-try or unstick a call with insufficient fundscreate callID using hash of this contract's address + timestampchange state | function cURL(uint128 _endpointID, bytes32 _callback, bytes32 _calldata, uint _value) internal returns(bytes32, uint) {
uint _nonce = 0;
bytes32 _callID = keccak256(abi.encodePacked(
_endpointID, _callback, _calldata, _nonce, block.timestamp));
if(useLocalQueueFeatures){
localQueueMap[_callID] = _nonce;
localQueueArray.push(_callID);
}
if(_value == 0){
_value = msg.value;
}
require(_value > 0, "Insufficient funds.");
_endpointID, _callID, _callback, _nonce, _calldata
);
}
| 6,467,047 |
./full_match/3/0xaAA567FBA9D8C427E6cEB97280fA5ef32E53EF16/sources/interface.sol | interface IUniswapV2Pair | interface V2PoolInterface {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
| 8,111,199 |
./partial_match/1/0xc880c252db7C51F74161633338A3BdafA8E65276/sources/BancorBridge.sol | solhint-disable no-empty-blocks Payable fallback to receive ETH from Bancor/WETH. Poor man's receive in 0.5.9 | function ()
external
payable
{
require(msg.data.length == 0);
}
| 10,999,203 |
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity ^0.7.1;
//
/******************************************************************************\
* Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen)
/******************************************************************************/
interface IDiamondCut {
enum FacetCutAction {Add, Replace, Remove}
struct FacetCut {
address facetAddress;
FacetCutAction action;
bytes4[] functionSelectors;
}
/// @notice Add/replace/remove any number of functions and optionally execute
/// a function with delegatecall
/// @param _diamondCut Contains the facet addresses and function selectors
/// @param _init The address of the contract or facet to execute _calldata
/// @param _calldata A function call, including function selector and arguments
/// _calldata is executed with delegatecall on _init
function diamondCut(
FacetCut[] calldata _diamondCut,
address _init,
bytes calldata _calldata
) external;
event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata);
}
//
/******************************************************************************\
* Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen)
*
* Implementation of internal diamondCut function.
/******************************************************************************/
library LibDiamond {
bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage");
struct FacetAddressAndPosition {
address facetAddress;
uint16 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array
}
struct FacetFunctionSelectors {
bytes4[] functionSelectors;
uint16 facetAddressPosition; // position of facetAddress in facetAddresses array
}
struct DiamondStorage {
// maps function selector to the facet address and
// the position of the selector in the facetFunctionSelectors.selectors array
mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition;
// maps facet addresses to function selectors
mapping(address => FacetFunctionSelectors) facetFunctionSelectors;
// facet addresses
address[] facetAddresses;
// Used to query if a contract implements an interface.
// Used to implement ERC-165.
mapping(bytes4 => bool) supportedInterfaces;
// owner of the contract
address contractOwner;
}
function diamondStorage() internal pure returns (DiamondStorage storage ds) {
bytes32 position = DIAMOND_STORAGE_POSITION;
assembly {
ds.slot := position
}
}
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function setContractOwner(address _newOwner) internal {
DiamondStorage storage ds = diamondStorage();
address previousOwner = ds.contractOwner;
ds.contractOwner = _newOwner;
emit OwnershipTransferred(previousOwner, _newOwner);
}
function contractOwner() internal view returns (address contractOwner_) {
contractOwner_ = diamondStorage().contractOwner;
}
function enforceIsContractOwner() internal view {
require(msg.sender == diamondStorage().contractOwner, "LibDiamond: Must be contract owner");
}
modifier onlyOwner {
require(msg.sender == diamondStorage().contractOwner, "LibDiamond: Must be contract owner");
_;
}
event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata);
// Internal function version of diamondCut
// This code is almost the same as the external diamondCut,
// except it is using 'FacetCut[] memory _diamondCut' instead of
// 'FacetCut[] calldata _diamondCut'.
// The code is duplicated to prevent copying calldata to memory which
// causes an error for a two dimensional array.
function diamondCut(
IDiamondCut.FacetCut[] memory _diamondCut,
address _init,
bytes memory _calldata
) internal {
for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) {
addReplaceRemoveFacetSelectors(
_diamondCut[facetIndex].facetAddress,
_diamondCut[facetIndex].action,
_diamondCut[facetIndex].functionSelectors
);
}
emit DiamondCut(_diamondCut, _init, _calldata);
initializeDiamondCut(_init, _calldata);
}
function addReplaceRemoveFacetSelectors(
address _newFacetAddress,
IDiamondCut.FacetCutAction _action,
bytes4[] memory _selectors
) internal {
DiamondStorage storage ds = diamondStorage();
require(_selectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
// add or replace functions
if (_newFacetAddress != address(0)) {
uint256 facetAddressPosition = ds.facetFunctionSelectors[_newFacetAddress].facetAddressPosition;
// add new facet address if it does not exist
if (facetAddressPosition == 0 && ds.facetFunctionSelectors[_newFacetAddress].functionSelectors.length == 0) {
enforceHasContractCode(_newFacetAddress, "LibDiamondCut: New facet has no code");
facetAddressPosition = ds.facetAddresses.length;
ds.facetAddresses.push(_newFacetAddress);
ds.facetFunctionSelectors[_newFacetAddress].facetAddressPosition = uint16(facetAddressPosition);
}
// add or replace selectors
for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) {
bytes4 selector = _selectors[selectorIndex];
address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress;
// add
if (_action == IDiamondCut.FacetCutAction.Add) {
require(oldFacetAddress == address(0), "LibDiamondCut: Can't add function that already exists");
addSelector(_newFacetAddress, selector);
} else if (_action == IDiamondCut.FacetCutAction.Replace) {
// replace
require(oldFacetAddress != _newFacetAddress, "LibDiamondCut: Can't replace function with same function");
removeSelector(oldFacetAddress, selector);
addSelector(_newFacetAddress, selector);
} else {
revert("LibDiamondCut: Incorrect FacetCutAction");
}
}
} else {
require(_action == IDiamondCut.FacetCutAction.Remove, "LibDiamondCut: action not set to FacetCutAction.Remove");
// remove selectors
for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) {
bytes4 selector = _selectors[selectorIndex];
removeSelector(ds.selectorToFacetAndPosition[selector].facetAddress, selector);
}
}
}
function addSelector(address _newFacet, bytes4 _selector) internal {
DiamondStorage storage ds = diamondStorage();
uint256 selectorPosition = ds.facetFunctionSelectors[_newFacet].functionSelectors.length;
ds.facetFunctionSelectors[_newFacet].functionSelectors.push(_selector);
ds.selectorToFacetAndPosition[_selector].facetAddress = _newFacet;
ds.selectorToFacetAndPosition[_selector].functionSelectorPosition = uint16(selectorPosition);
}
function removeSelector(address _oldFacetAddress, bytes4 _selector) internal {
DiamondStorage storage ds = diamondStorage();
// if function does not exist then do nothing and return
require(_oldFacetAddress != address(0), "LibDiamondCut: Can't remove or replace function that doesn't exist");
require(_oldFacetAddress != address(this), "LibDiamondCut: Can't remove or replace immutable function");
// replace selector with last selector, then delete last selector
uint256 selectorPosition = ds.selectorToFacetAndPosition[_selector].functionSelectorPosition;
uint256 lastSelectorPosition = ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors.length - 1;
// if not the same then replace _selector with lastSelector
if (selectorPosition != lastSelectorPosition) {
bytes4 lastSelector = ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors[lastSelectorPosition];
ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors[selectorPosition] = lastSelector;
ds.selectorToFacetAndPosition[lastSelector].functionSelectorPosition = uint16(selectorPosition);
}
// delete the last selector
ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors.pop();
delete ds.selectorToFacetAndPosition[_selector];
// if no more selectors for facet address then delete the facet address
if (lastSelectorPosition == 0) {
// replace facet address with last facet address and delete last facet address
uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1;
uint256 facetAddressPosition = ds.facetFunctionSelectors[_oldFacetAddress].facetAddressPosition;
if (facetAddressPosition != lastFacetAddressPosition) {
address lastFacetAddress = ds.facetAddresses[lastFacetAddressPosition];
ds.facetAddresses[facetAddressPosition] = lastFacetAddress;
ds.facetFunctionSelectors[lastFacetAddress].facetAddressPosition = uint16(facetAddressPosition);
}
ds.facetAddresses.pop();
delete ds.facetFunctionSelectors[_oldFacetAddress];
}
}
function initializeDiamondCut(address _init, bytes memory _calldata) internal {
if (_init == address(0)) {
require(_calldata.length == 0, "LibDiamondCut: _init is address(0) but_calldata is not empty");
} else {
require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)");
if (_init != address(this)) {
enforceHasContractCode(_init, "LibDiamondCut: _init address has no code");
}
(bool success, bytes memory error) = _init.delegatecall(_calldata);
if (!success) {
if (error.length > 0) {
// bubble up the error
revert(string(error));
} else {
revert("LibDiamondCut: _init function reverted");
}
}
}
}
function enforceHasContractCode(address _contract, string memory _errorMessage) internal view {
uint256 contractSize;
assembly {
contractSize := extcodesize(_contract)
}
require(contractSize > 0, _errorMessage);
}
}
//
library LibReentryProtectionStorage {
bytes32 constant REENTRY_STORAGE_POSITION = keccak256(
"diamond.standard.reentry.storage"
);
struct RPStorage {
uint256 lockCounter;
}
function rpStorage() internal pure returns (RPStorage storage bs) {
bytes32 position = REENTRY_STORAGE_POSITION;
assembly {
bs.slot := position
}
}
}
//
contract ReentryProtectionFacet {
modifier noReentry {
// Use counter to only write to storage once
LibReentryProtectionStorage.RPStorage storage s
= LibReentryProtectionStorage.rpStorage();
s.lockCounter++;
uint256 lockValue = s.lockCounter;
_;
require(
lockValue == s.lockCounter,
"ReentryProtectionFacet.noReentry: reentry detected"
);
}
}
//
contract CallFacet is ReentryProtectionFacet {
function call(
address[] memory _targets,
bytes[] memory _calldata,
uint256[] memory _values
) external noReentry {
// ONLY THE OWNER CAN DO ARBITRARY CALLS
require(msg.sender == LibDiamond.diamondStorage().contractOwner);
require(
_targets.length == _calldata.length && _values.length == _calldata.length,
"ARRAY_LENGTH_MISMATCH"
);
for (uint256 i = 0; i < _targets.length; i++) {
// address(test).call{value: 1}(abi.encodeWithSignature("nonExistingFunction()"))
(bool success, ) = _targets[i].call{ value: _values[i] }(_calldata[i]);
require(success, "CALL_FAILED");
}
}
} | if function does not exist then do nothing and return replace selector with last selector, then delete last selector if not the same then replace _selector with lastSelector delete the last selector if no more selectors for facet address then delete the facet address replace facet address with last facet address and delete last facet address | function removeSelector(address _oldFacetAddress, bytes4 _selector) internal {
DiamondStorage storage ds = diamondStorage();
require(_oldFacetAddress != address(0), "LibDiamondCut: Can't remove or replace function that doesn't exist");
require(_oldFacetAddress != address(this), "LibDiamondCut: Can't remove or replace immutable function");
uint256 selectorPosition = ds.selectorToFacetAndPosition[_selector].functionSelectorPosition;
uint256 lastSelectorPosition = ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors.length - 1;
if (selectorPosition != lastSelectorPosition) {
bytes4 lastSelector = ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors[lastSelectorPosition];
ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors[selectorPosition] = lastSelector;
ds.selectorToFacetAndPosition[lastSelector].functionSelectorPosition = uint16(selectorPosition);
}
ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors.pop();
delete ds.selectorToFacetAndPosition[_selector];
if (lastSelectorPosition == 0) {
uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1;
uint256 facetAddressPosition = ds.facetFunctionSelectors[_oldFacetAddress].facetAddressPosition;
if (facetAddressPosition != lastFacetAddressPosition) {
address lastFacetAddress = ds.facetAddresses[lastFacetAddressPosition];
ds.facetAddresses[facetAddressPosition] = lastFacetAddress;
ds.facetFunctionSelectors[lastFacetAddress].facetAddressPosition = uint16(facetAddressPosition);
}
ds.facetAddresses.pop();
delete ds.facetFunctionSelectors[_oldFacetAddress];
}
}
| 2,193,502 |
./partial_match/42/0xDaFBf3142aEC7FCbE3c7600287A3D5476FE0ceBC/sources/MySuperCompliance.sol | See {ICompliance-destroyed}./ | function destroyed(address _from, uint256 _value) external onlyToken override {
destructionActionOnCountryRestrictions(_from, _value);
}
| 8,842,178 |
./full_match/1/0x9965cCd16803432C6a0842f1D5690f32E427aEDd/sources/contracts/Marketplace.sol | Changes The Amount Of NFTs For Sale/ | function __ChangeFixedPriceAmountForSale(uint SaleIndex, uint AmountForSale) external onlyAdmin { FixedPriceSales[SaleIndex]._AmountForSale = AmountForSale; }
| 8,471,316 |
pragma solidity ^0.5.0;
import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
contract Exchange {
using SafeMath for uint256;
//vars
address constant ETHER = address(0);
address payable public feeAccount;
uint256 public feePercent;
mapping(address => mapping(address => uint256)) public tokens;
mapping(uint256 => _Order) public orders;
mapping(uint256 => bool) public orderCancelled;
mapping(uint256 => bool) public orderFilled;
uint256 public orderCount;
//structs
struct _Order {
uint256 id;
address user;
address tokenGet;
uint256 amountGet;
address tokenGive;
uint256 amountGive;
uint256 timestamp;
}
//events
event Deposit(address _token, address _user, uint256 _amount, uint256 _balance);
event Withdraw(address _token, address _user, uint256 _amount, uint256 _balance);
event Order(uint256 _id, address _user, address _tokenGet, uint256 _amountGet,
address _tokenGive, uint256 _amountGive, uint256 _timestamp);
event Cancel(uint256 _id, address _user, address _tokenGet, uint256 _amountGet, address _tokenGive, uint256 _amountGive,
uint256 _timestamp);
event Trade(uint256 _id, address _user, address _tokenGet, uint256 _amountGet, address _tokenGive, uint256 _amountGive,
address _userFill, uint256 _timestamp);
//constructor
constructor (address payable _feeAccount, uint256 _feePercent) public {
feeAccount = _feeAccount;
feePercent = _feePercent;
}
function fillOrder(uint256 _id) public {
//require order is valid, not filled or cancelled already
require(_id > 0 && _id <= orderCount, "Invalid order id");
require(!orderCancelled[_id], "Order cancelled before fill");
require(!orderFilled[_id], "Order filled already");
//fetch order
_Order storage _order = orders[_id];
//do trade
_trade(_order.id, _order.user, _order.tokenGet, _order.amountGet, _order.tokenGive, _order.amountGive);
//mark order as filled
orderFilled[_id] = true;
}
function _trade(uint256 _id, address _user, address _tokenGet, uint256 _amountGet, address _tokenGive, uint256 _amountGive) internal {
//charge fees - taken from filler of order (msg.sender)
uint256 _feeAmount = _amountGet.mul(feePercent).div(100);
//DO TRADE
//msg.sender is the person filling order, _user the person who made the order
//move order fillers tokens to order maker, whilst subtracting fees from filler
tokens[_tokenGet][msg.sender] = tokens[_tokenGet][msg.sender].sub(_amountGet.add(_feeAmount));
tokens[_tokenGet][_user] = tokens[_tokenGet][_user].add(_amountGet);
//take fees to fee account
tokens[_tokenGet][feeAccount] = tokens[_tokenGet][feeAccount].add(_feeAmount);
//move order makers tokens to order filler
tokens[_tokenGive][_user] = tokens[_tokenGive][_user].sub(_amountGive);
tokens[_tokenGive][msg.sender] = tokens[_tokenGive][msg.sender].add(_amountGive);
//emit event
emit Trade(_id, _user, _tokenGet, _amountGet, _tokenGive, _amountGive, msg.sender, now);
}
//make order
function makeOrder(address _tokenGet, uint256 _amountGet, address _tokenGive, uint256 _amountGive) public {
//increment ordercount
orderCount = orderCount.add(1);
//add order to orders mapping by creating new struct
orders[orderCount] = _Order(orderCount, msg.sender, _tokenGet, _amountGet, _tokenGive, _amountGive, now);
//emit event
emit Order(orderCount, msg.sender, _tokenGet, _amountGet, _tokenGive, _amountGive, now);
}
//cancel order
function cancelOrder(uint256 _id) public returns (bool){
//retrieve order
_Order storage _order = orders[_id];
//require user is owner of order
require(address(_order.user) == msg.sender, "Must be order user to cancel");
//require valid order id
require(_id == _order.id, "Not valid order id");
//add to cancelled orders mapping
orderCancelled[_id] = true;
//emit event
emit Cancel(_id, _order.user, _order.tokenGet, _order.amountGet, _order.tokenGive, _order.amountGive, now);
//return true for cancelled order
return orderCancelled[_id];
}
//deposit erc20 tokens
function depositToken(address _tokenAddress, uint256 _amount) public {
//don't allow ether deposits
require(_tokenAddress != ETHER, "Can't send ether to this function");
//require this so we only continue if transfer occurs
require(IERC20(_tokenAddress).transferFrom(msg.sender, address(this), _amount), "Could not transfer");
//add to balance
tokens[_tokenAddress][msg.sender] = tokens[_tokenAddress][msg.sender].add(_amount);
//emit event
emit Deposit(_tokenAddress, msg.sender, _amount, tokens[_tokenAddress][msg.sender]);
}
//withdraw erc20 tokens
function withdrawToken(address _tokenAddress, uint256 _amount) public {
//dont allow ether
require(_tokenAddress != ETHER, "Token address not valid");
//require balance to be greater than amount
require(tokens[_tokenAddress][msg.sender] >= _amount, "Not enough tokens");
//subtract tokens
tokens[_tokenAddress][msg.sender] = tokens[_tokenAddress][msg.sender].sub(_amount);
//send tokens and require the transfer goes through
require(IERC20(_tokenAddress).transfer(msg.sender, _amount), "Could not transfer");
//emit event
emit Withdraw(_tokenAddress, msg.sender, _amount, tokens[_tokenAddress][msg.sender]);
}
//deposit ether
function depositEther() public payable {
//use tokens mapping to store ether
tokens[ETHER][msg.sender] = tokens[ETHER][msg.sender].add(msg.value);
//emit event
emit Deposit(ETHER, msg.sender, msg.value, tokens[ETHER][msg.sender]);
}
//withdraw ether
function withdrawEther(uint256 _amount) public {
//require balance to be greater than amount
require(tokens[ETHER][msg.sender] >= _amount, "Not enough ether");
//subtract ether
tokens[ETHER][msg.sender] = tokens[ETHER][msg.sender].sub(_amount);
//send ether
msg.sender.transfer(_amount);
//emit event
emit Withdraw(ETHER, msg.sender, _amount, tokens[ETHER][msg.sender]);
}
//balance of user
function balanceOf(address _tokenAddress, address _user) public view returns (uint256){
return tokens[_tokenAddress][_user];
}
//fallback
function() external {
revert("Cannot send ether directly to exchange");
}
} | charge fees - taken from filler of order (msg.sender)DO TRADEmsg.sender is the person filling order, _user the person who made the ordermove order fillers tokens to order maker, whilst subtracting fees from fillertake fees to fee accountmove order makers tokens to order filleremit event | function _trade(uint256 _id, address _user, address _tokenGet, uint256 _amountGet, address _tokenGive, uint256 _amountGive) internal {
uint256 _feeAmount = _amountGet.mul(feePercent).div(100);
tokens[_tokenGet][msg.sender] = tokens[_tokenGet][msg.sender].sub(_amountGet.add(_feeAmount));
tokens[_tokenGet][_user] = tokens[_tokenGet][_user].add(_amountGet);
tokens[_tokenGet][feeAccount] = tokens[_tokenGet][feeAccount].add(_feeAmount);
tokens[_tokenGive][_user] = tokens[_tokenGive][_user].sub(_amountGive);
tokens[_tokenGive][msg.sender] = tokens[_tokenGive][msg.sender].add(_amountGive);
emit Trade(_id, _user, _tokenGet, _amountGet, _tokenGive, _amountGive, msg.sender, now);
}
| 2,576,615 |
pragma solidity ^0.8.11;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {Unauthorized, IllegalState, IllegalArgument} from "./base/Errors.sol";
import "./base/Multicall.sol";
import "./base/Mutex.sol";
import "./interfaces/IAlchemistV2.sol";
import "./interfaces/IERC20Minimal.sol";
import "./interfaces/IERC20TokenReceiver.sol";
import "./interfaces/ITokenAdapter.sol";
import "./interfaces/IAlchemicToken.sol";
import "./interfaces/IWhitelist.sol";
import "./libraries/SafeCast.sol";
import "./libraries/Sets.sol";
import "./libraries/TokenUtils.sol";
import "./libraries/Limiters.sol";
/// @title AlchemistV2
/// @author Alchemix Finance
contract AlchemistV2 is IAlchemistV2, Initializable, Multicall, Mutex {
using Limiters for Limiters.LinearGrowthLimiter;
using Sets for Sets.AddressSet;
/// @notice A user account.
struct Account {
// A signed value which represents the current amount of debt or credit that the account has accrued.
// Positive values indicate debt, negative values indicate credit.
int256 debt;
// The share balances for each yield token.
mapping(address => uint256) balances;
// The last values recorded for accrued weights for each yield token.
mapping(address => uint256) lastAccruedWeights;
// The set of yield tokens that the account has deposited into the system.
Sets.AddressSet depositedTokens;
// The allowances for mints.
mapping(address => uint256) mintAllowances;
// The allowances for withdrawals.
mapping(address => mapping(address => uint256)) withdrawAllowances;
}
/// @notice The number of basis points there are to represent exactly 100%.
uint256 public constant BPS = 10000;
/// @notice The scalar used for conversion of integral numbers to fixed point numbers. Fixed point numbers in this
/// implementation have 18 decimals of resolution, meaning that 1 is represented as 1e18, 0.5 is
/// represented as 5e17, and 2 is represented as 2e18.
uint256 public constant FIXED_POINT_SCALAR = 1e18;
/// @inheritdoc IAlchemistV2Immutables
string public constant override version = "2.2.6";
/// @inheritdoc IAlchemistV2Immutables
address public override debtToken;
/// @inheritdoc IAlchemistV2State
address public override admin;
/// @inheritdoc IAlchemistV2State
address public override pendingAdmin;
/// @inheritdoc IAlchemistV2State
mapping(address => bool) public override sentinels;
/// @inheritdoc IAlchemistV2State
mapping(address => bool) public override keepers;
/// @inheritdoc IAlchemistV2State
address public override transmuter;
/// @inheritdoc IAlchemistV2State
uint256 public override minimumCollateralization;
/// @inheritdoc IAlchemistV2State
uint256 public override protocolFee;
/// @inheritdoc IAlchemistV2State
address public override protocolFeeReceiver;
/// @inheritdoc IAlchemistV2State
address public override whitelist;
/// @dev A linear growth function that limits the amount of debt-token minted.
Limiters.LinearGrowthLimiter private _mintingLimiter;
// @dev The repay limiters for each underlying token.
mapping(address => Limiters.LinearGrowthLimiter) private _repayLimiters;
// @dev The liquidation limiters for each underlying token.
mapping(address => Limiters.LinearGrowthLimiter) private _liquidationLimiters;
/// @dev Accounts mapped by the address that owns them.
mapping(address => Account) private _accounts;
/// @dev Underlying token parameters mapped by token address.
mapping(address => UnderlyingTokenParams) private _underlyingTokens;
/// @dev Yield token parameters mapped by token address.
mapping(address => YieldTokenParams) private _yieldTokens;
/// @dev An iterable set of the underlying tokens that are supported by the system.
Sets.AddressSet private _supportedUnderlyingTokens;
/// @dev An iterable set of the yield tokens that are supported by the system.
Sets.AddressSet private _supportedYieldTokens;
constructor() initializer {}
/// @inheritdoc IAlchemistV2State
function getYieldTokensPerShare(address yieldToken) external view override returns (uint256) {
return _convertSharesToYieldTokens(yieldToken, 10**_yieldTokens[yieldToken].decimals);
}
/// @inheritdoc IAlchemistV2State
function getUnderlyingTokensPerShare(address yieldToken) external view override returns (uint256) {
return _convertSharesToUnderlyingTokens(yieldToken, 10**_yieldTokens[yieldToken].decimals);
}
/// @inheritdoc IAlchemistV2State
function getSupportedUnderlyingTokens() external view override returns (address[] memory) {
return _supportedUnderlyingTokens.values;
}
/// @inheritdoc IAlchemistV2State
function getSupportedYieldTokens() external view override returns (address[] memory) {
return _supportedYieldTokens.values;
}
/// @inheritdoc IAlchemistV2State
function isSupportedUnderlyingToken(address underlyingToken) external view override returns (bool) {
return _supportedUnderlyingTokens.contains(underlyingToken);
}
/// @inheritdoc IAlchemistV2State
function isSupportedYieldToken(address yieldToken) external view override returns (bool) {
return _supportedYieldTokens.contains(yieldToken);
}
/// @inheritdoc IAlchemistV2State
function accounts(address owner)
external view override
returns (
int256 debt,
address[] memory depositedTokens
)
{
Account storage account = _accounts[owner];
return (
_calculateUnrealizedDebt(owner),
account.depositedTokens.values
);
}
/// @inheritdoc IAlchemistV2State
function positions(address owner, address yieldToken)
external view override
returns (
uint256 shares,
uint256 lastAccruedWeight
)
{
Account storage account = _accounts[owner];
return (account.balances[yieldToken], account.lastAccruedWeights[yieldToken]);
}
/// @inheritdoc IAlchemistV2State
function mintAllowance(address owner, address spender)
external view override
returns (uint256)
{
Account storage account = _accounts[owner];
return account.mintAllowances[spender];
}
/// @inheritdoc IAlchemistV2State
function withdrawAllowance(address owner, address spender, address yieldToken)
external view override
returns (uint256)
{
Account storage account = _accounts[owner];
return account.withdrawAllowances[spender][yieldToken];
}
/// @inheritdoc IAlchemistV2State
function getUnderlyingTokenParameters(address underlyingToken)
external view override
returns (UnderlyingTokenParams memory)
{
return _underlyingTokens[underlyingToken];
}
/// @inheritdoc IAlchemistV2State
function getYieldTokenParameters(address yieldToken)
external view override
returns (YieldTokenParams memory)
{
return _yieldTokens[yieldToken];
}
/// @inheritdoc IAlchemistV2State
function getMintLimitInfo()
external view override
returns (
uint256 currentLimit,
uint256 rate,
uint256 maximum
)
{
return (
_mintingLimiter.get(),
_mintingLimiter.rate,
_mintingLimiter.maximum
);
}
/// @inheritdoc IAlchemistV2State
function getRepayLimitInfo(address underlyingToken)
external view override
returns (
uint256 currentLimit,
uint256 rate,
uint256 maximum
)
{
Limiters.LinearGrowthLimiter storage limiter = _repayLimiters[underlyingToken];
return (
limiter.get(),
limiter.rate,
limiter.maximum
);
}
/// @inheritdoc IAlchemistV2State
function getLiquidationLimitInfo(address underlyingToken)
external view override
returns (
uint256 currentLimit,
uint256 rate,
uint256 maximum
)
{
Limiters.LinearGrowthLimiter storage limiter = _liquidationLimiters[underlyingToken];
return (
limiter.get(),
limiter.rate,
limiter.maximum
);
}
/// @inheritdoc IAlchemistV2AdminActions
function initialize(InitializationParams memory params) external initializer {
_checkArgument(params.protocolFee <= BPS);
debtToken = params.debtToken;
admin = params.admin;
transmuter = params.transmuter;
minimumCollateralization = params.minimumCollateralization;
protocolFee = params.protocolFee;
protocolFeeReceiver = params.protocolFeeReceiver;
whitelist = params.whitelist;
_mintingLimiter = Limiters.createLinearGrowthLimiter(
params.mintingLimitMaximum,
params.mintingLimitBlocks,
params.mintingLimitMinimum
);
emit AdminUpdated(admin);
emit TransmuterUpdated(transmuter);
emit MinimumCollateralizationUpdated(minimumCollateralization);
emit ProtocolFeeUpdated(protocolFee);
emit ProtocolFeeReceiverUpdated(protocolFeeReceiver);
emit MintingLimitUpdated(params.mintingLimitMaximum, params.mintingLimitBlocks);
}
/// @inheritdoc IAlchemistV2AdminActions
function setPendingAdmin(address value) external override {
_onlyAdmin();
pendingAdmin = value;
emit PendingAdminUpdated(value);
}
/// @inheritdoc IAlchemistV2AdminActions
function acceptAdmin() external override {
_checkState(pendingAdmin != address(0));
if (msg.sender != pendingAdmin) {
revert Unauthorized();
}
admin = pendingAdmin;
pendingAdmin = address(0);
emit AdminUpdated(admin);
emit PendingAdminUpdated(address(0));
}
/// @inheritdoc IAlchemistV2AdminActions
function setSentinel(address sentinel, bool flag) external override {
_onlyAdmin();
sentinels[sentinel] = flag;
emit SentinelSet(sentinel, flag);
}
/// @inheritdoc IAlchemistV2AdminActions
function setKeeper(address keeper, bool flag) external override {
_onlyAdmin();
keepers[keeper] = flag;
emit KeeperSet(keeper, flag);
}
/// @inheritdoc IAlchemistV2AdminActions
function addUnderlyingToken(address underlyingToken, UnderlyingTokenConfig calldata config) external override lock {
_onlyAdmin();
_checkState(!_supportedUnderlyingTokens.contains(underlyingToken));
uint8 tokenDecimals = TokenUtils.expectDecimals(underlyingToken);
uint8 debtTokenDecimals = TokenUtils.expectDecimals(debtToken);
_checkArgument(tokenDecimals <= debtTokenDecimals);
_underlyingTokens[underlyingToken] = UnderlyingTokenParams({
decimals: tokenDecimals,
conversionFactor: 10**(debtTokenDecimals - tokenDecimals),
enabled: false
});
_repayLimiters[underlyingToken] = Limiters.createLinearGrowthLimiter(
config.repayLimitMaximum,
config.repayLimitBlocks,
config.repayLimitMinimum
);
_liquidationLimiters[underlyingToken] = Limiters.createLinearGrowthLimiter(
config.liquidationLimitMaximum,
config.liquidationLimitBlocks,
config.liquidationLimitMinimum
);
_supportedUnderlyingTokens.add(underlyingToken);
emit AddUnderlyingToken(underlyingToken);
}
/// @inheritdoc IAlchemistV2AdminActions
function addYieldToken(address yieldToken, YieldTokenConfig calldata config) external override lock {
_onlyAdmin();
_checkArgument(config.maximumLoss <= BPS);
_checkArgument(config.creditUnlockBlocks > 0);
_checkState(!_supportedYieldTokens.contains(yieldToken));
ITokenAdapter adapter = ITokenAdapter(config.adapter);
_checkState(yieldToken == adapter.token());
_checkSupportedUnderlyingToken(adapter.underlyingToken());
_yieldTokens[yieldToken] = YieldTokenParams({
decimals: TokenUtils.expectDecimals(yieldToken),
underlyingToken: adapter.underlyingToken(),
adapter: config.adapter,
maximumLoss: config.maximumLoss,
maximumExpectedValue: config.maximumExpectedValue,
creditUnlockRate: FIXED_POINT_SCALAR / config.creditUnlockBlocks,
activeBalance: 0,
harvestableBalance: 0,
totalShares: 0,
expectedValue: 0,
accruedWeight: 0,
pendingCredit: 0,
distributedCredit: 0,
lastDistributionBlock: 0,
enabled: false
});
_supportedYieldTokens.add(yieldToken);
TokenUtils.safeApprove(yieldToken, config.adapter, type(uint256).max);
TokenUtils.safeApprove(adapter.underlyingToken(), config.adapter, type(uint256).max);
emit AddYieldToken(yieldToken);
emit TokenAdapterUpdated(yieldToken, config.adapter);
emit MaximumLossUpdated(yieldToken, config.maximumLoss);
}
/// @inheritdoc IAlchemistV2AdminActions
function setUnderlyingTokenEnabled(address underlyingToken, bool enabled) external override {
_onlySentinelOrAdmin();
_checkSupportedUnderlyingToken(underlyingToken);
_underlyingTokens[underlyingToken].enabled = enabled;
emit UnderlyingTokenEnabled(underlyingToken, enabled);
}
/// @inheritdoc IAlchemistV2AdminActions
function setYieldTokenEnabled(address yieldToken, bool enabled) external override {
_onlySentinelOrAdmin();
_checkSupportedYieldToken(yieldToken);
_yieldTokens[yieldToken].enabled = enabled;
emit YieldTokenEnabled(yieldToken, enabled);
}
/// @inheritdoc IAlchemistV2AdminActions
function configureRepayLimit(address underlyingToken, uint256 maximum, uint256 blocks) external override {
_onlyAdmin();
_checkSupportedUnderlyingToken(underlyingToken);
_repayLimiters[underlyingToken].update();
_repayLimiters[underlyingToken].configure(maximum, blocks);
emit RepayLimitUpdated(underlyingToken, maximum, blocks);
}
/// @inheritdoc IAlchemistV2AdminActions
function configureLiquidationLimit(address underlyingToken, uint256 maximum, uint256 blocks) external override {
_onlyAdmin();
_checkSupportedUnderlyingToken(underlyingToken);
_liquidationLimiters[underlyingToken].update();
_liquidationLimiters[underlyingToken].configure(maximum, blocks);
emit LiquidationLimitUpdated(underlyingToken, maximum, blocks);
}
/// @inheritdoc IAlchemistV2AdminActions
function setTransmuter(address value) external override {
_onlyAdmin();
_checkArgument(value != address(0));
transmuter = value;
emit TransmuterUpdated(value);
}
/// @inheritdoc IAlchemistV2AdminActions
function setMinimumCollateralization(uint256 value) external override {
_onlyAdmin();
minimumCollateralization = value;
emit MinimumCollateralizationUpdated(value);
}
/// @inheritdoc IAlchemistV2AdminActions
function setProtocolFee(uint256 value) external override {
_onlyAdmin();
_checkArgument(value <= BPS);
protocolFee = value;
emit ProtocolFeeUpdated(value);
}
/// @inheritdoc IAlchemistV2AdminActions
function setProtocolFeeReceiver(address value) external override {
_onlyAdmin();
_checkArgument(value != address(0));
protocolFeeReceiver = value;
emit ProtocolFeeReceiverUpdated(value);
}
/// @inheritdoc IAlchemistV2AdminActions
function configureMintingLimit(uint256 maximum, uint256 rate) external override {
_onlyAdmin();
_mintingLimiter.update();
_mintingLimiter.configure(maximum, rate);
emit MintingLimitUpdated(maximum, rate);
}
/// @inheritdoc IAlchemistV2AdminActions
function configureCreditUnlockRate(address yieldToken, uint256 blocks) external override {
_onlyAdmin();
_checkArgument(blocks > 0);
_checkSupportedYieldToken(yieldToken);
_yieldTokens[yieldToken].creditUnlockRate = FIXED_POINT_SCALAR / blocks;
emit CreditUnlockRateUpdated(yieldToken, blocks);
}
/// @inheritdoc IAlchemistV2AdminActions
function setTokenAdapter(address yieldToken, address adapter) external override {
_onlyAdmin();
_checkState(yieldToken == ITokenAdapter(adapter).token());
_checkSupportedYieldToken(yieldToken);
_yieldTokens[yieldToken].adapter = adapter;
TokenUtils.safeApprove(yieldToken, adapter, type(uint256).max);
TokenUtils.safeApprove(ITokenAdapter(adapter).underlyingToken(), adapter, type(uint256).max);
emit TokenAdapterUpdated(yieldToken, adapter);
}
/// @inheritdoc IAlchemistV2AdminActions
function setMaximumExpectedValue(address yieldToken, uint256 value) external override {
_onlyAdmin();
_checkSupportedYieldToken(yieldToken);
_yieldTokens[yieldToken].maximumExpectedValue = value;
emit MaximumExpectedValueUpdated(yieldToken, value);
}
/// @inheritdoc IAlchemistV2AdminActions
function setMaximumLoss(address yieldToken, uint256 value) external override {
_onlyAdmin();
_checkArgument(value <= BPS);
_checkSupportedYieldToken(yieldToken);
_yieldTokens[yieldToken].maximumLoss = value;
emit MaximumLossUpdated(yieldToken, value);
}
/// @inheritdoc IAlchemistV2AdminActions
function snap(address yieldToken) external override lock {
_onlyAdmin();
_checkSupportedYieldToken(yieldToken);
uint256 expectedValue = _convertYieldTokensToUnderlying(yieldToken, _yieldTokens[yieldToken].activeBalance);
_yieldTokens[yieldToken].expectedValue = expectedValue;
emit Snap(yieldToken, expectedValue);
}
/// @inheritdoc IAlchemistV2Actions
function approveMint(address spender, uint256 amount) external override {
_onlyWhitelisted();
_approveMint(msg.sender, spender, amount);
}
/// @inheritdoc IAlchemistV2Actions
function approveWithdraw(address spender, address yieldToken, uint256 shares) external override {
_onlyWhitelisted();
_checkSupportedYieldToken(yieldToken);
_approveWithdraw(msg.sender, spender, yieldToken, shares);
}
/// @inheritdoc IAlchemistV2Actions
function poke(address owner) external override lock {
_onlyWhitelisted();
_preemptivelyHarvestDeposited(owner);
_distributeUnlockedCreditDeposited(owner);
_poke(owner);
}
/// @inheritdoc IAlchemistV2Actions
function deposit(
address yieldToken,
uint256 amount,
address recipient
) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(recipient != address(0));
_checkSupportedYieldToken(yieldToken);
// Deposit the yield tokens to the recipient.
uint256 shares = _deposit(yieldToken, amount, recipient);
// Transfer tokens from the message sender now that the internal storage updates have been committed.
TokenUtils.safeTransferFrom(yieldToken, msg.sender, address(this), amount);
return shares;
}
/// @inheritdoc IAlchemistV2Actions
function depositUnderlying(
address yieldToken,
uint256 amount,
address recipient,
uint256 minimumAmountOut
) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(recipient != address(0));
_checkSupportedYieldToken(yieldToken);
// Before depositing, the underlying tokens must be wrapped into yield tokens.
uint256 amountYieldTokens = _wrap(yieldToken, amount, minimumAmountOut);
// Deposit the yield-tokens to the recipient.
return _deposit(yieldToken, amountYieldTokens, recipient);
}
/// @inheritdoc IAlchemistV2Actions
function withdraw(
address yieldToken,
uint256 shares,
address recipient
) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(recipient != address(0));
_checkSupportedYieldToken(yieldToken);
// Withdraw the shares from the system.
uint256 amountYieldTokens = _withdraw(yieldToken, msg.sender, shares, recipient);
// Transfer the yield tokens to the recipient.
TokenUtils.safeTransfer(yieldToken, recipient, amountYieldTokens);
return amountYieldTokens;
}
/// @inheritdoc IAlchemistV2Actions
function withdrawFrom(
address owner,
address yieldToken,
uint256 shares,
address recipient
) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(recipient != address(0));
_checkSupportedYieldToken(yieldToken);
// Preemptively try and decrease the withdrawal allowance. This will save gas when the allowance is not
// sufficient for the withdrawal.
_decreaseWithdrawAllowance(owner, msg.sender, yieldToken, shares);
// Withdraw the shares from the system.
uint256 amountYieldTokens = _withdraw(yieldToken, owner, shares, recipient);
// Transfer the yield tokens to the recipient.
TokenUtils.safeTransfer(yieldToken, recipient, amountYieldTokens);
return amountYieldTokens;
}
/// @inheritdoc IAlchemistV2Actions
function withdrawUnderlying(
address yieldToken,
uint256 shares,
address recipient,
uint256 minimumAmountOut
) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(recipient != address(0));
_checkSupportedYieldToken(yieldToken);
_checkLoss(yieldToken);
uint256 amountYieldTokens = _withdraw(yieldToken, msg.sender, shares, recipient);
return _unwrap(yieldToken, amountYieldTokens, recipient, minimumAmountOut);
}
/// @inheritdoc IAlchemistV2Actions
function withdrawUnderlyingFrom(
address owner,
address yieldToken,
uint256 shares,
address recipient,
uint256 minimumAmountOut
) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(recipient != address(0));
_checkSupportedYieldToken(yieldToken);
_checkLoss(yieldToken);
_decreaseWithdrawAllowance(owner, msg.sender, yieldToken, shares);
uint256 amountYieldTokens = _withdraw(yieldToken, owner, shares, recipient);
return _unwrap(yieldToken, amountYieldTokens, recipient, minimumAmountOut);
}
/// @inheritdoc IAlchemistV2Actions
function mint(uint256 amount, address recipient) external override lock {
_onlyWhitelisted();
_checkArgument(amount > 0);
_checkArgument(recipient != address(0));
// Mint tokens from the message sender's account to the recipient.
_mint(msg.sender, amount, recipient);
}
/// @inheritdoc IAlchemistV2Actions
function mintFrom(
address owner,
uint256 amount,
address recipient
) external override lock {
_onlyWhitelisted();
_checkArgument(amount > 0);
_checkArgument(recipient != address(0));
// Preemptively try and decrease the minting allowance. This will save gas when the allowance is not sufficient
// for the mint.
_decreaseMintAllowance(owner, msg.sender, amount);
// Mint tokens from the owner's account to the recipient.
_mint(owner, amount, recipient);
}
/// @inheritdoc IAlchemistV2Actions
function burn(uint256 amount, address recipient) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(amount > 0);
_checkArgument(recipient != address(0));
// Distribute unlocked credit to depositors.
_distributeUnlockedCreditDeposited(recipient);
// Update the recipient's account, decrease the debt of the recipient by the number of tokens burned.
_poke(recipient);
// Check that the debt is greater than zero.
//
// It is possible that the number of debt which is repayable is equal to or less than zero after realizing the
// credit that was earned since the last update. We do not want to perform a noop so we need to check that the
// amount of debt to repay is greater than zero.
int256 debt;
_checkState((debt = _accounts[recipient].debt) > 0);
// Limit how much debt can be repaid up to the current amount of debt that the account has. This prevents
// situations where the user may be trying to repay their entire debt, but it decreases since they send the
// transaction and causes a revert because burning can never decrease the debt below zero.
//
// Casts here are safe because it is asserted that debt is greater than zero.
uint256 credit = amount > uint256(debt) ? uint256(debt) : amount;
// Update the recipient's debt.
_updateDebt(recipient, -SafeCast.toInt256(credit));
// Burn the tokens from the message sender.
TokenUtils.safeBurnFrom(debtToken, msg.sender, credit);
emit Burn(msg.sender, credit, recipient);
return credit;
}
/// @inheritdoc IAlchemistV2Actions
function repay(address underlyingToken, uint256 amount, address recipient) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(amount > 0);
_checkArgument(recipient != address(0));
_checkSupportedUnderlyingToken(underlyingToken);
_checkUnderlyingTokenEnabled(underlyingToken);
// Distribute unlocked credit to depositors.
_distributeUnlockedCreditDeposited(recipient);
// Update the recipient's account and decrease the amount of debt incurred.
_poke(recipient);
// Check that the debt is greater than zero.
//
// It is possible that the amount of debt which is repayable is equal to or less than zero after realizing the
// credit that was earned since the last update. We do not want to perform a noop so we need to check that the
// amount of debt to repay is greater than zero.
int256 debt;
_checkState((debt = _accounts[recipient].debt) > 0);
// Determine the maximum amount of underlying tokens that can be repaid.
//
// It is implied that this value is greater than zero because `debt` is greater than zero so a noop is not possible
// beyond this point. Casting the debt to an unsigned integer is also safe because `debt` is greater than zero.
uint256 maximumAmount = _normalizeDebtTokensToUnderlying(underlyingToken, uint256(debt));
// Limit the number of underlying tokens to repay up to the maximum allowed.
uint256 actualAmount = amount > maximumAmount ? maximumAmount : amount;
Limiters.LinearGrowthLimiter storage limiter = _repayLimiters[underlyingToken];
// Check to make sure that the underlying token repay limit has not been breached.
uint256 currentRepayLimit = limiter.get();
if (actualAmount > currentRepayLimit) {
revert RepayLimitExceeded(underlyingToken, actualAmount, currentRepayLimit);
}
uint256 credit = _normalizeUnderlyingTokensToDebt(underlyingToken, actualAmount);
// Update the recipient's debt.
_updateDebt(recipient, -SafeCast.toInt256(credit));
// Decrease the amount of the underlying token which is globally available to be repaid.
limiter.decrease(actualAmount);
// Transfer the repaid tokens to the transmuter.
TokenUtils.safeTransferFrom(underlyingToken, msg.sender, transmuter, actualAmount);
// Inform the transmuter that it has received tokens.
IERC20TokenReceiver(transmuter).onERC20Received(underlyingToken, actualAmount);
emit Repay(msg.sender, underlyingToken, actualAmount, recipient);
return actualAmount;
}
/// @inheritdoc IAlchemistV2Actions
function liquidate(
address yieldToken,
uint256 shares,
uint256 minimumAmountOut
) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(shares > 0);
YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken];
address underlyingToken = yieldTokenParams.underlyingToken;
_checkSupportedYieldToken(yieldToken);
_checkYieldTokenEnabled(yieldToken);
_checkUnderlyingTokenEnabled(underlyingToken);
_checkLoss(yieldToken);
// Calculate the unrealized debt.
//
// It is possible that the number of debt which is repayable is equal to or less than zero after realizing the
// credit that was earned since the last update. We do not want to perform a noop so we need to check that the
// amount of debt to repay is greater than zero.
int256 unrealizedDebt;
_checkState((unrealizedDebt = _calculateUnrealizedDebt(msg.sender)) > 0);
// Determine the maximum amount of shares that can be liquidated from the unrealized debt.
//
// It is implied that this value is greater than zero because `debt` is greater than zero. Casting the debt to an
// unsigned integer is also safe for this reason.
uint256 maximumShares = _convertUnderlyingTokensToShares(
yieldToken,
_normalizeDebtTokensToUnderlying(underlyingToken, uint256(unrealizedDebt))
);
// Limit the number of shares to liquidate up to the maximum allowed.
uint256 actualShares = shares > maximumShares ? maximumShares : shares;
// Unwrap the yield tokens that the shares are worth.
uint256 amountYieldTokens = _convertSharesToYieldTokens(yieldToken, actualShares);
uint256 amountUnderlyingTokens = _unwrap(yieldToken, amountYieldTokens, address(this), minimumAmountOut);
// Again, perform another noop check. It is possible that the amount of underlying tokens that were received by
// unwrapping the yield tokens was zero because the amount of yield tokens to unwrap was too small.
_checkState(amountUnderlyingTokens > 0);
Limiters.LinearGrowthLimiter storage limiter = _liquidationLimiters[underlyingToken];
// Check to make sure that the underlying token liquidation limit has not been breached.
uint256 liquidationLimit = limiter.get();
if (amountUnderlyingTokens > liquidationLimit) {
revert LiquidationLimitExceeded(underlyingToken, amountUnderlyingTokens, liquidationLimit);
}
// Buffers any harvestable yield tokens. This will properly synchronize the balance which is held by users
// and the balance which is held by the system. This is required for `_sync` to function correctly.
_preemptivelyHarvest(yieldToken);
// Distribute unlocked credit to depositors.
_distributeUnlockedCreditDeposited(msg.sender);
uint256 credit = _normalizeUnderlyingTokensToDebt(underlyingToken, amountUnderlyingTokens);
// Update the message sender's account, proactively burn shares, decrease the amount of debt incurred, and then
// decrease the value of the token that the system is expected to hold.
_poke(msg.sender, yieldToken);
_burnShares(msg.sender, yieldToken, actualShares);
_updateDebt(msg.sender, -SafeCast.toInt256(credit));
_sync(yieldToken, amountYieldTokens, _usub);
// Decrease the amount of the underlying token which is globally available to be liquidated.
limiter.decrease(amountUnderlyingTokens);
// Transfer the liquidated tokens to the transmuter.
TokenUtils.safeTransfer(underlyingToken, transmuter, amountUnderlyingTokens);
// Inform the transmuter that it has received tokens.
IERC20TokenReceiver(transmuter).onERC20Received(underlyingToken, amountUnderlyingTokens);
emit Liquidate(msg.sender, yieldToken, underlyingToken, actualShares);
return actualShares;
}
/// @inheritdoc IAlchemistV2Actions
function donate(address yieldToken, uint256 amount) external override lock {
_onlyWhitelisted();
_checkArgument(amount != 0);
// Distribute any unlocked credit so that the accrued weight is up to date.
_distributeUnlockedCredit(yieldToken);
// Update the message sender's account. This will assure that any credit that was earned is not overridden.
_poke(msg.sender);
uint256 shares = _yieldTokens[yieldToken].totalShares - _accounts[msg.sender].balances[yieldToken];
_yieldTokens[yieldToken].accruedWeight += amount * FIXED_POINT_SCALAR / shares;
_accounts[msg.sender].lastAccruedWeights[yieldToken] = _yieldTokens[yieldToken].accruedWeight;
TokenUtils.safeBurnFrom(debtToken, msg.sender, amount);
emit Donate(msg.sender, yieldToken, amount);
}
/// @inheritdoc IAlchemistV2Actions
function harvest(address yieldToken, uint256 minimumAmountOut) external override lock {
_onlyKeeper();
_checkSupportedYieldToken(yieldToken);
YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken];
// Buffer any harvestable yield tokens. This will properly synchronize the balance which is held by users
// and the balance which is held by the system to be harvested during this call.
_preemptivelyHarvest(yieldToken);
// Load and proactively clear the amount of harvestable tokens so that future calls do not rely on stale data.
// Because we cannot call an external unwrap until the amount of harvestable tokens has been calculated,
// clearing this data immediately prevents any potential reentrancy attacks which would use stale harvest
// buffer values.
uint256 harvestableAmount = yieldTokenParams.harvestableBalance;
yieldTokenParams.harvestableBalance = 0;
// Check that the harvest will not be a no-op.
_checkState(harvestableAmount != 0);
address underlyingToken = yieldTokenParams.underlyingToken;
uint256 amountUnderlyingTokens = _unwrap(yieldToken, harvestableAmount, address(this), minimumAmountOut);
// Calculate how much of the unwrapped underlying tokens will be allocated for fees and distributed to users.
uint256 feeAmount = amountUnderlyingTokens * protocolFee / BPS;
uint256 distributeAmount = amountUnderlyingTokens - feeAmount;
uint256 credit = _normalizeUnderlyingTokensToDebt(underlyingToken, distributeAmount);
// Distribute credit to all of the users who hold shares of the yield token.
_distributeCredit(yieldToken, credit);
// Transfer the tokens to the fee receiver and transmuter.
TokenUtils.safeTransfer(underlyingToken, protocolFeeReceiver, feeAmount);
TokenUtils.safeTransfer(underlyingToken, transmuter, distributeAmount);
// Inform the transmuter that it has received tokens.
IERC20TokenReceiver(transmuter).onERC20Received(underlyingToken, distributeAmount);
emit Harvest(yieldToken, minimumAmountOut, amountUnderlyingTokens);
}
/// @dev Checks that the `msg.sender` is the administrator.
///
/// @dev `msg.sender` must be the administrator or this call will revert with an {Unauthorized} error.
function _onlyAdmin() internal view {
if (msg.sender != admin) {
revert Unauthorized();
}
}
/// @dev Checks that the `msg.sender` is the administrator or a sentinel.
///
/// @dev `msg.sender` must be either the administrator or a sentinel or this call will revert with an
/// {Unauthorized} error.
function _onlySentinelOrAdmin() internal view {
// Check if the message sender is the administrator.
if (msg.sender == admin) {
return;
}
// Check if the message sender is a sentinel. After this check we can revert since we know that it is neither
// the administrator or a sentinel.
if (!sentinels[msg.sender]) {
revert Unauthorized();
}
}
/// @dev Checks that the `msg.sender` is a keeper.
///
/// @dev `msg.sender` must be a keeper or this call will revert with an {Unauthorized} error.
function _onlyKeeper() internal view {
if (!keepers[msg.sender]) {
revert Unauthorized();
}
}
/// @dev Preemptively harvests all of the yield tokens that have been deposited into an account.
///
/// @param owner The address which owns the account.
function _preemptivelyHarvestDeposited(address owner) internal {
Sets.AddressSet storage depositedTokens = _accounts[owner].depositedTokens;
for (uint256 i = 0; i < depositedTokens.values.length; i++) {
_preemptivelyHarvest(depositedTokens.values[i]);
}
}
/// @dev Preemptively harvests `yieldToken`.
///
/// @dev This will earmark yield tokens to be harvested at a future time when the current value of the token is
/// greater than the expected value. The purpose of this function is to synchronize the balance of the yield
/// token which is held by users versus tokens which will be seized by the protocol.
///
/// @param yieldToken The address of the yield token to preemptively harvest.
function _preemptivelyHarvest(address yieldToken) internal {
uint256 activeBalance = _yieldTokens[yieldToken].activeBalance;
if (activeBalance == 0) {
return;
}
uint256 currentValue = _convertYieldTokensToUnderlying(yieldToken, activeBalance);
uint256 expectedValue = _yieldTokens[yieldToken].expectedValue;
if (currentValue <= expectedValue) {
return;
}
uint256 harvestable = _convertUnderlyingTokensToYield(yieldToken, currentValue - expectedValue);
if (harvestable == 0) {
return;
}
_yieldTokens[yieldToken].activeBalance -= harvestable;
_yieldTokens[yieldToken].harvestableBalance += harvestable;
}
/// @dev Checks if a yield token is enabled.
///
/// @param yieldToken The address of the yield token.
function _checkYieldTokenEnabled(address yieldToken) internal view {
if (!_yieldTokens[yieldToken].enabled) {
revert TokenDisabled(yieldToken);
}
}
/// @dev Checks if an underlying token is enabled.
///
/// @param underlyingToken The address of the underlying token.
function _checkUnderlyingTokenEnabled(address underlyingToken) internal view {
if (!_underlyingTokens[underlyingToken].enabled) {
revert TokenDisabled(underlyingToken);
}
}
/// @dev Checks if an address is a supported yield token.
///
/// If the address is not a supported yield token, this function will revert using a {UnsupportedToken} error.
///
/// @param yieldToken The address to check.
function _checkSupportedYieldToken(address yieldToken) internal view {
if (!_supportedYieldTokens.contains(yieldToken)) {
revert UnsupportedToken(yieldToken);
}
}
/// @dev Checks if an address is a supported underlying token.
///
/// If the address is not a supported yield token, this function will revert using a {UnsupportedToken} error.
///
/// @param underlyingToken The address to check.
function _checkSupportedUnderlyingToken(address underlyingToken) internal view {
if (!_supportedUnderlyingTokens.contains(underlyingToken)) {
revert UnsupportedToken(underlyingToken);
}
}
/// @dev Checks if `amount` of debt tokens can be minted.
///
/// @dev `amount` must be less than the current minting limit or this call will revert with a
/// {MintingLimitExceeded} error.
///
/// @param amount The amount to check.
function _checkMintingLimit(uint256 amount) internal view {
uint256 limit = _mintingLimiter.get();
if (amount > limit) {
revert MintingLimitExceeded(amount, limit);
}
}
/// @dev Checks if the current loss of `yieldToken` has exceeded its maximum acceptable loss.
///
/// @dev The loss that `yieldToken` has incurred must be less than its maximum accepted value or this call will
/// revert with a {LossExceeded} error.
///
/// @param yieldToken The address of the yield token.
function _checkLoss(address yieldToken) internal view {
uint256 loss = _loss(yieldToken);
uint256 maximumLoss = _yieldTokens[yieldToken].maximumLoss;
if (loss > maximumLoss) {
revert LossExceeded(yieldToken, loss, maximumLoss);
}
}
/// @dev Deposits `amount` yield tokens into the account of `recipient`.
///
/// @dev Emits a {Deposit} event.
///
/// @param yieldToken The address of the yield token to deposit.
/// @param amount The amount of yield tokens to deposit.
/// @param recipient The recipient of the yield tokens.
///
/// @return The number of shares minted to `recipient`.
function _deposit(
address yieldToken,
uint256 amount,
address recipient
) internal returns (uint256) {
_checkArgument(amount > 0);
YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken];
address underlyingToken = yieldTokenParams.underlyingToken;
// Check that the yield token and it's underlying token are enabled. Disabling the yield token and or the
// underlying token prevents the system from holding more of the disabled yield token or underlying token.
_checkYieldTokenEnabled(yieldToken);
_checkUnderlyingTokenEnabled(underlyingToken);
// Check to assure that the token has not experienced a sudden unexpected loss. This prevents users from being
// able to deposit funds and then have them siphoned if the price recovers.
_checkLoss(yieldToken);
// Buffers any harvestable yield tokens. This will properly synchronize the balance which is held by users
// and the balance which is held by the system to eventually be harvested.
_preemptivelyHarvest(yieldToken);
// Distribute unlocked credit to depositors.
_distributeUnlockedCreditDeposited(recipient);
// Update the recipient's account, proactively issue shares for the deposited tokens to the recipient, and then
// increase the value of the token that the system is expected to hold.
_poke(recipient, yieldToken);
uint256 shares = _issueSharesForAmount(recipient, yieldToken, amount);
_sync(yieldToken, amount, _uadd);
// Check that the maximum expected value has not been breached.
uint256 maximumExpectedValue = yieldTokenParams.maximumExpectedValue;
if (yieldTokenParams.expectedValue > maximumExpectedValue) {
revert ExpectedValueExceeded(yieldToken, amount, maximumExpectedValue);
}
emit Deposit(msg.sender, yieldToken, amount, recipient);
return shares;
}
/// @dev Withdraw `yieldToken` from the account owned by `owner` by burning shares and receiving yield tokens of
/// equivalent value.
///
/// @dev Emits a {Withdraw} event.
///
/// @param yieldToken The address of the yield token to withdraw.
/// @param owner The address of the account owner to withdraw from.
/// @param shares The number of shares to burn.
/// @param recipient The recipient of the withdrawn shares. This parameter is only used for logging.
///
/// @return The amount of yield tokens that the burned shares were exchanged for.
function _withdraw(
address yieldToken,
address owner,
uint256 shares,
address recipient
) internal returns (uint256) {
// Buffers any harvestable yield tokens that the owner of the account has deposited. This will properly
// synchronize the balance of all the tokens held by the owner so that the validation check properly
// computes the total value of the tokens held by the owner.
_preemptivelyHarvestDeposited(owner);
// Distribute unlocked credit for all of the tokens that the user has deposited into the system. This updates
// the accrued weights so that the debt is properly calculated before the account is validated.
_distributeUnlockedCreditDeposited(owner);
uint256 amountYieldTokens = _convertSharesToYieldTokens(yieldToken, shares);
// Update the owner's account, burn shares from the owner's account, and then decrease the value of the token
// that the system is expected to hold.
_poke(owner);
_burnShares(owner, yieldToken, shares);
_sync(yieldToken, amountYieldTokens, _usub);
// Valid the owner's account to assure that the collateralization invariant is still held.
_validate(owner);
emit Withdraw(owner, yieldToken, shares, recipient);
return amountYieldTokens;
}
/// @dev Mints debt tokens to `recipient` using the account owned by `owner`.
///
/// @dev Emits a {Mint} event.
///
/// @param owner The owner of the account to mint from.
/// @param amount The amount to mint.
/// @param recipient The recipient of the minted debt tokens.
function _mint(address owner, uint256 amount, address recipient) internal {
// Check that the system will allow for the specified amount to be minted.
_checkMintingLimit(amount);
// Preemptively harvest all tokens that the user has deposited into the system. This allows the debt to be
// properly calculated before the account is validated.
_preemptivelyHarvestDeposited(owner);
// Distribute unlocked credit for all of the tokens that the user has deposited into the system. This updates
// the accrued weights so that the debt is properly calculated before the account is validated.
_distributeUnlockedCreditDeposited(owner);
// Update the owner's account, increase their debt by the amount of tokens to mint, and then finally validate
// their account to assure that the collateralization invariant is still held.
_poke(owner);
_updateDebt(owner, SafeCast.toInt256(amount));
_validate(owner);
// Decrease the global amount of mintable debt tokens.
_mintingLimiter.decrease(amount);
// Mint the debt tokens to the recipient.
TokenUtils.safeMint(debtToken, recipient, amount);
emit Mint(owner, amount, recipient);
}
/// @dev Synchronizes the active balance and expected value of `yieldToken`.
///
/// @param yieldToken The address of the yield token.
/// @param amount The amount to add or subtract from the debt.
/// @param operation The mathematical operation to perform for the update. Either one of {_uadd} or {_usub}.
function _sync(
address yieldToken,
uint256 amount,
function(uint256, uint256) internal pure returns (uint256) operation
) internal {
YieldTokenParams memory yieldTokenParams = _yieldTokens[yieldToken];
uint256 amountUnderlyingTokens = _convertYieldTokensToUnderlying(yieldToken, amount);
uint256 updatedActiveBalance = operation(yieldTokenParams.activeBalance, amount);
uint256 updatedExpectedValue = operation(yieldTokenParams.expectedValue, amountUnderlyingTokens);
_yieldTokens[yieldToken].activeBalance = updatedActiveBalance;
_yieldTokens[yieldToken].expectedValue = updatedExpectedValue;
}
/// @dev Gets the amount of loss that `yieldToken` has incurred measured in basis points. When the expected
/// underlying value is less than the actual value, this will return zero.
///
/// @param yieldToken The address of the yield token.
///
/// @return The loss in basis points.
function _loss(address yieldToken) internal view returns (uint256) {
YieldTokenParams memory yieldTokenParams = _yieldTokens[yieldToken];
uint256 amountUnderlyingTokens = _convertYieldTokensToUnderlying(yieldToken, yieldTokenParams.activeBalance);
uint256 expectedUnderlyingValue = yieldTokenParams.expectedValue;
return expectedUnderlyingValue > amountUnderlyingTokens
? ((expectedUnderlyingValue - amountUnderlyingTokens) * BPS) / expectedUnderlyingValue
: 0;
}
/// @dev Distributes `amount` credit to all depositors of `yieldToken`.
///
/// @param yieldToken The address of the yield token to distribute credit for.
/// @param amount The amount of credit to distribute in debt tokens.
function _distributeCredit(address yieldToken, uint256 amount) internal {
YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken];
uint256 pendingCredit = yieldTokenParams.pendingCredit;
uint256 distributedCredit = yieldTokenParams.distributedCredit;
uint256 unlockedCredit = _calculateUnlockedCredit(yieldToken);
uint256 lockedCredit = pendingCredit - (distributedCredit + unlockedCredit);
// Distribute any unlocked credit before overriding it.
if (unlockedCredit > 0) {
yieldTokenParams.accruedWeight += unlockedCredit * FIXED_POINT_SCALAR / yieldTokenParams.totalShares;
}
yieldTokenParams.pendingCredit = amount + lockedCredit;
yieldTokenParams.distributedCredit = 0;
yieldTokenParams.lastDistributionBlock = block.number;
}
/// @dev Distributes unlocked credit for all of the yield tokens that have been deposited into the account owned
/// by `owner`.
///
/// @param owner The address of the account owner.
function _distributeUnlockedCreditDeposited(address owner) internal {
Sets.AddressSet storage depositedTokens = _accounts[owner].depositedTokens;
for (uint256 i = 0; i < depositedTokens.values.length; i++) {
_distributeUnlockedCredit(depositedTokens.values[i]);
}
}
/// @dev Distributes unlocked credit of `yieldToken` to all depositors.
///
/// @param yieldToken The address of the yield token to distribute unlocked credit for.
function _distributeUnlockedCredit(address yieldToken) internal {
YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken];
uint256 unlockedCredit = _calculateUnlockedCredit(yieldToken);
if (unlockedCredit == 0) {
return;
}
yieldTokenParams.accruedWeight += unlockedCredit * FIXED_POINT_SCALAR / yieldTokenParams.totalShares;
yieldTokenParams.distributedCredit += unlockedCredit;
}
/// @dev Wraps `amount` of an underlying token into its `yieldToken`.
///
/// @param yieldToken The address of the yield token to wrap the underlying tokens into.
/// @param amount The amount of the underlying token to wrap.
/// @param minimumAmountOut The minimum amount of yield tokens that are expected to be received from the operation.
///
/// @return The amount of yield tokens that resulted from the operation.
function _wrap(
address yieldToken,
uint256 amount,
uint256 minimumAmountOut
) internal returns (uint256) {
YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken];
ITokenAdapter adapter = ITokenAdapter(yieldTokenParams.adapter);
address underlyingToken = yieldTokenParams.underlyingToken;
TokenUtils.safeTransferFrom(underlyingToken, msg.sender, address(this), amount);
uint256 wrappedShares = adapter.wrap(amount, address(this));
if (wrappedShares < minimumAmountOut) {
revert SlippageExceeded(wrappedShares, minimumAmountOut);
}
return wrappedShares;
}
/// @dev Unwraps `amount` of `yieldToken` into its underlying token.
///
/// @param yieldToken The address of the yield token to unwrap.
/// @param amount The amount of the underlying token to wrap.
/// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be received from the
/// operation.
///
/// @return The amount of underlying tokens that resulted from the operation.
function _unwrap(
address yieldToken,
uint256 amount,
address recipient,
uint256 minimumAmountOut
) internal returns (uint256) {
ITokenAdapter adapter = ITokenAdapter(_yieldTokens[yieldToken].adapter);
uint256 amountUnwrapped = adapter.unwrap(amount, recipient);
if (amountUnwrapped < minimumAmountOut) {
revert SlippageExceeded(amountUnwrapped, minimumAmountOut);
}
return amountUnwrapped;
}
/// @dev Synchronizes the state for all of the tokens deposited in the account owned by `owner`.
///
/// @param owner The address of the account owner.
function _poke(address owner) internal {
Sets.AddressSet storage depositedTokens = _accounts[owner].depositedTokens;
for (uint256 i = 0; i < depositedTokens.values.length; i++) {
_poke(owner, depositedTokens.values[i]);
}
}
/// @dev Synchronizes the state of `yieldToken` for the account owned by `owner`.
///
/// @param owner The address of the account owner.
/// @param yieldToken The address of the yield token to synchronize the state for.
function _poke(address owner, address yieldToken) internal {
Account storage account = _accounts[owner];
uint256 currentAccruedWeight = _yieldTokens[yieldToken].accruedWeight;
uint256 lastAccruedWeight = account.lastAccruedWeights[yieldToken];
if (currentAccruedWeight == lastAccruedWeight) {
return;
}
uint256 balance = account.balances[yieldToken];
uint256 unrealizedCredit = (currentAccruedWeight - lastAccruedWeight) * balance / FIXED_POINT_SCALAR;
account.debt -= SafeCast.toInt256(unrealizedCredit);
account.lastAccruedWeights[yieldToken] = currentAccruedWeight;
}
/// @dev Increases the debt by `amount` for the account owned by `owner`.
///
/// @param owner The address of the account owner.
/// @param amount The amount to increase the debt by.
function _updateDebt(address owner, int256 amount) internal {
Account storage account = _accounts[owner];
account.debt += amount;
}
/// @dev Set the mint allowance for `spender` to `amount` for the account owned by `owner`.
///
/// @param owner The address of the account owner.
/// @param spender The address of the spender.
/// @param amount The amount of debt tokens to set the mint allowance to.
function _approveMint(address owner, address spender, uint256 amount) internal {
Account storage account = _accounts[owner];
account.mintAllowances[spender] = amount;
emit ApproveMint(owner, spender, amount);
}
/// @dev Decrease the mint allowance for `spender` by `amount` for the account owned by `owner`.
///
/// @param owner The address of the account owner.
/// @param spender The address of the spender.
/// @param amount The amount of debt tokens to decrease the mint allowance by.
function _decreaseMintAllowance(address owner, address spender, uint256 amount) internal {
Account storage account = _accounts[owner];
account.mintAllowances[spender] -= amount;
}
/// @dev Set the withdraw allowance of `yieldToken` for `spender` to `shares` for the account owned by `owner`.
///
/// @param owner The address of the account owner.
/// @param spender The address of the spender.
/// @param yieldToken The address of the yield token to set the withdraw allowance for.
/// @param shares The amount of shares to set the withdraw allowance to.
function _approveWithdraw(address owner, address spender, address yieldToken, uint256 shares) internal {
Account storage account = _accounts[owner];
account.withdrawAllowances[spender][yieldToken] = shares;
emit ApproveWithdraw(owner, spender, yieldToken, shares);
}
/// @dev Decrease the withdraw allowance of `yieldToken` for `spender` by `amount` for the account owned by `owner`.
///
/// @param owner The address of the account owner.
/// @param spender The address of the spender.
/// @param yieldToken The address of the yield token to decrease the withdraw allowance for.
/// @param amount The amount of shares to decrease the withdraw allowance by.
function _decreaseWithdrawAllowance(address owner, address spender, address yieldToken, uint256 amount) internal {
Account storage account = _accounts[owner];
account.withdrawAllowances[spender][yieldToken] -= amount;
}
/// @dev Checks that the account owned by `owner` is properly collateralized.
///
/// @dev If the account is undercollateralized then this will revert with an {Undercollateralized} error.
///
/// @param owner The address of the account owner.
function _validate(address owner) internal view {
int256 debt = _accounts[owner].debt;
if (debt <= 0) {
return;
}
uint256 collateralization = _totalValue(owner) * FIXED_POINT_SCALAR / uint256(debt);
if (collateralization < minimumCollateralization) {
revert Undercollateralized();
}
}
/// @dev Gets the total value of the deposit collateral measured in debt tokens of the account owned by `owner`.
///
/// @param owner The address of the account owner.
///
/// @return The total value.
function _totalValue(address owner) internal view returns (uint256) {
uint256 totalValue = 0;
Sets.AddressSet storage depositedTokens = _accounts[owner].depositedTokens;
for (uint256 i = 0; i < depositedTokens.values.length; i++) {
address yieldToken = depositedTokens.values[i];
address underlyingToken = _yieldTokens[yieldToken].underlyingToken;
uint256 shares = _accounts[owner].balances[yieldToken];
uint256 amountUnderlyingTokens = _convertSharesToUnderlyingTokens(yieldToken, shares);
totalValue += _normalizeUnderlyingTokensToDebt(underlyingToken, amountUnderlyingTokens);
}
return totalValue;
}
/// @dev Issues shares of `yieldToken` for `amount` of its underlying token to `recipient`.
///
/// IMPORTANT: `amount` must never be 0.
///
/// @param recipient The address of the recipient.
/// @param yieldToken The address of the yield token.
/// @param amount The amount of the underlying token.
///
/// @return The amount of shares issued to `recipient`.
function _issueSharesForAmount(
address recipient,
address yieldToken,
uint256 amount
) internal returns (uint256) {
uint256 shares = _convertYieldTokensToShares(yieldToken, amount);
if (_accounts[recipient].balances[yieldToken] == 0) {
_accounts[recipient].depositedTokens.add(yieldToken);
}
_accounts[recipient].balances[yieldToken] += shares;
_yieldTokens[yieldToken].totalShares += shares;
return shares;
}
/// @dev Burns `share` shares of `yieldToken` from the account owned by `owner`.
///
/// @param owner The address of the owner.
/// @param yieldToken The address of the yield token.
/// @param shares The amount of shares to burn.
function _burnShares(address owner, address yieldToken, uint256 shares) internal {
Account storage account = _accounts[owner];
account.balances[yieldToken] -= shares;
_yieldTokens[yieldToken].totalShares -= shares;
if (account.balances[yieldToken] == 0) {
account.depositedTokens.remove(yieldToken);
}
}
/// @dev Gets the amount of debt that the account owned by `owner` will have after an update occurs.
///
/// @param owner The address of the account owner.
///
/// @return The amount of debt that the account owned by `owner` will have after an update.
function _calculateUnrealizedDebt(address owner) internal view returns (int256) {
int256 debt = _accounts[owner].debt;
Sets.AddressSet storage depositedTokens = _accounts[owner].depositedTokens;
for (uint256 i = 0; i < depositedTokens.values.length; i++) {
address yieldToken = depositedTokens.values[i];
uint256 currentAccruedWeight = _yieldTokens[yieldToken].accruedWeight;
uint256 lastAccruedWeight = _accounts[owner].lastAccruedWeights[yieldToken];
uint256 unlockedCredit = _calculateUnlockedCredit(yieldToken);
currentAccruedWeight += unlockedCredit > 0
? unlockedCredit * FIXED_POINT_SCALAR / _yieldTokens[yieldToken].totalShares
: 0;
if (currentAccruedWeight == lastAccruedWeight) {
continue;
}
uint256 balance = _accounts[owner].balances[yieldToken];
uint256 unrealizedCredit = ((currentAccruedWeight - lastAccruedWeight) * balance) / FIXED_POINT_SCALAR;
debt -= SafeCast.toInt256(unrealizedCredit);
}
return debt;
}
/// @dev Gets the virtual active balance of `yieldToken`.
///
/// @dev The virtual active balance is the active balance minus any harvestable tokens which have yet to be realized.
///
/// @param yieldToken The address of the yield token to get the virtual active balance of.
///
/// @return The virtual active balance.
function _calculateUnrealizedActiveBalance(address yieldToken) internal view returns (uint256) {
YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken];
uint256 activeBalance = yieldTokenParams.activeBalance;
if (activeBalance == 0) {
return activeBalance;
}
uint256 currentValue = _convertYieldTokensToUnderlying(yieldToken, activeBalance);
uint256 expectedValue = yieldTokenParams.expectedValue;
if (currentValue <= expectedValue) {
return activeBalance;
}
uint256 harvestable = _convertUnderlyingTokensToYield(yieldToken, currentValue - expectedValue);
if (harvestable == 0) {
return activeBalance;
}
return activeBalance - harvestable;
}
/// @dev Calculates the amount of unlocked credit for `yieldToken` that is available for distribution.
///
/// @param yieldToken The address of the yield token.
///
/// @return The amount of unlocked credit available.
function _calculateUnlockedCredit(address yieldToken) internal view returns (uint256) {
YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken];
uint256 pendingCredit = yieldTokenParams.pendingCredit;
if (pendingCredit == 0) {
return 0;
}
uint256 creditUnlockRate = yieldTokenParams.creditUnlockRate;
uint256 distributedCredit = yieldTokenParams.distributedCredit;
uint256 lastDistributionBlock = yieldTokenParams.lastDistributionBlock;
uint256 percentUnlocked = (block.number - lastDistributionBlock) * creditUnlockRate;
return percentUnlocked < FIXED_POINT_SCALAR
? (pendingCredit * percentUnlocked / FIXED_POINT_SCALAR) - distributedCredit
: pendingCredit - distributedCredit;
}
/// @dev Gets the amount of shares that `amount` of `yieldToken` is exchangeable for.
///
/// @param yieldToken The address of the yield token.
/// @param amount The amount of yield tokens.
///
/// @return The number of shares.
function _convertYieldTokensToShares(address yieldToken, uint256 amount) internal view returns (uint256) {
if (_yieldTokens[yieldToken].totalShares == 0) {
return amount;
}
return amount * _yieldTokens[yieldToken].totalShares / _calculateUnrealizedActiveBalance(yieldToken);
}
/// @dev Gets the amount of yield tokens that `shares` shares of `yieldToken` is exchangeable for.
///
/// @param yieldToken The address of the yield token.
/// @param shares The amount of shares.
///
/// @return The amount of yield tokens.
function _convertSharesToYieldTokens(address yieldToken, uint256 shares) internal view returns (uint256) {
uint256 totalShares = _yieldTokens[yieldToken].totalShares;
if (totalShares == 0) {
return shares;
}
return (shares * _calculateUnrealizedActiveBalance(yieldToken)) / totalShares;
}
/// @dev Gets the amount of underlying tokens that `shares` shares of `yieldToken` is exchangeable for.
///
/// @param yieldToken The address of the yield token.
/// @param shares The amount of shares.
///
/// @return The amount of underlying tokens.
function _convertSharesToUnderlyingTokens(address yieldToken, uint256 shares) internal view returns (uint256) {
uint256 amountYieldTokens = _convertSharesToYieldTokens(yieldToken, shares);
return _convertYieldTokensToUnderlying(yieldToken, amountYieldTokens);
}
/// @dev Gets the amount of an underlying token that `amount` of `yieldToken` is exchangeable for.
///
/// @param yieldToken The address of the yield token.
/// @param amount The amount of yield tokens.
///
/// @return The amount of underlying tokens.
function _convertYieldTokensToUnderlying(address yieldToken, uint256 amount) internal view returns (uint256) {
YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken];
ITokenAdapter adapter = ITokenAdapter(yieldTokenParams.adapter);
return amount * adapter.price() / 10**yieldTokenParams.decimals;
}
/// @dev Gets the amount of `yieldToken` that `amount` of its underlying token is exchangeable for.
///
/// @param yieldToken The address of the yield token.
/// @param amount The amount of underlying tokens.
///
/// @return The amount of yield tokens.
function _convertUnderlyingTokensToYield(address yieldToken, uint256 amount) internal view returns (uint256) {
YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken];
ITokenAdapter adapter = ITokenAdapter(yieldTokenParams.adapter);
return amount * 10**yieldTokenParams.decimals / adapter.price();
}
/// @dev Gets the amount of shares of `yieldToken` that `amount` of its underlying token is exchangeable for.
///
/// @param yieldToken The address of the yield token.
/// @param amount The amount of underlying tokens.
///
/// @return The amount of shares.
function _convertUnderlyingTokensToShares(address yieldToken, uint256 amount) internal view returns (uint256) {
uint256 amountYieldTokens = _convertUnderlyingTokensToYield(yieldToken, amount);
return _convertYieldTokensToShares(yieldToken, amountYieldTokens);
}
/// @dev Normalize `amount` of `underlyingToken` to a value which is comparable to units of the debt token.
///
/// @param underlyingToken The address of the underlying token.
/// @param amount The amount of the debt token.
///
/// @return The normalized amount.
function _normalizeUnderlyingTokensToDebt(address underlyingToken, uint256 amount) internal view returns (uint256) {
return amount * _underlyingTokens[underlyingToken].conversionFactor;
}
/// @dev Normalize `amount` of the debt token to a value which is comparable to units of `underlyingToken`.
///
/// @dev This operation will result in truncation of some of the least significant digits of `amount`. This
/// truncation amount will be the least significant N digits where N is the difference in decimals between
/// the debt token and the underlying token.
///
/// @param underlyingToken The address of the underlying token.
/// @param amount The amount of the debt token.
///
/// @return The normalized amount.
function _normalizeDebtTokensToUnderlying(address underlyingToken, uint256 amount) internal view returns (uint256) {
return amount / _underlyingTokens[underlyingToken].conversionFactor;
}
/// @dev Checks the whitelist for msg.sender.
///
/// Reverts if msg.sender is not in the whitelist.
function _onlyWhitelisted() internal view {
// Check if the message sender is an EOA. In the future, this potentially may break. It is important that functions
// which rely on the whitelist not be explicitly vulnerable in the situation where this no longer holds true.
if (tx.origin == msg.sender) {
return;
}
// Only check the whitelist for calls from contracts.
if (!IWhitelist(whitelist).isWhitelisted(msg.sender)) {
revert Unauthorized();
}
}
/// @dev Checks an expression and reverts with an {IllegalArgument} error if the expression is {false}.
///
/// @param expression The expression to check.
function _checkArgument(bool expression) internal pure {
if (!expression) {
revert IllegalArgument();
}
}
/// @dev Checks an expression and reverts with an {IllegalState} error if the expression is {false}.
///
/// @param expression The expression to check.
function _checkState(bool expression) internal pure {
if (!expression) {
revert IllegalState();
}
}
/// @dev Adds two unsigned 256 bit integers together and returns the result.
///
/// @dev This operation is checked and will fail if the result overflows.
///
/// @param x The first operand.
/// @param y The second operand.
///
/// @return z The result.
function _uadd(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x + y; }
/// @dev Subtracts two unsigned 256 bit integers together and returns the result.
///
/// @dev This operation is checked and will fail if the result overflows.
///
/// @param x The first operand.
/// @param y The second operand.
///
/// @return z the result.
function _usub(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x - y; }
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
pragma solidity ^0.8.11;
/// @notice An error used to indicate that an action could not be completed because either the `msg.sender` or
/// `msg.origin` is not authorized.
error Unauthorized();
/// @notice An error used to indicate that an action could not be completed because the contract either already existed
/// or entered an illegal condition which is not recoverable from.
error IllegalState();
/// @notice An error used to indicate that an action could not be completed because of an illegal argument was passed
/// to the function.
error IllegalArgument();
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.11;
import "../interfaces/IMulticall.sol";
/// @title Multicall
/// @author Uniswap Labs
///
/// @notice Enables calling multiple methods in a single call to the contract
abstract contract Multicall is IMulticall {
/// @inheritdoc IMulticall
function multicall(bytes[] calldata data) external payable override returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
if (!success) {
revert MulticallFailed(data[i], result);
}
results[i] = result;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.11;
/// @title Mutex
/// @author Alchemix Finance
///
/// @notice Provides a mutual exclusion lock for implementing contracts.
abstract contract Mutex {
/// @notice An error which is thrown when a lock is attempted to be claimed before it has been freed.
error LockAlreadyClaimed();
/// @notice The lock state. Non-zero values indicate the lock has been claimed.
uint256 private _lockState;
/// @dev A modifier which acquires the mutex.
modifier lock() {
_claimLock();
_;
_freeLock();
}
/// @dev Gets if the mutex is locked.
///
/// @return if the mutex is locked.
function _isLocked() internal returns (bool) {
return _lockState == 1;
}
/// @dev Claims the lock. If the lock is already claimed, then this will revert.
function _claimLock() internal {
// Check that the lock has not been claimed yet.
if (_lockState != 0) {
revert LockAlreadyClaimed();
}
// Claim the lock.
_lockState = 1;
}
/// @dev Frees the lock.
function _freeLock() internal {
_lockState = 0;
}
}
pragma solidity >=0.5.0;
import "./alchemist/IAlchemistV2Actions.sol";
import "./alchemist/IAlchemistV2AdminActions.sol";
import "./alchemist/IAlchemistV2Errors.sol";
import "./alchemist/IAlchemistV2Immutables.sol";
import "./alchemist/IAlchemistV2Events.sol";
import "./alchemist/IAlchemistV2State.sol";
/// @title IAlchemistV2
/// @author Alchemix Finance
interface IAlchemistV2 is
IAlchemistV2Actions,
IAlchemistV2AdminActions,
IAlchemistV2Errors,
IAlchemistV2Immutables,
IAlchemistV2Events,
IAlchemistV2State
{ }
pragma solidity >=0.5.0;
/// @title IERC20Minimal
/// @author Alchemix Finance
interface IERC20Minimal {
/// @notice An event which is emitted when tokens are transferred between two parties.
///
/// @param owner The owner of the tokens from which the tokens were transferred.
/// @param recipient The recipient of the tokens to which the tokens were transferred.
/// @param amount The amount of tokens which were transferred.
event Transfer(address indexed owner, address indexed recipient, uint256 amount);
/// @notice An event which is emitted when an approval is made.
///
/// @param owner The address which made the approval.
/// @param spender The address which is allowed to transfer tokens on behalf of `owner`.
/// @param amount The amount of tokens that `spender` is allowed to transfer.
event Approval(address indexed owner, address indexed spender, uint256 amount);
/// @notice Gets the current total supply of tokens.
///
/// @return The total supply.
function totalSupply() external view returns (uint256);
/// @notice Gets the balance of tokens that an account holds.
///
/// @param account The account address.
///
/// @return The balance of the account.
function balanceOf(address account) external view returns (uint256);
/// @notice Gets the allowance that an owner has allotted for a spender.
///
/// @param owner The owner address.
/// @param spender The spender address.
///
/// @return The number of tokens that `spender` is allowed to transfer on behalf of `owner`.
function allowance(address owner, address spender) external view returns (uint256);
/// @notice Transfers `amount` tokens from `msg.sender` to `recipient`.
///
/// @notice Emits a {Transfer} event.
///
/// @param recipient The address which will receive the tokens.
/// @param amount The amount of tokens to transfer.
///
/// @return If the transfer was successful.
function transfer(address recipient, uint256 amount) external returns (bool);
/// @notice Approves `spender` to transfer `amount` tokens on behalf of `msg.sender`.
///
/// @notice Emits a {Approval} event.
///
/// @param spender The address which is allowed to transfer tokens on behalf of `msg.sender`.
/// @param amount The amount of tokens that `spender` is allowed to transfer.
///
/// @return If the approval was successful.
function approve(address spender, uint256 amount) external returns (bool);
/// @notice Transfers `amount` tokens from `owner` to `recipient` using an approval that `owner` gave to `msg.sender`.
///
/// @notice Emits a {Approval} event.
/// @notice Emits a {Transfer} event.
///
/// @param owner The address to transfer tokens from.
/// @param recipient The address that will receive the tokens.
/// @param amount The amount of tokens to transfer.
///
/// @return If the transfer was successful.
function transferFrom(address owner, address recipient, uint256 amount) external returns (bool);
}
pragma solidity >=0.5.0;
/// @title IERC20TokenReceiver
/// @author Alchemix Finance
interface IERC20TokenReceiver {
/// @notice Informs implementors of this interface that an ERC20 token has been transferred.
///
/// @param token The token that was transferred.
/// @param value The amount of the token that was transferred.
function onERC20Received(address token, uint256 value) external;
}
pragma solidity >=0.5.0;
/// @title ITokenAdapter
/// @author Alchemix Finance
interface ITokenAdapter {
/// @notice Gets the current version.
///
/// @return The version.
function version() external view returns (string memory);
/// @notice Gets the address of the yield token that this adapter supports.
///
/// @return The address of the yield token.
function token() external view returns (address);
/// @notice Gets the address of the underlying token that the yield token wraps.
///
/// @return The address of the underlying token.
function underlyingToken() external view returns (address);
/// @notice Gets the number of underlying tokens that a single whole yield token is redeemable for.
///
/// @return The price.
function price() external view returns (uint256);
/// @notice Wraps `amount` underlying tokens into the yield token.
///
/// @param amount The amount of the underlying token to wrap.
/// @param recipient The address which will receive the yield tokens.
///
/// @return amountYieldTokens The amount of yield tokens minted to `recipient`.
function wrap(uint256 amount, address recipient)
external
returns (uint256 amountYieldTokens);
/// @notice Unwraps `amount` yield tokens into the underlying token.
///
/// @param amount The amount of yield-tokens to redeem.
/// @param recipient The recipient of the resulting underlying-tokens.
///
/// @return amountUnderlyingTokens The amount of underlying tokens unwrapped to `recipient`.
function unwrap(uint256 amount, address recipient)
external
returns (uint256 amountUnderlyingTokens);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.5.0;
import "./IERC20Burnable.sol";
import "./IERC20Minimal.sol";
import "./IERC20Mintable.sol";
/// @title IAlchemicToken
/// @author Alchemix Finance
interface IAlchemicToken is IERC20Minimal, IERC20Burnable, IERC20Mintable {
/// @notice Gets the total amount of minted tokens for an account.
///
/// @param account The address of the account.
///
/// @return The total minted.
function hasMinted(address account) external view returns (uint256);
/// @notice Lowers the number of tokens which the `msg.sender` has minted.
///
/// This reverts if the `msg.sender` is not whitelisted.
///
/// @param amount The amount to lower the minted amount by.
function lowerHasMinted(uint256 amount) external;
}
pragma solidity ^0.8.11;
import "../base/Errors.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../libraries/Sets.sol";
/// @title Whitelist
/// @author Alchemix Finance
interface IWhitelist {
/// @dev Emitted when a contract is added to the whitelist.
///
/// @param account The account that was added to the whitelist.
event AccountAdded(address account);
/// @dev Emitted when a contract is removed from the whitelist.
///
/// @param account The account that was removed from the whitelist.
event AccountRemoved(address account);
/// @dev Emitted when the whitelist is deactivated.
event WhitelistDisabled();
/// @dev Returns the list of addresses that are whitelisted for the given contract address.
///
/// @return addresses The addresses that are whitelisted to interact with the given contract.
function getAddresses() external view returns (address[] memory addresses);
/// @dev Returns the disabled status of a given whitelist.
///
/// @return disabled A flag denoting if the given whitelist is disabled.
function disabled() external view returns (bool);
/// @dev Adds an contract to the whitelist.
///
/// @param caller The address to add to the whitelist.
function add(address caller) external;
/// @dev Adds a contract to the whitelist.
///
/// @param caller The address to remove from the whitelist.
function remove(address caller) external;
/// @dev Disables the whitelist of the target whitelisted contract.
///
/// This can only occur once. Once the whitelist is disabled, then it cannot be reenabled.
function disable() external;
/// @dev Checks that the `msg.sender` is whitelisted when it is not an EOA.
///
/// @param account The account to check.
///
/// @return whitelisted A flag denoting if the given account is whitelisted.
function isWhitelisted(address account) external view returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import {IllegalArgument} from "../base/Errors.sol";
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param y The uint256 to be casted
/// @return z The casted integer, now type int256
function toInt256(uint256 y) internal pure returns (int256 z) {
if (y >= 2**255) {
revert IllegalArgument();
}
z = int256(y);
}
/// @notice Cast a int256 to a uint256, revert on underflow
/// @param y The int256 to be casted
/// @return z The casted integer, now type uint256
function toUint256(int256 y) internal pure returns (uint256 z) {
if (y < 0) {
revert IllegalArgument();
}
z = uint256(y);
}
}
pragma solidity ^0.8.11;
/// @title Sets
/// @author Alchemix Finance
library Sets {
using Sets for AddressSet;
/// @notice A data structure holding an array of values with an index mapping for O(1) lookup.
struct AddressSet {
address[] values;
mapping(address => uint256) indexes;
}
/// @dev Add a value to a Set
///
/// @param self The Set.
/// @param value The value to add.
///
/// @return Whether the operation was successful (unsuccessful if the value is already contained in the Set)
function add(AddressSet storage self, address value) internal returns (bool) {
if (self.contains(value)) {
return false;
}
self.values.push(value);
self.indexes[value] = self.values.length;
return true;
}
/// @dev Remove a value from a Set
///
/// @param self The Set.
/// @param value The value to remove.
///
/// @return Whether the operation was successful (unsuccessful if the value was not contained in the Set)
function remove(AddressSet storage self, address value) internal returns (bool) {
uint256 index = self.indexes[value];
if (index == 0) {
return false;
}
// Normalize the index since we know that the element is in the set.
index--;
uint256 lastIndex = self.values.length - 1;
if (index != lastIndex) {
address lastValue = self.values[lastIndex];
self.values[index] = lastValue;
self.indexes[lastValue] = index + 1;
}
self.values.pop();
delete self.indexes[value];
return true;
}
/// @dev Returns true if the value exists in the Set
///
/// @param self The Set.
/// @param value The value to check.
///
/// @return True if the value is contained in the Set, False if it is not.
function contains(AddressSet storage self, address value) internal view returns (bool) {
return self.indexes[value] != 0;
}
}
pragma solidity ^0.8.11;
import "../interfaces/IERC20Burnable.sol";
import "../interfaces/IERC20Metadata.sol";
import "../interfaces/IERC20Minimal.sol";
import "../interfaces/IERC20Mintable.sol";
/// @title TokenUtils
/// @author Alchemix Finance
library TokenUtils {
/// @notice An error used to indicate that a call to an ERC20 contract failed.
///
/// @param target The target address.
/// @param success If the call to the token was a success.
/// @param data The resulting data from the call. This is error data when the call was not a success. Otherwise,
/// this is malformed data when the call was a success.
error ERC20CallFailed(address target, bool success, bytes data);
/// @dev A safe function to get the decimals of an ERC20 token.
///
/// @dev Reverts with a {CallFailed} error if execution of the query fails or returns an unexpected value.
///
/// @param token The target token.
///
/// @return The amount of decimals of the token.
function expectDecimals(address token) internal view returns (uint8) {
(bool success, bytes memory data) = token.staticcall(
abi.encodeWithSelector(IERC20Metadata.decimals.selector)
);
if (!success || data.length < 32) {
revert ERC20CallFailed(token, success, data);
}
return abi.decode(data, (uint8));
}
/// @dev Gets the balance of tokens held by an account.
///
/// @dev Reverts with a {CallFailed} error if execution of the query fails or returns an unexpected value.
///
/// @param token The token to check the balance of.
/// @param account The address of the token holder.
///
/// @return The balance of the tokens held by an account.
function safeBalanceOf(address token, address account) internal view returns (uint256) {
(bool success, bytes memory data) = token.staticcall(
abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, account)
);
if (!success || data.length < 32) {
revert ERC20CallFailed(token, success, data);
}
return abi.decode(data, (uint256));
}
/// @dev Transfers tokens to another address.
///
/// @dev Reverts with a {CallFailed} error if execution of the transfer failed or returns an unexpected value.
///
/// @param token The token to transfer.
/// @param recipient The address of the recipient.
/// @param amount The amount of tokens to transfer.
function safeTransfer(address token, address recipient, uint256 amount) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Minimal.transfer.selector, recipient, amount)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
/// @dev Approves tokens for the smart contract.
///
/// @dev Reverts with a {CallFailed} error if execution of the approval fails or returns an unexpected value.
///
/// @param token The token to approve.
/// @param spender The contract to spend the tokens.
/// @param value The amount of tokens to approve.
function safeApprove(address token, address spender, uint256 value) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Minimal.approve.selector, spender, value)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
/// @dev Transfer tokens from one address to another address.
///
/// @dev Reverts with a {CallFailed} error if execution of the transfer fails or returns an unexpected value.
///
/// @param token The token to transfer.
/// @param owner The address of the owner.
/// @param recipient The address of the recipient.
/// @param amount The amount of tokens to transfer.
function safeTransferFrom(address token, address owner, address recipient, uint256 amount) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Minimal.transferFrom.selector, owner, recipient, amount)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
/// @dev Mints tokens to an address.
///
/// @dev Reverts with a {CallFailed} error if execution of the mint fails or returns an unexpected value.
///
/// @param token The token to mint.
/// @param recipient The address of the recipient.
/// @param amount The amount of tokens to mint.
function safeMint(address token, address recipient, uint256 amount) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Mintable.mint.selector, recipient, amount)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
/// @dev Burns tokens.
///
/// Reverts with a `CallFailed` error if execution of the burn fails or returns an unexpected value.
///
/// @param token The token to burn.
/// @param amount The amount of tokens to burn.
function safeBurn(address token, uint256 amount) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Burnable.burn.selector, amount)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
/// @dev Burns tokens from its total supply.
///
/// @dev Reverts with a {CallFailed} error if execution of the burn fails or returns an unexpected value.
///
/// @param token The token to burn.
/// @param owner The owner of the tokens.
/// @param amount The amount of tokens to burn.
function safeBurnFrom(address token, address owner, uint256 amount) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Burnable.burnFrom.selector, owner, amount)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
}
pragma solidity ^0.8.11;
import {IllegalArgument} from "../base/Errors.sol";
/// @title Functions
/// @author Alchemix Finance
library Limiters {
using Limiters for LinearGrowthLimiter;
/// @dev A maximum cooldown to avoid malicious governance bricking the contract.
/// @dev 1 day @ 12 sec / block
uint256 constant public MAX_COOLDOWN_BLOCKS = 7200;
/// @dev The scalar used to convert integral types to fixed point numbers.
uint256 constant public FIXED_POINT_SCALAR = 1e18;
/// @dev The configuration and state of a linear growth function (LGF).
struct LinearGrowthLimiter {
uint256 maximum; /// The maximum limit of the function.
uint256 rate; /// The rate at which the function increases back to its maximum.
uint256 lastValue; /// The most recently saved value of the function.
uint256 lastBlock; /// The block that `lastValue` was recorded.
uint256 minLimit; /// A minimum limit to avoid malicious governance bricking the contract
}
/// @dev Instantiates a new linear growth function.
///
/// @param maximum The maximum value for the LGF.
/// @param blocks The number of blocks that determins the rate of the LGF.
///
/// @return The LGF struct.
function createLinearGrowthLimiter(uint256 maximum, uint256 blocks, uint256 _minLimit) internal view returns (LinearGrowthLimiter memory) {
if (blocks > MAX_COOLDOWN_BLOCKS) {
revert IllegalArgument();
}
if (maximum < _minLimit) {
revert IllegalArgument();
}
return LinearGrowthLimiter({
maximum: maximum,
rate: maximum * FIXED_POINT_SCALAR / blocks,
lastValue: maximum,
lastBlock: block.number,
minLimit: _minLimit
});
}
/// @dev Configure an LGF.
///
/// @param self The LGF to configure.
/// @param maximum The maximum value of the LFG.
/// @param blocks The number of recovery blocks of the LGF.
function configure(LinearGrowthLimiter storage self, uint256 maximum, uint256 blocks) internal {
if (blocks > MAX_COOLDOWN_BLOCKS) {
revert IllegalArgument();
}
if (maximum < self.minLimit) {
revert IllegalArgument();
}
if (self.lastValue > maximum) {
self.lastValue = maximum;
}
self.maximum = maximum;
self.rate = maximum * FIXED_POINT_SCALAR / blocks;
}
/// @dev Updates the state of an LGF by updating `lastValue` and `lastBlock`.
///
/// @param self the LGF to update.
function update(LinearGrowthLimiter storage self) internal {
self.lastValue = self.get();
self.lastBlock = block.number;
}
/// @dev Decrease the value of the linear growth limiter.
///
/// @param self The linear growth limiter.
/// @param amount The amount to decrease `lastValue`.
function decrease(LinearGrowthLimiter storage self, uint256 amount) internal {
uint256 value = self.get();
self.lastValue = value - amount;
self.lastBlock = block.number;
}
/// @dev Get the current value of the linear growth limiter.
///
/// @return The current value.
function get(LinearGrowthLimiter storage self) internal view returns (uint256) {
uint256 elapsed = block.number - self.lastBlock;
if (elapsed == 0) {
return self.lastValue;
}
uint256 delta = elapsed * self.rate / FIXED_POINT_SCALAR;
uint256 value = self.lastValue + delta;
return value > self.maximum ? self.maximum : value;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @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 on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
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");
(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");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Multicall interface
/// @author Uniswap Labs
///
/// @notice Enables calling multiple methods in a single call to the contract.
/// @dev The use of `msg.value` should be heavily scrutinized for implementors of this interfaces.
interface IMulticall {
/// @notice An error used to indicate that an individual call in a multicall failed.
///
/// @param data The call data.
/// @param result The result of the call.
error MulticallFailed(bytes data, bytes result);
/// @notice Call multiple functions in the implementing contract.
///
/// @param data The encoded function data for each of the calls to make to this contract.
///
/// @return results The results from each of the calls passed in via data.
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}
pragma solidity >=0.5.0;
/// @title IAlchemistV2Actions
/// @author Alchemix Finance
///
/// @notice Specifies user actions.
interface IAlchemistV2Actions {
/// @notice Approve `spender` to mint `amount` debt tokens.
///
/// **_NOTE:_** This function is WHITELISTED.
///
/// @param spender The address that will be approved to mint.
/// @param amount The amount of tokens that `spender` will be allowed to mint.
function approveMint(address spender, uint256 amount) external;
/// @notice Approve `spender` to withdraw `amount` shares of `yieldToken`.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @param spender The address that will be approved to withdraw.
/// @param yieldToken The address of the yield token that `spender` will be allowed to withdraw.
/// @param shares The amount of shares that `spender` will be allowed to withdraw.
function approveWithdraw(
address spender,
address yieldToken,
uint256 shares
) external;
/// @notice Synchronizes the state of the account owned by `owner`.
///
/// @param owner The owner of the account to synchronize.
function poke(address owner) external;
/// @notice Deposit a yield token into a user's account.
///
/// @notice An approval must be set for `yieldToken` which is greater than `amount`.
///
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `yieldToken` must be enabled or this call will revert with a {TokenDisabled} error.
/// @notice `yieldToken` underlying token must be enabled or this call will revert with a {TokenDisabled} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice `amount` must be greater than zero or the call will revert with an {IllegalArgument} error.
///
/// @notice Emits a {Deposit} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **_NOTE:_** When depositing, the `AlchemistV2` contract must have **allowance()** to spend funds on behalf of **msg.sender** for at least **amount** of the **yieldToken** being deposited. This can be done via the standard `ERC20.approve()` method.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 amount = 50000;
/// @notice IERC20(ydai).approve(alchemistAddress, amount);
/// @notice AlchemistV2(alchemistAddress).deposit(ydai, amount, msg.sender);
/// @notice ```
///
/// @param yieldToken The yield-token to deposit.
/// @param amount The amount of yield tokens to deposit.
/// @param recipient The owner of the account that will receive the resulting shares.
///
/// @return sharesIssued The number of shares issued to `recipient`.
function deposit(
address yieldToken,
uint256 amount,
address recipient
) external returns (uint256 sharesIssued);
/// @notice Deposit an underlying token into the account of `recipient` as `yieldToken`.
///
/// @notice An approval must be set for the underlying token of `yieldToken` which is greater than `amount`.
///
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice `amount` must be greater than zero or the call will revert with an {IllegalArgument} error.
///
/// @notice Emits a {Deposit} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
/// @notice **_NOTE:_** When depositing, the `AlchemistV2` contract must have **allowance()** to spend funds on behalf of **msg.sender** for at least **amount** of the **underlyingToken** being deposited. This can be done via the standard `ERC20.approve()` method.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 amount = 50000;
/// @notice AlchemistV2(alchemistAddress).depositUnderlying(ydai, amount, msg.sender, 1);
/// @notice ```
///
/// @param yieldToken The address of the yield token to wrap the underlying tokens into.
/// @param amount The amount of the underlying token to deposit.
/// @param recipient The address of the recipient.
/// @param minimumAmountOut The minimum amount of yield tokens that are expected to be deposited to `recipient`.
///
/// @return sharesIssued The number of shares issued to `recipient`.
function depositUnderlying(
address yieldToken,
uint256 amount,
address recipient,
uint256 minimumAmountOut
) external returns (uint256 sharesIssued);
/// @notice Withdraw yield tokens to `recipient` by burning `share` shares. The number of yield tokens withdrawn to `recipient` will depend on the value of shares for that yield token at the time of the call.
///
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
///
/// @notice Emits a {Withdraw} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 pps = AlchemistV2(alchemistAddress).getYieldTokensPerShare(ydai);
/// @notice uint256 amtYieldTokens = 5000;
/// @notice AlchemistV2(alchemistAddress).withdraw(ydai, amtYieldTokens / pps, msg.sender);
/// @notice ```
///
/// @param yieldToken The address of the yield token to withdraw.
/// @param shares The number of shares to burn.
/// @param recipient The address of the recipient.
///
/// @return amountWithdrawn The number of yield tokens that were withdrawn to `recipient`.
function withdraw(
address yieldToken,
uint256 shares,
address recipient
) external returns (uint256 amountWithdrawn);
/// @notice Withdraw yield tokens to `recipient` by burning `share` shares from the account of `owner`
///
/// @notice `owner` must have an withdrawal allowance which is greater than `amount` for this call to succeed.
///
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
///
/// @notice Emits a {Withdraw} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 pps = AlchemistV2(alchemistAddress).getYieldTokensPerShare(ydai);
/// @notice uint256 amtYieldTokens = 5000;
/// @notice AlchemistV2(alchemistAddress).withdrawFrom(msg.sender, ydai, amtYieldTokens / pps, msg.sender);
/// @notice ```
///
/// @param owner The address of the account owner to withdraw from.
/// @param yieldToken The address of the yield token to withdraw.
/// @param shares The number of shares to burn.
/// @param recipient The address of the recipient.
///
/// @return amountWithdrawn The number of yield tokens that were withdrawn to `recipient`.
function withdrawFrom(
address owner,
address yieldToken,
uint256 shares,
address recipient
) external returns (uint256 amountWithdrawn);
/// @notice Withdraw underlying tokens to `recipient` by burning `share` shares and unwrapping the yield tokens that the shares were redeemed for.
///
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice The loss in expected value of `yieldToken` must be less than the maximum permitted by the system or this call will revert with a {LossExceeded} error.
///
/// @notice Emits a {Withdraw} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
/// @notice **_NOTE:_** The caller of `withdrawFrom()` must have **withdrawAllowance()** to withdraw funds on behalf of **owner** for at least the amount of `yieldTokens` that **shares** will be converted to. This can be done via the `approveWithdraw()` or `permitWithdraw()` methods.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 pps = AlchemistV2(alchemistAddress).getUnderlyingTokensPerShare(ydai);
/// @notice uint256 amountUnderlyingTokens = 5000;
/// @notice AlchemistV2(alchemistAddress).withdrawUnderlying(ydai, amountUnderlyingTokens / pps, msg.sender, 1);
/// @notice ```
///
/// @param yieldToken The address of the yield token to withdraw.
/// @param shares The number of shares to burn.
/// @param recipient The address of the recipient.
/// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be withdrawn to `recipient`.
///
/// @return amountWithdrawn The number of underlying tokens that were withdrawn to `recipient`.
function withdrawUnderlying(
address yieldToken,
uint256 shares,
address recipient,
uint256 minimumAmountOut
) external returns (uint256 amountWithdrawn);
/// @notice Withdraw underlying tokens to `recipient` by burning `share` shares from the account of `owner` and unwrapping the yield tokens that the shares were redeemed for.
///
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice The loss in expected value of `yieldToken` must be less than the maximum permitted by the system or this call will revert with a {LossExceeded} error.
///
/// @notice Emits a {Withdraw} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
/// @notice **_NOTE:_** The caller of `withdrawFrom()` must have **withdrawAllowance()** to withdraw funds on behalf of **owner** for at least the amount of `yieldTokens` that **shares** will be converted to. This can be done via the `approveWithdraw()` or `permitWithdraw()` methods.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 pps = AlchemistV2(alchemistAddress).getUnderlyingTokensPerShare(ydai);
/// @notice uint256 amtUnderlyingTokens = 5000 * 10**ydai.decimals();
/// @notice AlchemistV2(alchemistAddress).withdrawUnderlying(msg.sender, ydai, amtUnderlyingTokens / pps, msg.sender, 1);
/// @notice ```
///
/// @param owner The address of the account owner to withdraw from.
/// @param yieldToken The address of the yield token to withdraw.
/// @param shares The number of shares to burn.
/// @param recipient The address of the recipient.
/// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be withdrawn to `recipient`.
///
/// @return amountWithdrawn The number of underlying tokens that were withdrawn to `recipient`.
function withdrawUnderlyingFrom(
address owner,
address yieldToken,
uint256 shares,
address recipient,
uint256 minimumAmountOut
) external returns (uint256 amountWithdrawn);
/// @notice Mint `amount` debt tokens.
///
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error.
///
/// @notice Emits a {Mint} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice uint256 amtDebt = 5000;
/// @notice AlchemistV2(alchemistAddress).mint(amtDebt, msg.sender);
/// @notice ```
///
/// @param amount The amount of tokens to mint.
/// @param recipient The address of the recipient.
function mint(uint256 amount, address recipient) external;
/// @notice Mint `amount` debt tokens from the account owned by `owner` to `recipient`.
///
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error.
///
/// @notice Emits a {Mint} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
/// @notice **_NOTE:_** The caller of `mintFrom()` must have **mintAllowance()** to mint debt from the `Account` controlled by **owner** for at least the amount of **yieldTokens** that **shares** will be converted to. This can be done via the `approveMint()` or `permitMint()` methods.
///
/// @notice **Example:**
/// @notice ```
/// @notice uint256 amtDebt = 5000;
/// @notice AlchemistV2(alchemistAddress).mintFrom(msg.sender, amtDebt, msg.sender);
/// @notice ```
///
/// @param owner The address of the owner of the account to mint from.
/// @param amount The amount of tokens to mint.
/// @param recipient The address of the recipient.
function mintFrom(
address owner,
uint256 amount,
address recipient
) external;
/// @notice Burn `amount` debt tokens to credit the account owned by `recipient`.
///
/// @notice `amount` will be limited up to the amount of debt that `recipient` currently holds.
///
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error.
/// @notice `recipient` must have non-zero debt or this call will revert with an {IllegalState} error.
///
/// @notice Emits a {Burn} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice uint256 amtBurn = 5000;
/// @notice AlchemistV2(alchemistAddress).burn(amtBurn, msg.sender);
/// @notice ```
///
/// @param amount The amount of tokens to burn.
/// @param recipient The address of the recipient.
///
/// @return amountBurned The amount of tokens that were burned.
function burn(uint256 amount, address recipient) external returns (uint256 amountBurned);
/// @notice Repay `amount` debt using `underlyingToken` to credit the account owned by `recipient`.
///
/// @notice `amount` will be limited up to the amount of debt that `recipient` currently holds.
///
/// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice `underlyingToken` must be enabled or this call will revert with a {TokenDisabled} error.
/// @notice `amount` must be less than or equal to the current available repay limit or this call will revert with a {ReplayLimitExceeded} error.
///
/// @notice Emits a {Repay} event.
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice address dai = 0x6b175474e89094c44da98b954eedeac495271d0f;
/// @notice uint256 amtRepay = 5000;
/// @notice AlchemistV2(alchemistAddress).repay(dai, amtRepay, msg.sender);
/// @notice ```
///
/// @param underlyingToken The address of the underlying token to repay.
/// @param amount The amount of the underlying token to repay.
/// @param recipient The address of the recipient which will receive credit.
///
/// @return amountRepaid The amount of tokens that were repaid.
function repay(
address underlyingToken,
uint256 amount,
address recipient
) external returns (uint256 amountRepaid);
/// @notice
///
/// @notice `shares` will be limited up to an equal amount of debt that `recipient` currently holds.
///
/// @notice `shares` must be greater than zero or this call will revert with a {IllegalArgument} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `yieldToken` must be enabled or this call will revert with a {TokenDisabled} error.
/// @notice `yieldToken` underlying token must be enabled or this call will revert with a {TokenDisabled} error.
/// @notice The loss in expected value of `yieldToken` must be less than the maximum permitted by the system or this call will revert with a {LossExceeded} error.
/// @notice `amount` must be less than or equal to the current available liquidation limit or this call will revert with a {LiquidationLimitExceeded} error.
///
/// @notice Emits a {Liquidate} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 amtSharesLiquidate = 5000 * 10**ydai.decimals();
/// @notice AlchemistV2(alchemistAddress).liquidate(ydai, amtSharesLiquidate, 1);
/// @notice ```
///
/// @param yieldToken The address of the yield token to liquidate.
/// @param shares The number of shares to burn for credit.
/// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be liquidated.
///
/// @return sharesLiquidated The amount of shares that were liquidated.
function liquidate(
address yieldToken,
uint256 shares,
uint256 minimumAmountOut
) external returns (uint256 sharesLiquidated);
/// @notice Burns `amount` debt tokens to credit accounts which have deposited `yieldToken`.
///
/// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @notice Emits a {Donate} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 amtSharesLiquidate = 5000;
/// @notice AlchemistV2(alchemistAddress).liquidate(dai, amtSharesLiquidate, 1);
/// @notice ```
///
/// @param yieldToken The address of the yield token to credit accounts for.
/// @param amount The amount of debt tokens to burn.
function donate(address yieldToken, uint256 amount) external;
/// @notice Harvests outstanding yield that a yield token has accumulated and distributes it as credit to holders.
///
/// @notice `msg.sender` must be a keeper or this call will revert with an {Unauthorized} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice The amount being harvested must be greater than zero or else this call will revert with an {IllegalState} error.
///
/// @notice Emits a {Harvest} event.
///
/// @param yieldToken The address of the yield token to harvest.
/// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be withdrawn to `recipient`.
function harvest(address yieldToken, uint256 minimumAmountOut) external;
}
pragma solidity >=0.5.0;
/// @title IAlchemistV2AdminActions
/// @author Alchemix Finance
///
/// @notice Specifies admin and or sentinel actions.
interface IAlchemistV2AdminActions {
/// @notice Contract initialization parameters.
struct InitializationParams {
// The initial admin account.
address admin;
// The ERC20 token used to represent debt.
address debtToken;
// The initial transmuter or transmuter buffer.
address transmuter;
// The minimum collateralization ratio that an account must maintain.
uint256 minimumCollateralization;
// The percentage fee taken from each harvest measured in units of basis points.
uint256 protocolFee;
// The address that receives protocol fees.
address protocolFeeReceiver;
// A limit used to prevent administrators from making minting functionality inoperable.
uint256 mintingLimitMinimum;
// The maximum number of tokens that can be minted per period of time.
uint256 mintingLimitMaximum;
// The number of blocks that it takes for the minting limit to be refreshed.
uint256 mintingLimitBlocks;
// The address of the whitelist.
address whitelist;
}
/// @notice Configuration parameters for an underlying token.
struct UnderlyingTokenConfig {
// A limit used to prevent administrators from making repayment functionality inoperable.
uint256 repayLimitMinimum;
// The maximum number of underlying tokens that can be repaid per period of time.
uint256 repayLimitMaximum;
// The number of blocks that it takes for the repayment limit to be refreshed.
uint256 repayLimitBlocks;
// A limit used to prevent administrators from making liquidation functionality inoperable.
uint256 liquidationLimitMinimum;
// The maximum number of underlying tokens that can be liquidated per period of time.
uint256 liquidationLimitMaximum;
// The number of blocks that it takes for the liquidation limit to be refreshed.
uint256 liquidationLimitBlocks;
}
/// @notice Configuration parameters of a yield token.
struct YieldTokenConfig {
// The adapter used by the system to interop with the token.
address adapter;
// The maximum percent loss in expected value that can occur before certain actions are disabled measured in
// units of basis points.
uint256 maximumLoss;
// The maximum value that can be held by the system before certain actions are disabled measured in the
// underlying token.
uint256 maximumExpectedValue;
// The number of blocks that credit will be distributed over to depositors.
uint256 creditUnlockBlocks;
}
/// @notice Initialize the contract.
///
/// @notice `params.protocolFee` must be in range or this call will with an {IllegalArgument} error.
/// @notice The minting growth limiter parameters must be valid or this will revert with an {IllegalArgument} error. For more information, see the {Limiters} library.
///
/// @notice Emits an {AdminUpdated} event.
/// @notice Emits a {TransmuterUpdated} event.
/// @notice Emits a {MinimumCollateralizationUpdated} event.
/// @notice Emits a {ProtocolFeeUpdated} event.
/// @notice Emits a {ProtocolFeeReceiverUpdated} event.
/// @notice Emits a {MintingLimitUpdated} event.
///
/// @param params The contract initialization parameters.
function initialize(InitializationParams memory params) external;
/// @notice Sets the pending administrator.
///
/// @notice `msg.sender` must be the admin or this call will will revert with an {Unauthorized} error.
///
/// @notice Emits a {PendingAdminUpdated} event.
///
/// @dev This is the first step in the two-step process of setting a new administrator. After this function is called, the pending administrator will then need to call {acceptAdmin} to complete the process.
///
/// @param value the address to set the pending admin to.
function setPendingAdmin(address value) external;
/// @notice Allows for `msg.sender` to accepts the role of administrator.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice The current pending administrator must be non-zero or this call will revert with an {IllegalState} error.
///
/// @dev This is the second step in the two-step process of setting a new administrator. After this function is successfully called, this pending administrator will be reset and the new administrator will be set.
///
/// @notice Emits a {AdminUpdated} event.
/// @notice Emits a {PendingAdminUpdated} event.
function acceptAdmin() external;
/// @notice Sets an address as a sentinel.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
///
/// @param sentinel The address to set or unset as a sentinel.
/// @param flag A flag indicating of the address should be set or unset as a sentinel.
function setSentinel(address sentinel, bool flag) external;
/// @notice Sets an address as a keeper.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
///
/// @param keeper The address to set or unset as a keeper.
/// @param flag A flag indicating of the address should be set or unset as a keeper.
function setKeeper(address keeper, bool flag) external;
/// @notice Adds an underlying token to the system.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
///
/// @param underlyingToken The address of the underlying token to add.
/// @param config The initial underlying token configuration.
function addUnderlyingToken(
address underlyingToken,
UnderlyingTokenConfig calldata config
) external;
/// @notice Adds a yield token to the system.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
///
/// @notice Emits a {AddYieldToken} event.
/// @notice Emits a {TokenAdapterUpdated} event.
/// @notice Emits a {MaximumLossUpdated} event.
///
/// @param yieldToken The address of the yield token to add.
/// @param config The initial yield token configuration.
function addYieldToken(address yieldToken, YieldTokenConfig calldata config)
external;
/// @notice Sets an underlying token as either enabled or disabled.
///
/// @notice `msg.sender` must be either the admin or a sentinel or this call will revert with an {Unauthorized} error.
/// @notice `underlyingToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @notice Emits an {UnderlyingTokenEnabled} event.
///
/// @param underlyingToken The address of the underlying token to enable or disable.
/// @param enabled If the underlying token should be enabled or disabled.
function setUnderlyingTokenEnabled(address underlyingToken, bool enabled)
external;
/// @notice Sets a yield token as either enabled or disabled.
///
/// @notice `msg.sender` must be either the admin or a sentinel or this call will revert with an {Unauthorized} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @notice Emits a {YieldTokenEnabled} event.
///
/// @param yieldToken The address of the yield token to enable or disable.
/// @param enabled If the underlying token should be enabled or disabled.
function setYieldTokenEnabled(address yieldToken, bool enabled) external;
/// @notice Configures the the repay limit of `underlyingToken`.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `underlyingToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @notice Emits a {ReplayLimitUpdated} event.
///
/// @param underlyingToken The address of the underlying token to configure the repay limit of.
/// @param maximum The maximum repay limit.
/// @param blocks The number of blocks it will take for the maximum repayment limit to be replenished when it is completely exhausted.
function configureRepayLimit(
address underlyingToken,
uint256 maximum,
uint256 blocks
) external;
/// @notice Configure the liquidation limiter of `underlyingToken`.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `underlyingToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @notice Emits a {LiquidationLimitUpdated} event.
///
/// @param underlyingToken The address of the underlying token to configure the liquidation limit of.
/// @param maximum The maximum liquidation limit.
/// @param blocks The number of blocks it will take for the maximum liquidation limit to be replenished when it is completely exhausted.
function configureLiquidationLimit(
address underlyingToken,
uint256 maximum,
uint256 blocks
) external;
/// @notice Set the address of the transmuter.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `value` must be non-zero or this call will revert with an {IllegalArgument} error.
///
/// @notice Emits a {TransmuterUpdated} event.
///
/// @param value The address of the transmuter.
function setTransmuter(address value) external;
/// @notice Set the minimum collateralization ratio.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
///
/// @notice Emits a {MinimumCollateralizationUpdated} event.
///
/// @param value The new minimum collateralization ratio.
function setMinimumCollateralization(uint256 value) external;
/// @notice Sets the fee that the protocol will take from harvests.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `value` must be in range or this call will with an {IllegalArgument} error.
///
/// @notice Emits a {ProtocolFeeUpdated} event.
///
/// @param value The value to set the protocol fee to measured in basis points.
function setProtocolFee(uint256 value) external;
/// @notice Sets the address which will receive protocol fees.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `value` must be non-zero or this call will revert with an {IllegalArgument} error.
///
/// @notice Emits a {ProtocolFeeReceiverUpdated} event.
///
/// @param value The address to set the protocol fee receiver to.
function setProtocolFeeReceiver(address value) external;
/// @notice Configures the minting limiter.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
///
/// @notice Emits a {MintingLimitUpdated} event.
///
/// @param maximum The maximum minting limit.
/// @param blocks The number of blocks it will take for the maximum minting limit to be replenished when it is completely exhausted.
function configureMintingLimit(uint256 maximum, uint256 blocks) external;
/// @notice Sets the rate at which credit will be completely available to depositors after it is harvested.
///
/// @notice Emits a {CreditUnlockRateUpdated} event.
///
/// @param yieldToken The address of the yield token to set the credit unlock rate for.
/// @param blocks The number of blocks that it will take before the credit will be unlocked.
function configureCreditUnlockRate(address yieldToken, uint256 blocks) external;
/// @notice Sets the token adapter of a yield token.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice The token that `adapter` supports must be `yieldToken` or this call will revert with a {IllegalState} error.
///
/// @notice Emits a {TokenAdapterUpdated} event.
///
/// @param yieldToken The address of the yield token to set the adapter for.
/// @param adapter The address to set the token adapter to.
function setTokenAdapter(address yieldToken, address adapter) external;
/// @notice Sets the maximum expected value of a yield token that the system can hold.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @param yieldToken The address of the yield token to set the maximum expected value for.
/// @param value The maximum expected value of the yield token denoted measured in its underlying token.
function setMaximumExpectedValue(address yieldToken, uint256 value)
external;
/// @notice Sets the maximum loss that a yield bearing token will permit before restricting certain actions.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @dev There are two types of loss of value for yield bearing assets: temporary or permanent. The system will automatically restrict actions which are sensitive to both forms of loss when detected. For example, deposits must be restricted when an excessive loss is encountered to prevent users from having their collateral harvested from them. While the user would receive credit, which then could be exchanged for value equal to the collateral that was harvested from them, it is seen as a negative user experience because the value of their collateral should have been higher than what was originally recorded when they made their deposit.
///
/// @param yieldToken The address of the yield bearing token to set the maximum loss for.
/// @param value The value to set the maximum loss to. This is in units of basis points.
function setMaximumLoss(address yieldToken, uint256 value) external;
/// @notice Snap the expected value `yieldToken` to the current value.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @dev This function should only be used in the event of a loss in the target yield-token. For example, say a third-party protocol experiences a fifty percent loss. The expected value (amount of underlying tokens) of the yield tokens being held by the system would be two times the real value that those yield tokens could be redeemed for. This function gives governance a way to realize those losses so that users can continue using the token as normal.
///
/// @param yieldToken The address of the yield token to snap.
function snap(address yieldToken) external;
}
pragma solidity >=0.5.0;
/// @title IAlchemistV2Errors
/// @author Alchemix Finance
///
/// @notice Specifies errors.
interface IAlchemistV2Errors {
/// @notice An error which is used to indicate that an operation failed because it tried to operate on a token that the system did not recognize.
///
/// @param token The address of the token.
error UnsupportedToken(address token);
/// @notice An error which is used to indicate that an operation failed because it tried to operate on a token that has been disabled.
///
/// @param token The address of the token.
error TokenDisabled(address token);
/// @notice An error which is used to indicate that an operation failed because an account became undercollateralized.
error Undercollateralized();
/// @notice An error which is used to indicate that an operation failed because the expected value of a yield token in the system exceeds the maximum value permitted.
///
/// @param yieldToken The address of the yield token.
/// @param expectedValue The expected value measured in units of the underlying token.
/// @param maximumExpectedValue The maximum expected value permitted measured in units of the underlying token.
error ExpectedValueExceeded(address yieldToken, uint256 expectedValue, uint256 maximumExpectedValue);
/// @notice An error which is used to indicate that an operation failed because the loss that a yield token in the system exceeds the maximum value permitted.
///
/// @param yieldToken The address of the yield token.
/// @param loss The amount of loss measured in basis points.
/// @param maximumLoss The maximum amount of loss permitted measured in basis points.
error LossExceeded(address yieldToken, uint256 loss, uint256 maximumLoss);
/// @notice An error which is used to indicate that a minting operation failed because the minting limit has been exceeded.
///
/// @param amount The amount of debt tokens that were requested to be minted.
/// @param available The amount of debt tokens which are available to mint.
error MintingLimitExceeded(uint256 amount, uint256 available);
/// @notice An error which is used to indicate that an repay operation failed because the repay limit for an underlying token has been exceeded.
///
/// @param underlyingToken The address of the underlying token.
/// @param amount The amount of underlying tokens that were requested to be repaid.
/// @param available The amount of underlying tokens that are available to be repaid.
error RepayLimitExceeded(address underlyingToken, uint256 amount, uint256 available);
/// @notice An error which is used to indicate that an repay operation failed because the liquidation limit for an underlying token has been exceeded.
///
/// @param underlyingToken The address of the underlying token.
/// @param amount The amount of underlying tokens that were requested to be liquidated.
/// @param available The amount of underlying tokens that are available to be liquidated.
error LiquidationLimitExceeded(address underlyingToken, uint256 amount, uint256 available);
/// @notice An error which is used to indicate that the slippage of a wrap or unwrap operation was exceeded.
///
/// @param amount The amount of underlying or yield tokens returned by the operation.
/// @param minimumAmountOut The minimum amount of the underlying or yield token that was expected when performing
/// the operation.
error SlippageExceeded(uint256 amount, uint256 minimumAmountOut);
}
pragma solidity >=0.5.0;
/// @title IAlchemistV2Immutables
/// @author Alchemix Finance
interface IAlchemistV2Immutables {
/// @notice Returns the version of the alchemist.
///
/// @return The version.
function version() external view returns (string memory);
/// @notice Returns the address of the debt token used by the system.
///
/// @return The address of the debt token.
function debtToken() external view returns (address);
}
pragma solidity >=0.5.0;
/// @title IAlchemistV2Events
/// @author Alchemix Finance
interface IAlchemistV2Events {
/// @notice Emitted when the pending admin is updated.
///
/// @param pendingAdmin The address of the pending admin.
event PendingAdminUpdated(address pendingAdmin);
/// @notice Emitted when the administrator is updated.
///
/// @param admin The address of the administrator.
event AdminUpdated(address admin);
/// @notice Emitted when an address is set or unset as a sentinel.
///
/// @param sentinel The address of the sentinel.
/// @param flag A flag indicating if `sentinel` was set or unset as a sentinel.
event SentinelSet(address sentinel, bool flag);
/// @notice Emitted when an address is set or unset as a keeper.
///
/// @param sentinel The address of the keeper.
/// @param flag A flag indicating if `keeper` was set or unset as a sentinel.
event KeeperSet(address sentinel, bool flag);
/// @notice Emitted when an underlying token is added.
///
/// @param underlyingToken The address of the underlying token that was added.
event AddUnderlyingToken(address indexed underlyingToken);
/// @notice Emitted when a yield token is added.
///
/// @param yieldToken The address of the yield token that was added.
event AddYieldToken(address indexed yieldToken);
/// @notice Emitted when an underlying token is enabled or disabled.
///
/// @param underlyingToken The address of the underlying token that was enabled or disabled.
/// @param enabled A flag indicating if the underlying token was enabled or disabled.
event UnderlyingTokenEnabled(address indexed underlyingToken, bool enabled);
/// @notice Emitted when an yield token is enabled or disabled.
///
/// @param yieldToken The address of the yield token that was enabled or disabled.
/// @param enabled A flag indicating if the yield token was enabled or disabled.
event YieldTokenEnabled(address indexed yieldToken, bool enabled);
/// @notice Emitted when the repay limit of an underlying token is updated.
///
/// @param underlyingToken The address of the underlying token.
/// @param maximum The updated maximum repay limit.
/// @param blocks The updated number of blocks it will take for the maximum repayment limit to be replenished when it is completely exhausted.
event RepayLimitUpdated(address indexed underlyingToken, uint256 maximum, uint256 blocks);
/// @notice Emitted when the liquidation limit of an underlying token is updated.
///
/// @param underlyingToken The address of the underlying token.
/// @param maximum The updated maximum liquidation limit.
/// @param blocks The updated number of blocks it will take for the maximum liquidation limit to be replenished when it is completely exhausted.
event LiquidationLimitUpdated(address indexed underlyingToken, uint256 maximum, uint256 blocks);
/// @notice Emitted when the transmuter is updated.
///
/// @param transmuter The updated address of the transmuter.
event TransmuterUpdated(address transmuter);
/// @notice Emitted when the minimum collateralization is updated.
///
/// @param minimumCollateralization The updated minimum collateralization.
event MinimumCollateralizationUpdated(uint256 minimumCollateralization);
/// @notice Emitted when the protocol fee is updated.
///
/// @param protocolFee The updated protocol fee.
event ProtocolFeeUpdated(uint256 protocolFee);
/// @notice Emitted when the protocol fee receiver is updated.
///
/// @param protocolFeeReceiver The updated address of the protocol fee receiver.
event ProtocolFeeReceiverUpdated(address protocolFeeReceiver);
/// @notice Emitted when the minting limit is updated.
///
/// @param maximum The updated maximum minting limit.
/// @param blocks The updated number of blocks it will take for the maximum minting limit to be replenished when it is completely exhausted.
event MintingLimitUpdated(uint256 maximum, uint256 blocks);
/// @notice Emitted when the credit unlock rate is updated.
///
/// @param yieldToken The address of the yield token.
/// @param blocks The number of blocks that distributed credit will unlock over.
event CreditUnlockRateUpdated(address yieldToken, uint256 blocks);
/// @notice Emitted when the adapter of a yield token is updated.
///
/// @param yieldToken The address of the yield token.
/// @param tokenAdapter The updated address of the token adapter.
event TokenAdapterUpdated(address yieldToken, address tokenAdapter);
/// @notice Emitted when the maximum expected value of a yield token is updated.
///
/// @param yieldToken The address of the yield token.
/// @param maximumExpectedValue The updated maximum expected value.
event MaximumExpectedValueUpdated(address indexed yieldToken, uint256 maximumExpectedValue);
/// @notice Emitted when the maximum loss of a yield token is updated.
///
/// @param yieldToken The address of the yield token.
/// @param maximumLoss The updated maximum loss.
event MaximumLossUpdated(address indexed yieldToken, uint256 maximumLoss);
/// @notice Emitted when the expected value of a yield token is snapped to its current value.
///
/// @param yieldToken The address of the yield token.
/// @param expectedValue The updated expected value measured in the yield token's underlying token.
event Snap(address indexed yieldToken, uint256 expectedValue);
/// @notice Emitted when `owner` grants `spender` the ability to mint debt tokens on its behalf.
///
/// @param owner The address of the account owner.
/// @param spender The address which is being permitted to mint tokens on the behalf of `owner`.
/// @param amount The amount of debt tokens that `spender` is allowed to mint.
event ApproveMint(address indexed owner, address indexed spender, uint256 amount);
/// @notice Emitted when `owner` grants `spender` the ability to withdraw `yieldToken` from its account.
///
/// @param owner The address of the account owner.
/// @param spender The address which is being permitted to mint tokens on the behalf of `owner`.
/// @param yieldToken The address of the yield token that `spender` is allowed to withdraw.
/// @param amount The amount of shares of `yieldToken` that `spender` is allowed to withdraw.
event ApproveWithdraw(address indexed owner, address indexed spender, address indexed yieldToken, uint256 amount);
/// @notice Emitted when a user deposits `amount of `yieldToken` to `recipient`.
///
/// @notice This event does not imply that `sender` directly deposited yield tokens. It is possible that the
/// underlying tokens were wrapped.
///
/// @param sender The address of the user which deposited funds.
/// @param yieldToken The address of the yield token that was deposited.
/// @param amount The amount of yield tokens that were deposited.
/// @param recipient The address that received the deposited funds.
event Deposit(address indexed sender, address indexed yieldToken, uint256 amount, address recipient);
/// @notice Emitted when `shares` shares of `yieldToken` are burned to withdraw `yieldToken` from the account owned
/// by `owner` to `recipient`.
///
/// @notice This event does not imply that `recipient` received yield tokens. It is possible that the yield tokens
/// were unwrapped.
///
/// @param owner The address of the account owner.
/// @param yieldToken The address of the yield token that was withdrawn.
/// @param shares The amount of shares that were burned.
/// @param recipient The address that received the withdrawn funds.
event Withdraw(address indexed owner, address indexed yieldToken, uint256 shares, address recipient);
/// @notice Emitted when `amount` debt tokens are minted to `recipient` using the account owned by `owner`.
///
/// @param owner The address of the account owner.
/// @param amount The amount of tokens that were minted.
/// @param recipient The recipient of the minted tokens.
event Mint(address indexed owner, uint256 amount, address recipient);
/// @notice Emitted when `sender` burns `amount` debt tokens to grant credit to `recipient`.
///
/// @param sender The address which is burning tokens.
/// @param amount The amount of tokens that were burned.
/// @param recipient The address that received credit for the burned tokens.
event Burn(address indexed sender, uint256 amount, address recipient);
/// @notice Emitted when `amount` of `underlyingToken` are repaid to grant credit to `recipient`.
///
/// @param sender The address which is repaying tokens.
/// @param underlyingToken The address of the underlying token that was used to repay debt.
/// @param amount The amount of the underlying token that was used to repay debt.
/// @param recipient The address that received credit for the repaid tokens.
event Repay(address indexed sender, address indexed underlyingToken, uint256 amount, address recipient);
/// @notice Emitted when `sender` liquidates `share` shares of `yieldToken`.
///
/// @param owner The address of the account owner liquidating shares.
/// @param yieldToken The address of the yield token.
/// @param underlyingToken The address of the underlying token.
/// @param shares The amount of the shares of `yieldToken` that were liquidated.
event Liquidate(address indexed owner, address indexed yieldToken, address indexed underlyingToken, uint256 shares);
/// @notice Emitted when `sender` burns `amount` debt tokens to grant credit to users who have deposited `yieldToken`.
///
/// @param sender The address which burned debt tokens.
/// @param yieldToken The address of the yield token.
/// @param amount The amount of debt tokens which were burned.
event Donate(address indexed sender, address indexed yieldToken, uint256 amount);
/// @notice Emitted when `yieldToken` is harvested.
///
/// @param yieldToken The address of the yield token that was harvested.
/// @param minimumAmountOut The maximum amount of loss that is acceptable when unwrapping the underlying tokens into yield tokens, measured in basis points.
/// @param totalHarvested The total amount of underlying tokens harvested.
event Harvest(address indexed yieldToken, uint256 minimumAmountOut, uint256 totalHarvested);
}
pragma solidity >=0.5.0;
/// @title IAlchemistV2State
/// @author Alchemix Finance
interface IAlchemistV2State {
/// @notice Defines underlying token parameters.
struct UnderlyingTokenParams {
// The number of decimals the token has. This value is cached once upon registering the token so it is important
// that the decimals of the token are immutable or the system will begin to have computation errors.
uint8 decimals;
// A coefficient used to normalize the token to a value comparable to the debt token. For example, if the
// underlying token is 8 decimals and the debt token is 18 decimals then the conversion factor will be
// 10^10. One unit of the underlying token will be comparably equal to one unit of the debt token.
uint256 conversionFactor;
// A flag to indicate if the token is enabled.
bool enabled;
}
/// @notice Defines yield token parameters.
struct YieldTokenParams {
// The number of decimals the token has. This value is cached once upon registering the token so it is important
// that the decimals of the token are immutable or the system will begin to have computation errors.
uint8 decimals;
// The associated underlying token that can be redeemed for the yield-token.
address underlyingToken;
// The adapter used by the system to wrap, unwrap, and lookup the conversion rate of this token into its
// underlying token.
address adapter;
// The maximum percentage loss that is acceptable before disabling certain actions.
uint256 maximumLoss;
// The maximum value of yield tokens that the system can hold, measured in units of the underlying token.
uint256 maximumExpectedValue;
// The percent of credit that will be unlocked per block. The representation of this value is a 18 decimal
// fixed point integer.
uint256 creditUnlockRate;
// The current balance of yield tokens which are held by users.
uint256 activeBalance;
// The current balance of yield tokens which are earmarked to be harvested by the system at a later time.
uint256 harvestableBalance;
// The total number of shares that have been minted for this token.
uint256 totalShares;
// The expected value of the tokens measured in underlying tokens. This value controls how much of the token
// can be harvested. When users deposit yield tokens, it increases the expected value by how much the tokens
// are exchangeable for in the underlying token. When users withdraw yield tokens, it decreases the expected
// value by how much the tokens are exchangeable for in the underlying token.
uint256 expectedValue;
// The current amount of credit which is will be distributed over time to depositors.
uint256 pendingCredit;
// The amount of the pending credit that has been distributed.
uint256 distributedCredit;
// The block number which the last credit distribution occurred.
uint256 lastDistributionBlock;
// The total accrued weight. This is used to calculate how much credit a user has been granted over time. The
// representation of this value is a 18 decimal fixed point integer.
uint256 accruedWeight;
// A flag to indicate if the token is enabled.
bool enabled;
}
/// @notice Gets the address of the admin.
///
/// @return admin The admin address.
function admin() external view returns (address admin);
/// @notice Gets the address of the pending administrator.
///
/// @return pendingAdmin The pending administrator address.
function pendingAdmin() external view returns (address pendingAdmin);
/// @notice Gets if an address is a sentinel.
///
/// @param sentinel The address to check.
///
/// @return isSentinel If the address is a sentinel.
function sentinels(address sentinel) external view returns (bool isSentinel);
/// @notice Gets if an address is a keeper.
///
/// @param keeper The address to check.
///
/// @return isKeeper If the address is a keeper
function keepers(address keeper) external view returns (bool isKeeper);
/// @notice Gets the address of the transmuter.
///
/// @return transmuter The transmuter address.
function transmuter() external view returns (address transmuter);
/// @notice Gets the minimum collateralization.
///
/// @notice Collateralization is determined by taking the total value of collateral that a user has deposited into their account and dividing it their debt.
///
/// @dev The value returned is a 18 decimal fixed point integer.
///
/// @return minimumCollateralization The minimum collateralization.
function minimumCollateralization() external view returns (uint256 minimumCollateralization);
/// @notice Gets the protocol fee.
///
/// @return protocolFee The protocol fee.
function protocolFee() external view returns (uint256 protocolFee);
/// @notice Gets the protocol fee receiver.
///
/// @return protocolFeeReceiver The protocol fee receiver.
function protocolFeeReceiver() external view returns (address protocolFeeReceiver);
/// @notice Gets the address of the whitelist contract.
///
/// @return whitelist The address of the whitelist contract.
function whitelist() external view returns (address whitelist);
/// @notice Gets the conversion rate of underlying tokens per share.
///
/// @param yieldToken The address of the yield token to get the conversion rate for.
///
/// @return rate The rate of underlying tokens per share.
function getUnderlyingTokensPerShare(address yieldToken) external view returns (uint256 rate);
/// @notice Gets the conversion rate of yield tokens per share.
///
/// @param yieldToken The address of the yield token to get the conversion rate for.
///
/// @return rate The rate of yield tokens per share.
function getYieldTokensPerShare(address yieldToken) external view returns (uint256 rate);
/// @notice Gets the supported underlying tokens.
///
/// @dev The order of the entries returned by this function is not guaranteed to be consistent between calls.
///
/// @return tokens The supported underlying tokens.
function getSupportedUnderlyingTokens() external view returns (address[] memory tokens);
/// @notice Gets the supported yield tokens.
///
/// @dev The order of the entries returned by this function is not guaranteed to be consistent between calls.
///
/// @return tokens The supported yield tokens.
function getSupportedYieldTokens() external view returns (address[] memory tokens);
/// @notice Gets if an underlying token is supported.
///
/// @param underlyingToken The address of the underlying token to check.
///
/// @return isSupported If the underlying token is supported.
function isSupportedUnderlyingToken(address underlyingToken) external view returns (bool isSupported);
/// @notice Gets if a yield token is supported.
///
/// @param yieldToken The address of the yield token to check.
///
/// @return isSupported If the yield token is supported.
function isSupportedYieldToken(address yieldToken) external view returns (bool isSupported);
/// @notice Gets information about the account owned by `owner`.
///
/// @param owner The address that owns the account.
///
/// @return debt The unrealized amount of debt that the account had incurred.
/// @return depositedTokens The yield tokens that the owner has deposited.
function accounts(address owner) external view returns (int256 debt, address[] memory depositedTokens);
/// @notice Gets information about a yield token position for the account owned by `owner`.
///
/// @param owner The address that owns the account.
/// @param yieldToken The address of the yield token to get the position of.
///
/// @return shares The amount of shares of that `owner` owns of the yield token.
/// @return lastAccruedWeight The last recorded accrued weight of the yield token.
function positions(address owner, address yieldToken)
external view
returns (
uint256 shares,
uint256 lastAccruedWeight
);
/// @notice Gets the amount of debt tokens `spender` is allowed to mint on behalf of `owner`.
///
/// @param owner The owner of the account.
/// @param spender The address which is allowed to mint on behalf of `owner`.
///
/// @return allowance The amount of debt tokens that `spender` can mint on behalf of `owner`.
function mintAllowance(address owner, address spender) external view returns (uint256 allowance);
/// @notice Gets the amount of shares of `yieldToken` that `spender` is allowed to withdraw on behalf of `owner`.
///
/// @param owner The owner of the account.
/// @param spender The address which is allowed to withdraw on behalf of `owner`.
/// @param yieldToken The address of the yield token.
///
/// @return allowance The amount of shares that `spender` can withdraw on behalf of `owner`.
function withdrawAllowance(address owner, address spender, address yieldToken) external view returns (uint256 allowance);
/// @notice Gets the parameters of an underlying token.
///
/// @param underlyingToken The address of the underlying token.
///
/// @return params The underlying token parameters.
function getUnderlyingTokenParameters(address underlyingToken)
external view
returns (UnderlyingTokenParams memory params);
/// @notice Get the parameters and state of a yield-token.
///
/// @param yieldToken The address of the yield token.
///
/// @return params The yield token parameters.
function getYieldTokenParameters(address yieldToken)
external view
returns (YieldTokenParams memory params);
/// @notice Gets current limit, maximum, and rate of the minting limiter.
///
/// @return currentLimit The current amount of debt tokens that can be minted.
/// @return rate The maximum possible amount of tokens that can be liquidated at a time.
/// @return maximum The highest possible maximum amount of debt tokens that can be minted at a time.
function getMintLimitInfo()
external view
returns (
uint256 currentLimit,
uint256 rate,
uint256 maximum
);
/// @notice Gets current limit, maximum, and rate of a repay limiter for `underlyingToken`.
///
/// @param underlyingToken The address of the underlying token.
///
/// @return currentLimit The current amount of underlying tokens that can be repaid.
/// @return rate The rate at which the the current limit increases back to its maximum in tokens per block.
/// @return maximum The maximum possible amount of tokens that can be repaid at a time.
function getRepayLimitInfo(address underlyingToken)
external view
returns (
uint256 currentLimit,
uint256 rate,
uint256 maximum
);
/// @notice Gets current limit, maximum, and rate of the liquidation limiter for `underlyingToken`.
///
/// @param underlyingToken The address of the underlying token.
///
/// @return currentLimit The current amount of underlying tokens that can be liquidated.
/// @return rate The rate at which the function increases back to its maximum limit (tokens / block).
/// @return maximum The highest possible maximum amount of debt tokens that can be liquidated at a time.
function getLiquidationLimitInfo(address underlyingToken)
external view
returns (
uint256 currentLimit,
uint256 rate,
uint256 maximum
);
}
pragma solidity >=0.5.0;
import "./IERC20Minimal.sol";
/// @title IERC20Burnable
/// @author Alchemix Finance
interface IERC20Burnable is IERC20Minimal {
/// @notice Burns `amount` tokens from the balance of `msg.sender`.
///
/// @param amount The amount of tokens to burn.
///
/// @return If burning the tokens was successful.
function burn(uint256 amount) external returns (bool);
/// @notice Burns `amount` tokens from `owner`'s balance.
///
/// @param owner The address to burn tokens from.
/// @param amount The amount of tokens to burn.
///
/// @return If burning the tokens was successful.
function burnFrom(address owner, uint256 amount) external returns (bool);
}
pragma solidity >=0.5.0;
import "./IERC20Minimal.sol";
/// @title IERC20Mintable
/// @author Alchemix Finance
interface IERC20Mintable is IERC20Minimal {
/// @notice Mints `amount` tokens to `recipient`.
///
/// @param recipient The address which will receive the minted tokens.
/// @param amount The amount of tokens to mint.
///
/// @return If minting the tokens was successful.
function mint(address recipient, uint256 amount) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @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 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) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
pragma solidity >=0.5.0;
/// @title IERC20Metadata
/// @author Alchemix Finance
interface IERC20Metadata {
/// @notice Gets the name of the token.
///
/// @return The name.
function name() external view returns (string memory);
/// @notice Gets the symbol of the token.
///
/// @return The symbol.
function symbol() external view returns (string memory);
/// @notice Gets the number of decimals that the token has.
///
/// @return The number of decimals.
function decimals() external view returns (uint8);
} | Increases the debt by `amount` for the account owned by `owner`. owner The address of the account owner. amount The amount to increase the debt by. | function _updateDebt(address owner, int256 amount) internal {
Account storage account = _accounts[owner];
account.debt += amount;
}
| 504,835 |
pragma solidity >=0.7.0 <0.9.0;
pragma experimental ABIEncoderV2;
//SPDX-License-Identifier: MIT
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {
ISuperfluid,
ISuperToken,
SuperAppBase,
SuperAppDefinitions
} from "@superfluid-finance/ethereum-contracts/contracts/apps/SuperAppBase.sol";
import {
IInstantDistributionAgreementV1
} from "@superfluid-finance/ethereum-contracts/contracts/interfaces/agreements/IInstantDistributionAgreementV1.sol";
import {
IConstantFlowAgreementV1
} from "@superfluid-finance/ethereum-contracts/contracts/interfaces/agreements/IConstantFlowAgreementV1.sol";
import {
ISETHCustom
} from "@superfluid-finance/ethereum-contracts/contracts/tokens/SETH.sol";
contract NEA is Ownable, ERC20, SuperAppBase {
uint32 public constant INDEX_ID = 0;
ISuperToken private _ethx;
ISuperfluid private _host;
IInstantDistributionAgreementV1 private _ida;
IConstantFlowAgreementV1 private _cfa;
uint64 _share_price;
uint256 _supply;
address _nea;
address _platform;
constructor(
address nea,
string memory name,
string memory symbol,
uint256 supply,
uint64 share_price,
address platform,
ISuperToken ethx,
ISuperfluid host,
IInstantDistributionAgreementV1 ida,
IConstantFlowAgreementV1 cfa
) public ERC20(name, symbol) {
transferOwnership(platform);
_platform = platform;
_nea = nea;
_supply = supply;
_share_price = share_price;
_ethx = ethx;
_host = host;
_ida = ida;
_cfa = cfa;
// create pool
_host.callAgreement(
_ida,
abi.encodeWithSelector(
_ida.createIndex.selector,
_ethx,
INDEX_ID,
new bytes(0)
),
new bytes(0)
);
_setupDecimals(0); // no decimals
uint total = 100;
uint platform_share = 90;
_mint(_nea, _supply * (platform_share/total));
_mint(_platform, _supply * ((total - platform_share)/total));
}
/**
@dev issue shares
@param beneficiary investor address
@param amount amount invested
*/
function _issue(address beneficiary, uint256 amount) internal {
uint256 currentAmount = balanceOf(beneficiary);
ERC20._mint(beneficiary, amount);
//update # shares
_host.callAgreement(
_ida,
abi.encodeWithSelector(
_ida.updateSubscription.selector,
_ethx,
INDEX_ID,
beneficiary,
uint128(currentAmount) + uint128(amount),
new bytes(0)
),
new bytes(0)
);
}
/**
@dev investor sends ETH and it gets streamed to the artist; he receives shares in return
*/
function supportNEA() external payable {
//upgrade ETH to ETHx [TODO]
ISETHCustom(address(_ethx)).upgradeByETH{value: msg.value}();
//check if flow exists
(,int96 outFlowRate,,) = _cfa.getFlow(_ethx, address(this), _nea);
//stream over 30 days
if (outFlowRate == 0) {
_host.callAgreement(
_cfa,
abi.encodeWithSelector(
_cfa.createFlow.selector,
_ethx,
_nea,
int96(int256(msg.value/2592000)),
new bytes(0)
),
"0x"
);
}
else if (outFlowRate > 0) {
_host.callAgreement(
_cfa,
abi.encodeWithSelector(
_cfa.updateFlow.selector,
_ethx,
_nea,
int96(int256(address(this).balance/2592000)),
new bytes(0)
),
"0x"
);
}
_issue(msg.sender, msg.value);
}
/**
@dev distribute ETHx tokens to all shareholders in a single transaction
@param cashAmount amount to distribute
*/
function _distribute(uint256 cashAmount) internal {
//divides amount to be distributed by # of outstanding shares (& removes excess - do NOT test with low # of wei!)
(uint256 actualCashAmount,) = _ida.calculateDistribution(
_ethx,
address(this), INDEX_ID,
cashAmount
);
_host.callAgreement(
_ida,
abi.encodeWithSelector(
_ida.distribute.selector,
_ethx,
INDEX_ID,
actualCashAmount,
new bytes(0) // placeholder ctx
),
new bytes(0) // user data
);
}
fallback() external payable {
//upgrade ETH to ETHx
ISETHCustom(address(_ethx)).upgradeByETH{value: msg.value}();
_distribute(msg.value);
}
}
| /divides amount to be distributed by of outstanding shares (& removes excess - do NOT test with low of wei!) | function _distribute(uint256 cashAmount) internal {
(uint256 actualCashAmount,) = _ida.calculateDistribution(
_ethx,
address(this), INDEX_ID,
cashAmount
);
_host.callAgreement(
_ida,
abi.encodeWithSelector(
_ida.distribute.selector,
_ethx,
INDEX_ID,
actualCashAmount,
),
);
}
| 7,307,396 |
./full_match/137/0x839ddcCea2cA70A66d08397E0047D2C272465Cd4/sources/mrat.sol | reward claim protocol | function activateContract() public onlyOwner {
disableEasyRewardFrom = block.timestamp + 1 weeks;
rewardCycleBlock = 7 days;
easyRewardCycleBlock = 1 days;
winningDoubleRewardPercentage = 5;
disruptiveTransferEnabledFrom = block.timestamp;
liquidityAdded = true;
setSwapAndLiquifyEnabled(true);
burnRate = 1;
moonMissionStarted = true;
}
| 3,751,429 |
./full_match/42161/0xF7246C656D8AFf1e7da5547D8A7C0A88Fcb76831/sources/interfaces/libs/BalancerUtils.sol | Return a completed fund management struct, not stored here due to library restrictions. return funds Struct is always the same with receiver address the same as sender./ | function funds() private view returns (IBalancerVault.FundManagement memory) {
return IBalancerVault.FundManagement(
address(this),
false,
payable(address(this)),
false
);
}
| 16,299,626 |
pragma solidity ^0.4.16;
/*
* Abstract Token Smart Contract. Copyright ยฉ 2017 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.4.20;
/*
* EIP-20 Standard Token Smart Contract Interface.
* Copyright ยฉ 2016โ2018 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.4.20;
/**
* ERC-20 standard token interface, as defined
* <a href="https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md">here</a>.
*/
contract Token {
/**
* Get total number of tokens in circulation.
*
* @return total number of tokens in circulation
*/
function totalSupply () public view returns (uint256 supply);
/**
* Get number of tokens currently belonging to given owner.
*
* @param _owner address to get number of tokens currently belonging to the
* owner of
* @return number of tokens currently belonging to the owner of given address
*/
function balanceOf (address _owner) public view returns (uint256 balance);
/**
* Transfer given number of tokens from message sender to given recipient.
*
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
*/
function transfer (address _to, uint256 _value)
public returns (bool success);
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
* recipient
* @return true if tokens were transferred successfully, false otherwise
*/
function transferFrom (address _from, address _to, uint256 _value)
public returns (bool success);
/**
* Allow given spender to transfer given number of tokens from message sender.
*
* @param _spender address to allow the owner of to transfer tokens from
* message sender
* @param _value number of tokens to allow to transfer
* @return true if token transfer was successfully approved, false otherwise
*/
function approve (address _spender, uint256 _value)
public returns (bool success);
/**
* Tell how many tokens given spender is currently allowed to transfer from
* given owner.
*
* @param _owner address to get number of tokens allowed to be transferred
* from the owner of
* @param _spender address to get number of tokens allowed to be transferred
* by the owner of
* @return number of tokens given spender is currently allowed to transfer
* from given owner
*/
function allowance (address _owner, address _spender)
public view returns (uint256 remaining);
/**
* Logged when tokens were transferred from one owner to another.
*
* @param _from address of the owner, tokens were transferred from
* @param _to address of the owner, tokens were transferred to
* @param _value number of tokens transferred
*/
event Transfer (address indexed _from, address indexed _to, uint256 _value);
/**
* Logged when owner approved his tokens to be transferred by some spender.
*
* @param _owner owner who approved his tokens to be transferred
* @param _spender spender who were allowed to transfer the tokens belonging
* to the owner
* @param _value number of tokens belonging to the owner, approved to be
* transferred by the spender
*/
event Approval (
address indexed _owner, address indexed _spender, uint256 _value);
}
/*
* Safe Math Smart Contract. Copyright ยฉ 2016โ2017 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.4.20;
/**
* Provides methods to safely add, subtract and multiply uint256 numbers.
*/
contract SafeMath {
uint256 constant private MAX_UINT256 =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Add two uint256 values, throw in case of overflow.
*
* @param x first value to add
* @param y second value to add
* @return x + y
*/
function safeAdd (uint256 x, uint256 y)
pure internal
returns (uint256 z) {
assert (x <= MAX_UINT256 - y);
return x + y;
}
/**
* Subtract one uint256 value from another, throw in case of underflow.
*
* @param x value to subtract from
* @param y value to subtract
* @return x - y
*/
function safeSub (uint256 x, uint256 y)
pure internal
returns (uint256 z) {
assert (x >= y);
return x - y;
}
/**
* Multiply two uint256 values, throw in case of overflow.
*
* @param x first value to multiply
* @param y second value to multiply
* @return x * y
*/
function safeMul (uint256 x, uint256 y)
pure internal
returns (uint256 z) {
if (y == 0) return 0; // Prevent division by zero at the next line
assert (x <= MAX_UINT256 / y);
return x * y;
}
}
/**
* Abstract Token Smart Contract that could be used as a base contract for
* ERC-20 token contracts.
*/
contract AbstractToken is Token, SafeMath {
/**
* Create new Abstract Token contract.
*/
function AbstractToken () public {
// Do nothing
}
/**
* Get number of tokens currently belonging to given owner.
*
* @param _owner address to get number of tokens currently belonging to the
* owner of
* @return number of tokens currently belonging to the owner of given address
*/
function balanceOf (address _owner) public view returns (uint256 balance) {
return accounts [_owner];
}
/**
* Transfer given number of tokens from message sender to given recipient.
*
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
*/
function transfer (address _to, uint256 _value)
public returns (bool success) {
uint256 fromBalance = accounts [msg.sender];
if (fromBalance < _value) return false;
if (_value > 0 && msg.sender != _to) {
accounts [msg.sender] = safeSub (fromBalance, _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
Transfer (msg.sender, _to, _value);
return true;
}
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
* recipient
* @return true if tokens were transferred successfully, false otherwise
*/
function transferFrom (address _from, address _to, uint256 _value)
public returns (bool success) {
uint256 spenderAllowance = allowances [_from][msg.sender];
if (spenderAllowance < _value) return false;
uint256 fromBalance = accounts [_from];
if (fromBalance < _value) return false;
allowances [_from][msg.sender] =
safeSub (spenderAllowance, _value);
if (_value > 0 && _from != _to) {
accounts [_from] = safeSub (fromBalance, _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
Transfer (_from, _to, _value);
return true;
}
/**
* Allow given spender to transfer given number of tokens from message sender.
*
* @param _spender address to allow the owner of to transfer tokens from
* message sender
* @param _value number of tokens to allow to transfer
* @return true if token transfer was successfully approved, false otherwise
*/
function approve (address _spender, uint256 _value)
public returns (bool success) {
allowances [msg.sender][_spender] = _value;
Approval (msg.sender, _spender, _value);
return true;
}
/**
* Tell how many tokens given spender is currently allowed to transfer from
* given owner.
*
* @param _owner address to get number of tokens allowed to be transferred
* from the owner of
* @param _spender address to get number of tokens allowed to be transferred
* by the owner of
* @return number of tokens given spender is currently allowed to transfer
* from given owner
*/
function allowance (address _owner, address _spender)
public view returns (uint256 remaining) {
return allowances [_owner][_spender];
}
/**
* Mapping from addresses of token holders to the numbers of tokens belonging
* to these token holders.
*/
mapping (address => uint256) internal accounts;
/**
* Mapping from addresses of token holders to the mapping of addresses of
* spenders to the allowances set by these token holders to these spenders.
*/
mapping (address => mapping (address => uint256)) internal allowances;
}
/**
* BAILSMAN token smart contract.
*/
contract BAILSToken is AbstractToken {
/**
* Address of the owner of this smart contract.
*/
address private owner;
/**
* Total number of tokens in circulation.
*/
uint256 tokenCount;
/**
* True if tokens transfers are currently frozen, false otherwise.
*/
bool frozen = false;
/**
* Create new BAILSMAN token smart contract, with given number of tokens issued
* and given to msg.sender, and make msg.sender the owner of this smart
* contract.
*
* @param _tokenCount number of tokens to issue and give to msg.sender
*/
function BAILSToken (uint256 _tokenCount) public {
owner = msg.sender;
tokenCount = _tokenCount;
accounts [msg.sender] = _tokenCount;
}
/**
* Get total number of tokens in circulation.
*
* @return total number of tokens in circulation
*/
function totalSupply () public view returns (uint256 supply) {
return tokenCount;
}
/**
* Get name of this token.
*
* @return name of this token
*/
function name () public pure returns (string result) {
return "BAILS";
}
/**
* Get symbol of this token.
*
* @return symbol of this token
*/
function symbol () public pure returns (string result) {
return "BAILS";
}
/**
* Get number of decimals for this token.
*
* @return number of decimals for this token
*/
function decimals () public pure returns (uint8 result) {
return 8;
}
/**
* Transfer given number of tokens from message sender to given recipient.
*
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
*/
function transfer (address _to, uint256 _value)
public returns (bool success) {
if (frozen) return false;
else return AbstractToken.transfer (_to, _value);
}
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
* recipient
* @return true if tokens were transferred successfully, false otherwise
*/
function transferFrom (address _from, address _to, uint256 _value)
public returns (bool success) {
if (frozen) return false;
else return AbstractToken.transferFrom (_from, _to, _value);
}
/**
* Change how many tokens given spender is allowed to transfer from message
* spender. In order to prevent double spending of allowance, this method
* receives assumed current allowance value as an argument. If actual
* allowance differs from an assumed one, this method just returns false.
*
* @param _spender address to allow the owner of to transfer tokens from
* message sender
* @param _currentValue assumed number of tokens currently allowed to be
* transferred
* @param _newValue number of tokens to allow to transfer
* @return true if token transfer was successfully approved, false otherwise
*/
function approve (address _spender, uint256 _currentValue, uint256 _newValue)
public returns (bool success) {
if (allowance (msg.sender, _spender) == _currentValue)
return approve (_spender, _newValue);
else return false;
}
/**
* Burn given number of tokens belonging to message sender.
*
* @param _value number of tokens to burn
* @return true on success, false on error
*/
function burnTokens (uint256 _value) public returns (bool success) {
if (_value > accounts [msg.sender]) return false;
else if (_value > 0) {
accounts [msg.sender] = safeSub (accounts [msg.sender], _value);
tokenCount = safeSub (tokenCount, _value);
Transfer (msg.sender, address (0), _value);
return true;
} else return true;
}
/**
* Set new owner for the smart contract.
* May only be called by smart contract owner.
*
* @param _newOwner address of new owner of the smart contract
*/
function setOwner (address _newOwner) public {
require (msg.sender == owner);
owner = _newOwner;
}
/**
* Freeze token transfers.
* May only be called by smart contract owner.
*/
function freezeTransfers () public {
require (msg.sender == owner);
if (!frozen) {
frozen = true;
Freeze ();
}
}
/**
* Unfreeze token transfers.
* May only be called by smart contract owner.
*/
function unfreezeTransfers () public {
require (msg.sender == owner);
if (frozen) {
frozen = false;
Unfreeze ();
}
}
/**
* Logged when token transfers were frozen.
*/
event Freeze ();
/**
* Logged when token transfers were unfrozen.
*/
event Unfreeze ();
} | Change how many tokens given spender is allowed to transfer from message spender. In order to prevent double spending of allowance, this method receives assumed current allowance value as an argument. If actual allowance differs from an assumed one, this method just returns false. _spender address to allow the owner of to transfer tokens from message sender _currentValue assumed number of tokens currently allowed to be transferred _newValue number of tokens to allow to transfer return true if token transfer was successfully approved, false otherwise/ | function approve (address _spender, uint256 _currentValue, uint256 _newValue)
public returns (bool success) {
if (allowance (msg.sender, _spender) == _currentValue)
return approve (_spender, _newValue);
else return false;
}
| 715 |
/**
*Submitted for verification at Etherscan.io on 2022-04-08
*/
//SPDX-License-Identifier: MIT
/*
โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ
โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ
โ โ โ โ โ โโโโโโโ โ โ โ โโโโโโโโ โ โ โ โ โ
โ โ โ โ โ โ โโโโโโโโโโ โ โ โ โโโโโโโโโ โ โ โ โ โ
โ โ โ โ โโโโโโโโโโโโ โ โ โ โ โโโโโโโโโโโ โ โ โ โ โ โ โ
โ โ โ โ โ โ โโโโโโโโโโโโ โ โโโโโโโโโโโโ โ โ โ โ โ โ โ โ
โ โ โ โ โ โ โโโโโโโโโโโโ โโโโโโโโโโโโ โ โ โ โ โ โ โ โ
โ โ โ โ โโ โโโโโโโโโโโโ โโโโโโโโโโโโ โ โ โ โ
โ โ โ โโโ โโโโโโโโโโโโ โโโโโโโโโโโโ โโ โ โ โ โ โ โ โ
โ โ โ โ โ โ โ โโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โโโ โ โ โ โ โ โ
โ โ โ โ โ โ โโโโโโ โโโโโโโโโโโโโโโโโโโโ โโโโโ โ โ โ โ โ โ
โ โ โ โ โ โ โ โโโโโโโ โโโโโโโโโโโโโโโโ โโโโโโโ โ โ โ โ โ
โ โ โ โ โโโโโโโ โโโโโโโโโโโโ โโโโโโโโโโ โ โ โ โ
โ โ โ โ โ โ โโโโโโโ โโโโโโโโ โโโโโโโโโโโโ โ โ โ โ
โ โ โ โ โ โ โโโโโโโ โโโโ โโโโโโโโโโโโโโ โ โ โ โ โ โ
โ โ โ โ โ โ โ โโโโโโโ โ โ โ โโโโโโโโโ โโโโโโ โ โ โ โ โ
โ โ โ โ โ โ โ โโโโโโโ โ โ โโโโโโโโโ โโโโโโ โ โ โ โ โ โ
โ โ โ โ โ โโโโโโโ โ โ โ โโโโโโโโ โโโโโโ โ โ โ โ โ โ โ
โ โ โ โ โ โโโโโโโโ โ โ โ โโโโโโโโโ โโโโโโ โ โ โ โ โ
โ โ โ โ โ โ โ โ โ โโโโโโโ โ โ โ โ โโโโโโโโโ โโโโโโ โ โ โ โ โ
โ โ โ โ โ โ โ โ โโโโโโโโ โ โ โ โโโโโโโโ โโโโโโ โ โ โ โ โ
โ โ โ โ โ โโโโโโโโ โ โ โ โโโโโโโโโ โโโโโโ โ โ โ โ
โ โ โ โโโโโโโโ โ โ โ โโโโโโโโโ โโโโโโ โ โ โ โ โ โ
โ โ โ โ โ โ โโโโโโ โ โ โโโโโโโโโ โโโโโโ โ โ โ โ
โ โ โ โ โ โ โ โ โโโโ โ โ โโโโโโโโโ โโโโ โ โ โ โ โ โ โ
โ โ โ โ โ โโ โโโโโโโโโ โโ โ โ โ โ โ โ
โ โ โ โ โ โ โ โ โ โ โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Written, deployed & Migrated by Krakovia (@karola96)
*/
// o/
pragma solidity 0.8.13;
//interfaces
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB) external returns (address pair);
}
interface IUniswapV2Router02 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IERC20Metadata is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// contracts
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this;
return msg.data;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function getTime() public view returns (uint256) {
return block.timestamp;
}
}
// main contract
contract moonrock is Context, IERC20, Ownable {
//custom
IUniswapV2Router02 public uniswapV2Router;
//string
string private _name = "MoonRock";
string private _symbol = "ROCK";
//bool
bool public moveEthToWallets = true;
bool public TakeEthForFees = true;
bool public swapAndLiquifyEnabled = true;
bool public blockMultiBuys = true;
bool public marketActive = false;
bool private isInternalTransaction = false;
bool public vestingActive = true;
//address
address public uniswapV2Pair;
address public _MarketingWalletAddress = 0x9151D7B75601E8407049F3642365629e24d8f13d;
address public _DevelopmentWalletAddress = 0xc040621C8853d1E5fF74f891F976168d39Ba29aA;
address public _InvfundWalletAddress = 0x03c754661A0B30E01768D612328d95938716Cd31;
address[] private _excluded;
//uint
uint public buyReflectionFee = 4;
uint public sellReflectionFee = 4;
uint public buyMarketingFee = 2;
uint public sellMarketingFee = 2;
uint public buyDevelopmentFee = 2;
uint public sellDevelopmentFee = 2;
uint public buyInvfundFee = 2;
uint public sellInvfundFee = 2;
uint public buyFee = buyReflectionFee + buyMarketingFee + buyDevelopmentFee + buyInvfundFee;
uint public sellFee = sellReflectionFee + sellMarketingFee + sellDevelopmentFee + sellInvfundFee;
uint public buySecondsLimit = 5;
uint public minimumTokensBeforeSwap;
uint public tokensToSwap;
uint public intervalSecondsForSwap = 60;
uint public minimumWeiForTokenomics = 1 * 10**16; // 0.01 ETH
uint private startTimeForSwap;
uint private MarketActiveAt;
uint private constant MAX = ~uint256(0);
uint8 private _decimals = 9;
uint private _tTotal = 1_000_000_000 * 10 ** _decimals;
uint private _rTotal = (MAX - (MAX % _tTotal));
uint private _tFeeTotal;
uint private _ReflectionFee;
uint private _MarketingFee;
uint private _DevelopmentFee;
uint private _InvfundFee;
uint private _OldReflectionFee;
uint private _OldMarketingFee;
uint private _OldDevelopmentFee;
uint private _OldInvfundFee;
//struct
struct userData {
uint lastBuyTime;
}
//mapping
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) public premarketUser;
mapping (address => bool) public VestedUser;
mapping (address => bool) public excludedFromFees;
mapping (address => bool) private _isExcluded;
mapping (address => bool) public automatedMarketMakerPairs;
mapping (address => userData) public userLastTradeData;
//event
event MarketingCollected(uint256 amount);
event DevelopmentCollected(uint256 amount);
event InvestmentFundCollected(uint256 amount);
event ExcludedFromFees(address indexed user, bool state);
event SwapSystemChanged(bool status, uint256 intervalSecondsToWait, uint256 minimumToSwap, uint256 tokensToSwap);
event MoveEthToWallets(bool state);
// constructor
constructor() {
// set gvars
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
minimumTokensBeforeSwap = 50_000 * 10 ** _decimals ;
tokensToSwap = minimumTokensBeforeSwap;
excludedFromFees[address(this)] = true;
excludedFromFees[owner()] = true;
premarketUser[owner()] = true;
excludedFromFees[_MarketingWalletAddress] = true;
//spawn pair
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// mappings
automatedMarketMakerPairs[uniswapV2Pair] = true;
_rOwned[owner()] = _rTotal;
emit Transfer(address(0), owner(), _tTotal);
}
// accept eth for autoswap
receive() external payable {
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount / currentRate;
}
function setFees() private {
buyFee = buyReflectionFee + buyMarketingFee + buyDevelopmentFee + buyInvfundFee;
sellFee = sellReflectionFee + sellMarketingFee + sellDevelopmentFee + sellInvfundFee;
}
function excludeFromReward(address account) external onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already included");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function setMoveEthToWallets(bool state) external onlyOwner {
moveEthToWallets = state;
emit MoveEthToWallets(state);
}
function excludeFromFee(address account) external onlyOwner {
excludedFromFees[account] = true;
emit ExcludedFromFees(account,true);
}
function includeInFee(address account) external onlyOwner {
excludedFromFees[account] = false;
emit ExcludedFromFees(account,false);
}
function setReflectionFee(uint buy, uint sell) external onlyOwner() {
buyReflectionFee = buy;
sellReflectionFee = sell;
setFees();
require(buyFee + sellFee <= 25, "Fees to high");
}
function setMarketingFee(uint buy, uint sell) external onlyOwner() {
buyMarketingFee = buy;
sellMarketingFee = sell;
setFees();
require(buyFee + sellFee <= 25, "Fees to high");
}
function setDevelopmentFee(uint buy, uint sell) external onlyOwner() {
buyDevelopmentFee = buy;
sellDevelopmentFee = sell;
setFees();
require(buyFee + sellFee <= 25, "Fees to high");
}
function setInvfundFee(uint buy, uint sell) external onlyOwner() {
buyInvfundFee = buy;
sellInvfundFee = sell;
setFees();
require(buyFee + sellFee <= 25, "Fees to high");
}
function VestingMultipleAccounts(address[] calldata accounts, bool _state) external onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
VestedUser[accounts[i]] = _state;
}
}
function setMinimumWeiForTokenomics(uint _value) external onlyOwner {
minimumWeiForTokenomics = _value;
}
function disableVesting() external onlyOwner {
// there is no coming back after disabling vesting.
vestingActive = false;
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal - rFee;
_tFeeTotal = _tFeeTotal + tFee;
}
function _getValues(uint256 tAmount) private view returns (uint256 rAmount, uint256 rTransferAmount, uint256 rFee,
uint256 tTransferAmount, uint256 tFee, uint256 tMarketing,
uint256 tDevelopment, uint256 tInvfund) {
(tTransferAmount, tFee, tMarketing, tDevelopment, tInvfund) = _getTValues(tAmount);
(rAmount, rTransferAmount, rFee) = _getRValues(tAmount, tFee, tMarketing, tDevelopment, tInvfund, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tMarketing, tDevelopment, tInvfund);
}
function _getTValues(uint256 tAmount) private view returns (uint256 tTransferAmount, uint256 tFee, uint256 tMarketing, uint256 tDevelopment, uint256 tInvfund) {
tFee = calculateReflectionFee(tAmount);
tMarketing = calculateMarketingFee(tAmount);
tDevelopment = calculateDevelopmentFee(tAmount);
tInvfund = calculateInvfundFee(tAmount);
tTransferAmount = tAmount - tFee - tMarketing - tDevelopment - tInvfund;
return (tTransferAmount, tFee, tMarketing, tDevelopment, tInvfund);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tMarketing, uint256 tDevelopment, uint256 tInvfund, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount * currentRate;
uint256 rFee = tFee * currentRate;
uint256 rMarketing = tMarketing * currentRate;
uint256 rDevelopment = tDevelopment * currentRate;
uint256 rInvfund = tInvfund * currentRate;
uint256 rTransferAmount = rAmount - rFee - rMarketing - rDevelopment - rInvfund;
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply / tSupply;
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply - _rOwned[_excluded[i]];
tSupply = tSupply - _tOwned[_excluded[i]];
}
if (rSupply < _rTotal / _tTotal) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeMarketing(uint256 tMarketing) private {
uint256 currentRate = _getRate();
uint256 rMarketing = tMarketing * currentRate;
_rOwned[address(this)] = _rOwned[address(this)] + rMarketing;
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)] + tMarketing;
}
function _takeDevelopment(uint256 tDevelopment) private {
uint256 currentRate = _getRate();
uint256 rDevelopment = tDevelopment * currentRate;
_rOwned[address(this)] = _rOwned[address(this)] + rDevelopment;
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)] + tDevelopment;
}
function _takeInvfund(uint256 tInvfund) private {
uint256 currentRate = _getRate();
uint256 rInvfund = tInvfund * currentRate;
_rOwned[address(this)] = _rOwned[address(this)] + rInvfund;
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)] + tInvfund;
}
function calculateReflectionFee(uint256 _amount) private view returns (uint256) {
return _amount * _ReflectionFee / 10**2;
}
function calculateMarketingFee(uint256 _amount) private view returns (uint256) {
return _amount * _MarketingFee / 10**2;
}
function calculateDevelopmentFee(uint256 _amount) private view returns (uint256) {
return _amount * _DevelopmentFee / 10**2;
}
function calculateInvfundFee(uint256 _amount) private view returns (uint256) {
return _amount * _InvfundFee / 10**2;
}
function setOldFees() private {
_OldReflectionFee = _ReflectionFee;
_OldMarketingFee = _MarketingFee;
_OldDevelopmentFee = _DevelopmentFee;
_OldInvfundFee = _InvfundFee;
}
function shutdownFees() private {
_ReflectionFee = 0;
_MarketingFee = 0;
_DevelopmentFee = 0;
_InvfundFee = 0;
}
function setFeesByType(uint tradeType) private {
//buy
if(tradeType == 1) {
_ReflectionFee = buyReflectionFee;
_MarketingFee = buyMarketingFee;
_DevelopmentFee = buyDevelopmentFee;
_InvfundFee = buyInvfundFee;
}
//sell
else if(tradeType == 2) {
_ReflectionFee = sellReflectionFee;
_MarketingFee = sellMarketingFee;
_DevelopmentFee = sellDevelopmentFee;
_InvfundFee = sellInvfundFee;
}
}
function restoreFees() private {
_ReflectionFee = _OldReflectionFee;
_MarketingFee = _OldMarketingFee;
_DevelopmentFee = _OldDevelopmentFee;
_InvfundFee = _OldInvfundFee;
}
modifier CheckDisableFees(bool isEnabled, uint tradeType, address from) {
if(!isEnabled) {
setOldFees();
shutdownFees();
_;
restoreFees();
} else {
// vesting, used to lock vested users, no tranfer, no sell, buy allowed.
// can be disabled and cannot be enabled again
if(vestingActive) {
if(tradeType == 0 || tradeType == 2) {
require(!VestedUser[from],"your account is locked.");
}
}
//buy & sell
if(tradeType == 1 || tradeType == 2) {
setOldFees();
setFeesByType(tradeType);
_;
restoreFees();
}
// no wallet to wallet tax
else {
setOldFees();
shutdownFees();
_;
restoreFees();
}
}
}
function isExcludedFromFee(address account) public view returns(bool) {
return excludedFromFees[account];
}
function _approve(address owner, address spender, uint256 amount) private {
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);
}
modifier FastTx() {
isInternalTransaction = true;
_;
isInternalTransaction = false;
}
function sendToWallet(uint amount) private {
uint256 marketing_part = amount * sellMarketingFee / 100;
uint256 development_part = amount * sellDevelopmentFee / 100;
uint256 invfund_part = amount * sellInvfundFee / 100;
(bool success, ) = payable(_MarketingWalletAddress).call{value: marketing_part}("");
if(success) {
emit MarketingCollected(marketing_part);
}
(bool success1, ) = payable(_DevelopmentWalletAddress).call{value: development_part}("");
if(success1) {
emit DevelopmentCollected(development_part);
}
(bool success2, ) = payable(_InvfundWalletAddress).call{value: invfund_part}("");
if(success2) {
emit InvestmentFundCollected(invfund_part);
}
}
function swapAndLiquify(uint256 _tokensToSwap) private FastTx {
swapTokensForEth(_tokensToSwap);
}
// utility functions
function transferForeignToken(address _token, address _to, uint _value) external onlyOwner returns(bool _sent){
if(_value == 0) {
_value = IERC20(_token).balanceOf(address(this));
}
_sent = IERC20(_token).transfer(_to, _value);
}
function Sweep() external onlyOwner {
uint balance = address(this).balance;
payable(owner()).transfer(balance);
}
//switch functions
function ActivateMarket(bool _state) external onlyOwner {
marketActive = _state;
if(_state) {
MarketActiveAt = block.timestamp;
}
}
//set functions
function setMarketingAddress(address _value) external onlyOwner {
_MarketingWalletAddress = _value;
}
function setDevelopmentAddress(address _value) external onlyOwner {
_DevelopmentWalletAddress = _value;
}
function setInvfundAddress(address _value) external onlyOwner {
_InvfundWalletAddress = _value;
}
function setSwapAndLiquify(bool _state, uint _minimumTokensBeforeSwap, uint _intervalSecondsForSwap, uint _tokenToSwap) external onlyOwner {
swapAndLiquifyEnabled = _state;
intervalSecondsForSwap = _intervalSecondsForSwap;
minimumTokensBeforeSwap = _minimumTokensBeforeSwap*10**decimals();
tokensToSwap = _tokenToSwap*10**decimals();
require(tokensToSwap <= _tTotal / 500,"tokensToSwap should be max 0.2% of total supply.");
emit SwapSystemChanged(_state,_intervalSecondsForSwap,_minimumTokensBeforeSwap,_tokenToSwap);
}
// mappings functions
function editPowerUser(address _target, bool _status) external onlyOwner {
premarketUser[_target] = _status;
excludedFromFees[_target] = _status;
}
function editPremarketUser(address _target, bool _status) external onlyOwner {
premarketUser[_target] = _status;
}
function editExcludedFromFees(address _target, bool _status) external onlyOwner {
excludedFromFees[_target] = _status;
}
function editBatchExcludedFromFees(address[] memory _address, bool _status) external onlyOwner {
for(uint i=0; i< _address.length; i++){
address adr = _address[i];
excludedFromFees[adr] = _status;
}
}
function editAutomatedMarketMakerPairs(address _target, bool _status) external onlyOwner {
automatedMarketMakerPairs[_target] = _status;
}
// operational functions
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function _transfer(address from, address to, uint256 amount) private {
uint trade_type = 0;
bool takeFee = true;
bool overMinimumTokenBalance = balanceOf(address(this)) >= minimumTokensBeforeSwap;
require(from != address(0), "ERC20: transfer from the zero address");
// market status flag
if(!marketActive) {
require(premarketUser[from],"cannot trade before the market opening");
}
// normal transaction
if(!isInternalTransaction) {
// tx limits
//buy
if(automatedMarketMakerPairs[from]) {
trade_type = 1;
}
//sell
else if(automatedMarketMakerPairs[to]) {
trade_type = 2;
// liquidity generator for tokenomics
if (swapAndLiquifyEnabled &&
balanceOf(uniswapV2Pair) > 0 &&
overMinimumTokenBalance &&
startTimeForSwap + intervalSecondsForSwap <= block.timestamp
) {
startTimeForSwap = block.timestamp;
swapAndLiquify(tokensToSwap);
}
}
// send converted eth from fees to respective wallets
if(moveEthToWallets) {
uint256 remaningEth = address(this).balance;
if(remaningEth > minimumWeiForTokenomics) {
sendToWallet(remaningEth);
}
}
}
//if any account belongs to excludedFromFees account then remove the fee
if(excludedFromFees[from] || excludedFromFees[to]){
takeFee = false;
}
// transfer tokens
_tokenTransfer(from,to,amount,takeFee,trade_type);
}
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee, uint tradeType) private CheckDisableFees(takeFee,tradeType,sender) {
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing, uint256 tDevelopment, uint256 tInvFund) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender] - rAmount;
_rOwned[recipient] = _rOwned[recipient] + rTransferAmount;
_takeMarketing(tMarketing);
_takeDevelopment(tDevelopment);
_takeInvfund(tInvFund);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing, uint256 tDevelopment, uint256 tInvFund) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender] - rAmount;
_tOwned[recipient] = _tOwned[recipient] + tTransferAmount;
_rOwned[recipient] = _rOwned[recipient] + rTransferAmount;
_takeMarketing(tMarketing);
_takeDevelopment(tDevelopment);
_takeInvfund(tInvFund);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing, uint256 tDevelopment, uint256 tInvFund) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender] - tAmount;
_rOwned[sender] = _rOwned[sender] - rAmount;
_rOwned[recipient] = _rOwned[recipient] + rTransferAmount;
_takeMarketing(tMarketing);
_takeDevelopment(tDevelopment);
_takeInvfund(tInvFund);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing, uint256 tDevelopment, uint256 tInvFund) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender] - tAmount;
_rOwned[sender] = _rOwned[sender] - rAmount;
_tOwned[recipient] = _tOwned[recipient] + tTransferAmount;
_rOwned[recipient] = _rOwned[recipient] + rTransferAmount;
_takeMarketing(tMarketing);
_takeDevelopment(tDevelopment);
_takeInvfund(tInvFund);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function KKMigration(address[] memory _address, uint256[] memory _amount) external onlyOwner {
require(_amount.length == _amount.length,"wrong address:amount rows");
for(uint i=0; i< _amount.length; i++){
address adr = _address[i];
uint amnt = _amount[i] *10**decimals();
(uint256 rAmount, uint256 rTransferAmount,,,,,,) = _getValues(amnt);
_rOwned[owner()] = _rOwned[owner()] - rAmount;
_rOwned[adr] = _rOwned[adr] + rTransferAmount;
emit Transfer(owner(),adr,rTransferAmount);
}
}
} | market status flag normal transaction tx limitsbuysell liquidity generator for tokenomics send converted eth from fees to respective walletsif any account belongs to excludedFromFees account then remove the fee | function _transfer(address from, address to, uint256 amount) private {
uint trade_type = 0;
bool takeFee = true;
bool overMinimumTokenBalance = balanceOf(address(this)) >= minimumTokensBeforeSwap;
require(from != address(0), "ERC20: transfer from the zero address");
if(!marketActive) {
require(premarketUser[from],"cannot trade before the market opening");
}
if(!isInternalTransaction) {
if(automatedMarketMakerPairs[from]) {
trade_type = 1;
}
else if(automatedMarketMakerPairs[to]) {
trade_type = 2;
if (swapAndLiquifyEnabled &&
balanceOf(uniswapV2Pair) > 0 &&
overMinimumTokenBalance &&
startTimeForSwap + intervalSecondsForSwap <= block.timestamp
) {
startTimeForSwap = block.timestamp;
swapAndLiquify(tokensToSwap);
}
}
if(moveEthToWallets) {
uint256 remaningEth = address(this).balance;
if(remaningEth > minimumWeiForTokenomics) {
sendToWallet(remaningEth);
}
}
}
if(excludedFromFees[from] || excludedFromFees[to]){
takeFee = false;
}
}
| 14,967,831 |
./full_match/5/0x3c4A81308e287a4d1a315415205b6499a3C9286a/sources/project_/contracts/BaseContracts/BaseVault.sol | owner can change timeLock; the new `timeLock` cannot be lower than `absoluteMinTimeLock` _newTimeLock Sets the new minimum default `timeLock` in seconds; pending payments maintain their `earliestPayTime` | function setTimelock(uint256 _newTimeLock) public onlyOwner {
require(
_newTimeLock > absoluteMinTimeLock,
"BaseVault: _newTimeLock should be higher than absoluteMinTimeLock"
);
timeLock = _newTimeLock;
}
| 1,929,467 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./interfaces/IConvenience.sol";
import "./authorizers/interfaces/IAuthorizer.sol";
import "./interfaces/IAirnode.sol";
contract Convenience is IConvenience {
IAirnode public airnode;
constructor (address _airnode)
public
{
airnode = IAirnode(_airnode);
}
/// @notice A convenience function to retrieve provider parameters and the
/// block number with a single call
/// @param providerId Provider ID
/// @return admin Provider admin
/// @return xpub Master public key of the provider node
/// @return blockNumber Block number
function getProviderAndBlockNumber(bytes32 providerId)
external
view
override
returns (
address admin,
string memory xpub,
uint256 blockNumber
)
{
(admin, xpub) = airnode.getProvider(providerId);
blockNumber = block.number;
}
/// @notice A convenience function to retrieve multiple templates with a
/// single call
/// @param templateIds Request template IDs
/// @return providerIds Provider IDs from ProviderStore
/// @return endpointIds Endpoint IDs from EndpointStore
/// @return requesterIndices Requester indices from RequesterStore
/// @return designatedWallets Designated wallets that are requested to
/// fulfill the request
/// @return fulfillAddresses Addresses that will be called to fulfill
/// @return fulfillFunctionIds Signatures of the functions that will be
/// called to fulfill
/// @return parameters Array of static request parameters (i.e., parameters
/// that will not change between requests, unlike the dynamic parameters
/// determined at runtime)
function getTemplates(bytes32[] calldata templateIds)
external
view
override
returns (
bytes32[] memory providerIds,
bytes32[] memory endpointIds,
uint256[] memory requesterIndices,
address[] memory designatedWallets,
address[] memory fulfillAddresses,
bytes4[] memory fulfillFunctionIds,
bytes[] memory parameters
)
{
providerIds = new bytes32[](templateIds.length);
endpointIds = new bytes32[](templateIds.length);
requesterIndices = new uint256[](templateIds.length);
designatedWallets = new address[](templateIds.length);
fulfillAddresses = new address[](templateIds.length);
fulfillFunctionIds = new bytes4[](templateIds.length);
parameters = new bytes[](templateIds.length);
for (uint256 ind = 0; ind < templateIds.length; ind++)
{
(
providerIds[ind],
endpointIds[ind],
requesterIndices[ind],
designatedWallets[ind],
fulfillAddresses[ind],
fulfillFunctionIds[ind],
parameters[ind]
) = airnode.getTemplate(templateIds[ind]);
}
}
/// @notice Uses the authorizer contracts of an endpoint of a provider to
/// decide if a client contract is authorized to call the endpoint. Once an
/// oracle node receives a request, it calls this method to determine if it
/// should respond. Similarly, third parties can use this method to
/// determine if a client contract is authorized to call an endpoint.
/// @dev Authorizer contracts are not trusted, so this method should only
/// be called off-chain.
/// The elements of the authorizer array are either addresses of Authorizer
/// contracts with the interface defined in IAuthorizer or 0.
/// Say we have authorizer contracts X, Y, Z, T, and our authorizer
/// array is [X, Y, 0, Z, T]. This means that the requester should satisfy
/// (X AND Y) OR (Z AND T) to be considered authorized. In other words,
/// consequent authorizer contracts need to verify authorization
/// simultaneously, while 0 represents the start of an independent
/// authorization policy. From a logical standpoint, consequent authorizers
/// get ANDed while 0 acts as an OR gate, providing great flexibility in
/// forming an authorization policy out of simple building blocks. We could
/// also define a NOT gate here to achieve a full set of universal logic
/// gates, but that does not make much sense in this context because
/// authorizers tend to check for positive conditions (have paid, is
/// whitelisted, etc.) and we would not need policies that require these to
/// be false.
/// Note that authorizers should not start or end with 0, and 0s should
/// not be used consecutively (e.g., [X, Y, 0, 0, Z, T]).
/// [] returns false (deny everyone), [0] returns true (accept everyone).
/// @param providerId Provider ID from ProviderStore
/// @param requestId Request ID
/// @param endpointId Endpoint ID from EndpointStore
/// @param requesterIndex Requester index from RequesterStore
/// @param designatedWallet Designated wallet
/// @param clientAddress Client address
/// @return status Authorization status of the request
function checkAuthorizationStatus(
bytes32 providerId,
bytes32 requestId,
bytes32 endpointId,
uint256 requesterIndex,
address designatedWallet,
address clientAddress
)
public
view
override
returns(bool status)
{
address[] memory authorizers = airnode.getEndpointAuthorizers(providerId, endpointId);
uint256 noAuthorizers = authorizers.length;
// If no authorizers have been set, deny access by default
if (noAuthorizers == 0)
{
return false;
}
// authorizedByAll will remain true as long as none of the authorizers
// in a group reports that the client is unauthorized
bool authorizedByAll = true;
for (uint256 ind = 0; ind < noAuthorizers; ind++)
{
address authorizerAddress = authorizers[ind];
if (authorizerAddress == address(0)) {
// If we have reached a 0 without getting any unauthorized
// reports, we can return true
if (authorizedByAll) {
return true;
}
// Otherwise, reset authorizedByAll and start checking the next
// group
authorizedByAll = true;
}
// We only need to check the next authorizer if we have a good track
// record for this group
else if (authorizedByAll) {
IAuthorizer authorizer = IAuthorizer(authorizerAddress);
// Set authorizedByAll to false if we got an unauthorized report.
// This means that we will not be able to return a true from
// this group of authorizers.
if (!authorizer.checkIfAuthorized(
requestId, providerId, endpointId, requesterIndex, designatedWallet, clientAddress
)) {
authorizedByAll = false;
}
}
}
// Finally, if we have reached the end of the authorizers (i.e., we
// are at the last element of the last group), just return the current
// authorizedByAll, which will only be true if all authorizers from the
// last group have returned true.
return authorizedByAll;
}
/// @notice A convenience function to make multiple authorization status
/// checks with a single call
/// @param providerId Provider ID from ProviderStore
/// @param requestIds Request IDs
/// @param endpointIds Endpoint IDs from EndpointStore
/// @param requesterIndices Requester indices from RequesterStore
/// @param designatedWallets Designated wallets
/// @param clientAddresses Client addresses
/// @return statuses Authorization statuses of the request
function checkAuthorizationStatuses(
bytes32 providerId,
bytes32[] calldata requestIds,
bytes32[] calldata endpointIds,
uint256[] calldata requesterIndices,
address[] calldata designatedWallets,
address[] calldata clientAddresses
)
external
view
override
returns (bool[] memory statuses)
{
require(
requestIds.length == endpointIds.length
&& requestIds.length == requesterIndices.length
&& requestIds.length == designatedWallets.length
&& requestIds.length == clientAddresses.length,
"Parameter lengths must be equal"
);
statuses = new bool[](requestIds.length);
for (uint256 ind = 0; ind < requestIds.length; ind++)
{
statuses[ind] = checkAuthorizationStatus(
providerId,
requestIds[ind],
endpointIds[ind],
requesterIndices[ind],
designatedWallets[ind],
clientAddresses[ind]
);
}
}
}
| A convenience function to retrieve provider parameters and the block number with a single call providerId Provider ID return admin Provider admin return xpub Master public key of the provider node return blockNumber Block number | function getProviderAndBlockNumber(bytes32 providerId)
external
view
override
returns (
address admin,
string memory xpub,
uint256 blockNumber
)
{
(admin, xpub) = airnode.getProvider(providerId);
blockNumber = block.number;
}
| 5,360,031 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "./interfaces/ITrancheTokens.sol";
import "./interfaces/IPossum.sol";
contract TrancheAToken is Ownable, ERC20, AccessControl, ITrancheTokens {
using SafeMath for uint256;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
address public PossumAddress;
uint256 public protTrancheNum;
constructor(string memory name, string memory symbol, uint256 _trNum) ERC20(name, symbol) {
protTrancheNum = _trNum;
// Grant the minter role to a specified account
_setupRole(MINTER_ROLE, msg.sender);
}
function setPossumMinter(address _jYearn) external onlyOwner {
PossumAddress = _jYearn;
// Grant the minter role to a specified account
_setupRole(MINTER_ROLE, _jYearn);
}
/**
* @dev function that mints tokens to an account.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function mint(address account, uint256 value) external override {
require(hasRole(MINTER_ROLE, msg.sender), "JTrancheA: caller is not a minter");
require(value > 0, "JTrancheA: value is zero");
super._mint(account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given account.
* @param value The amount that will be burnt.
*/
function burn(uint256 value) external override {
require(hasRole(MINTER_ROLE, msg.sender), "JTrancheA: caller cannot burn tokens");
require(value > 0, "JTrancheA: value is zero");
super._burn(msg.sender, value);
}
}
| Grant the minter role to a specified account | function setPossumMinter(address _jYearn) external onlyOwner {
PossumAddress = _jYearn;
_setupRole(MINTER_ROLE, _jYearn);
}
| 1,029,549 |
pragma solidity >=0.7.0 <0.9.0;
import "../../../node_modules/@openzeppelin/contracts/access/Ownable.sol";
contract Quorum is Ownable {
using SafeERC20 for IERC20;
uint256 public gasPerTimeUnit = 100;
IERC20 public token;
event QuorumChanged(
address indexed consumer,
address indexed to,
uint256 amount
);
// event Spawn(
// address indexed from,
// address indexed to,
// string processJSON
// );
// event Kill(
// address indexed from,
// address indexed to,
// uint256 processid
// );
// struct Process {
// string processJSON
// }
struct Consumer {
address owner;
address[] dsps;
// Process[] runningProcesses;
}
mapping(address => Consumer) public consumers;
constructor () {
}
function regConsumer(address[] dsps, address owner) public {
Consumer consumer;
consumer.dsps = dsps;
consumer.owner = owner;
consumers[msg.sender] = consumer;
// emit event
}
// function spawn(address _consumer, string memory processJSON) public {
// // check owner permissions
// }
// function kill(address _consumer, uint256 processId) public {
// // check permissions
// }
function addDSP(address dsp) public {
// start existing processes on new DSP
consumers[msg.sender].dsps = dsps;
// emit event to existing DSPs
}
function setConsumerPermissions(address owner) public {
consumers[msg.sender].owner = owner;
// emit event
}
}
| start existing processes on new DSP emit event to existing DSPs | function addDSP(address dsp) public {
consumers[msg.sender].dsps = dsps;
}
| 2,510,986 |
pragma solidity 0.6.6;
// SPDX-License-Identifier: MIT
/*
* @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;
}
}
// SPDX-License-Identifier: MIT
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
/**
* @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);
}
// SPDX-License-Identifier: MIT
/**
* @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, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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 (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @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) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @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) {
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, reverting 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) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting 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) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* 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);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* 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);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* 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;
}
}
// SPDX-License-Identifier: MIT
/**
* @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 on 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");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
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);
}
}
}
}
// SPDX-License-Identifier: MIT
/**
* @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");
}
}
}
// SPDX-License-Identifier: MIT
abstract contract ReentrancyGuard {
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() public {
_status = _NOT_ENTERED;
}
modifier nonReentrant() {
require(_status != _ENTERED, "REENTRANCY_ERROR");
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// Interface declarations
/* solhint-disable func-order */
interface IUniswapRouter {
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
// SPDX-License-Identifier: MIT
interface IHarvestVault {
function deposit(uint256 amount) external;
function withdraw(uint256 numberOfShares) external;
}
// SPDX-License-Identifier: MIT
interface IMintNoRewardPool {
function stake(uint256 amount) external;
function withdraw(uint256 amount) external;
function earned(address account) external view returns (uint256);
function lastTimeRewardApplicable() external view returns (uint256);
function rewardPerToken() external view returns (uint256);
function rewards(address account) external view returns (uint256);
function userRewardPerTokenPaid(address account)
external
view
returns (uint256);
function lastUpdateTime() external view returns (uint256);
function rewardRate() external view returns (uint256);
function totalSupply() external view returns (uint256);
function rewardPerTokenStored() external view returns (uint256);
function periodFinish() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function getReward() external;
}
// SPDX-License-Identifier: MIT
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev 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) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
/**
* @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;
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 virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual 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 virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual 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 virtual {
_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 { }
}
// This contract is used for printing receipt tokens
// Whenever someone joins a pool, a receipt token will be printed for that person
contract ReceiptToken is ERC20, AccessControl {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
constructor()
public
ERC20("pAT", "Parachain Auction Token")
{
// Grant the contract deployer the default admin role: it will be able
// to grant and revoke any roles
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/**
* @notice Mint new receipt tokens to some user
* @param to Address of the user that gets the receipt tokens
* @param amount Amount of receipt tokens that will get minted
*/
function mint(address to, uint256 amount) public {
require(
hasRole(MINTER_ROLE, msg.sender),
"ReceiptToken: Caller is not a minter"
);
_mint(to, amount);
}
/**
* @notice Burn receipt tokens from some user
* @param from Address of the user that gets the receipt tokens burne
* @param amount Amount of receipt tokens that will get burned
*/
function burn(address from, uint256 amount) public {
require(
hasRole(BURNER_ROLE, msg.sender),
"ReceiptToken: Caller is not a burner"
);
_burn(from, amount);
}
}
// SPDX-License-Identifier: MIT
/*
|Strategy Flow|
- User shows up with ETH.
- We swap his ETH to DAI and then we deposit it in Havest's Vault.
- After this we have fDAI that we add in Harvest's Reward Pool which gives FARM as rewards
- Withdrawal flow does same thing, but backwards.
*/
contract HarvestDAI is Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeMath for uint256;
struct UserDeposits {
uint256 timestamp;
uint256 amountfDai;
}
/// @notice Info of each user.
struct UserInfo {
uint256 amountEth; //how much ETH the user entered with
uint256 amountDai; //how much DAI was obtained by swapping user's ETH
uint256 amountfDai; //how much fDAI was obtained after deposit to vault
uint256 amountReceiptToken; //receipt tokens printed for user; should be equal to amountfDai
uint256 underlyingRatio; //ratio between obtained fDai and dai
uint256 userTreasuryEth; //how much eth the user sent to treasury
uint256 userCollectedFees; //how much eth the user sent to fee address
uint256 joinTimestamp; //first deposit timestamp; taken into account for lock time
bool wasUserBlacklisted; //if user was blacklist at deposit time, he is not receiving receipt tokens
uint256 timestamp; //first deposit timestamp; used for withdrawal lock time check
UserDeposits[] deposits;
uint256 earnedTokens; //before fees
uint256 earnedRewards; //before fees
}
mapping(address => UserInfo) public userInfo;
mapping(address => bool) public blacklisted; //blacklisted users do not receive a receipt token
uint256 public firstDepositTimestamp; //used to calculate reward per block
uint256 public totalDeposits;
uint256 public cap = uint256(1000); //eth cap
uint256 public totalEth; //total invested eth
uint256 public ethPrice; //for UI; to be updated from a script
uint256 public lockTime = 10368000; //120 days
address payable public feeAddress;
uint256 public fee = uint256(50);
uint256 constant feeFactor = uint256(10000);
ReceiptToken public receiptToken;
address public dai;
address public weth;
address public farmToken;
address public harvestPoolToken;
address payable public treasuryAddress;
IMintNoRewardPool public harvestRewardPool; //deposit fDai
IHarvestVault public harvestRewardVault; //get fDai
IUniswapRouter public sushiswapRouter;
uint256 public ethDust;
uint256 public treasueryEthDust;
//events
event RewardsExchanged(
address indexed user,
uint256 rewardsAmount,
uint256 obtainedEth
);
event ExtraTokensExchanged(
address indexed user,
uint256 tokensAmount,
uint256 obtainedEth
);
event ObtainedInfo(
address indexed user,
uint256 underlying,
uint256 underlyingReceipt
);
event RewardsEarned(address indexed user, uint256 amount);
event ExtraTokens(address indexed user, uint256 amount);
event FeeSet(address indexed sender, uint256 feeAmount);
event FeeAddressSet(address indexed sender, address indexed feeAddress);
/// @notice Event emitted when blacklist status for an address changes
event BlacklistChanged(
string actionType,
address indexed user,
bool oldVal,
bool newVal
);
/// @notice Event emitted when user makes a deposit and receipt token is minted
event ReceiptMinted(address indexed user, uint256 amount);
/// @notice Event emitted when user withdraws and receipt token is burned
event ReceiptBurned(address indexed user, uint256 amount);
/// @notice Event emitted when user makes a deposit
event Deposit(
address indexed user,
address indexed origin,
uint256 amountEth,
uint256 amountDai,
uint256 amountfDai
);
/// @notice Event emitted when user withdraws
event Withdraw(
address indexed user,
address indexed origin,
uint256 amountEth,
uint256 amountDai,
uint256 amountfDai,
uint256 treasuryAmountEth
);
/// @notice Event emitted when owner makes a rescue dust request
event RescuedDust(string indexed dustType, uint256 amount);
/// @notice Event emitted when owner changes any contract address
event ChangedAddress(
string indexed addressType,
address indexed oldAddress,
address indexed newAddress
);
//internal
mapping(address => bool) public approved; //to defend against non whitelisted contracts
/// @notice Used internally for avoiding "stack-too-deep" error when depositing
struct DepositData {
address[] swapPath;
uint256[] swapAmounts;
uint256 obtainedDai;
uint256 obtainedfDai;
uint256 prevfDaiBalance;
}
/// @notice Used internally for avoiding "stack-too-deep" error when withdrawing
struct WithdrawData {
uint256 prevDustEthBalance;
uint256 prevfDaiBalance;
uint256 prevDaiBalance;
uint256 obtainedfDai;
uint256 obtainedDai;
uint256 feeableDai;
uint256 totalEth;
uint256 feeableEth;
uint256 auctionedEth;
uint256 rewards;
uint256 farmBalance;
}
/**
* @notice Create a new HarvestDAI contract
* @param _harvestRewardVault VaultDAI address
* @param _harvestRewardPool NoMintRewardPool address
* @param _sushiswapRouter Sushiswap Router address
* @param _harvestPoolToken Pool's underlying token address
* @param _farmToken Farm address
* @param _dai DAI address
* @param _weth WETH address
* @param _treasuryAddress treasury address
* @param _receiptToken Receipt token that is minted and burned
* @param _feeAddress fee address
*/
constructor(
address _harvestRewardVault,
address _harvestRewardPool,
address _sushiswapRouter,
address _harvestPoolToken,
address _farmToken,
address _dai,
address _weth,
address payable _treasuryAddress,
address _receiptToken,
address payable _feeAddress
) public {
require(_harvestRewardVault != address(0), "VAULT_0x0");
require(_harvestRewardPool != address(0), "POOL_0x0");
require(_sushiswapRouter != address(0), "ROUTER_0x0");
require(_harvestPoolToken != address(0), "TOKEN_0x0");
require(_farmToken != address(0), "FARM_0x0");
require(_dai != address(0), "DAI_0x0");
require(_weth != address(0), "WETH_0x0");
require(_treasuryAddress != address(0), "TREASURY_0x0");
require(_receiptToken != address(0), "RECEIPT_0x0");
require(_feeAddress != address(0), "FEE_0x0");
harvestRewardVault = IHarvestVault(_harvestRewardVault);
harvestRewardPool = IMintNoRewardPool(_harvestRewardPool);
sushiswapRouter = IUniswapRouter(_sushiswapRouter);
harvestPoolToken = _harvestPoolToken;
farmToken = _farmToken;
dai = _dai;
weth = _weth;
treasuryAddress = _treasuryAddress;
receiptToken = ReceiptToken(_receiptToken);
feeAddress = _feeAddress;
}
//-----------------------------------------------------------------------------------------------------------------//
//------------------------------------ Setters -------------------------------------------------//
//-----------------------------------------------------------------------------------------------------------------//
/**
* @notice Update the address of VaultDAI
* @dev Can only be called by the owner
* @param _harvestRewardVault Address of VaultDAI
*/
function setHarvestRewardVault(address _harvestRewardVault)
public
onlyOwner
{
require(_harvestRewardVault != address(0), "VAULT_0x0");
emit ChangedAddress(
"VAULT",
address(harvestRewardVault),
_harvestRewardVault
);
harvestRewardVault = IHarvestVault(_harvestRewardVault);
}
/**
* @notice Update the address of NoMintRewardPool
* @dev Can only be called by the owner
* @param _harvestRewardPool Address of NoMintRewardPool
*/
function setHarvestRewardPool(address _harvestRewardPool) public onlyOwner {
require(_harvestRewardPool != address(0), "POOL_0x0");
emit ChangedAddress(
"POOL",
address(harvestRewardPool),
_harvestRewardPool
);
harvestRewardPool = IMintNoRewardPool(_harvestRewardPool);
}
/**
* @notice Update the address of Sushiswap Router
* @dev Can only be called by the owner
* @param _sushiswapRouter Address of Sushiswap Router
*/
function setSushiswapRouter(address _sushiswapRouter) public onlyOwner {
require(_sushiswapRouter != address(0), "0x0");
emit ChangedAddress(
"SUSHISWAP_ROUTER",
address(sushiswapRouter),
_sushiswapRouter
);
sushiswapRouter = IUniswapRouter(_sushiswapRouter);
}
/**
* @notice Update the address of Pool's underlying token
* @dev Can only be called by the owner
* @param _harvestPoolToken Address of Pool's underlying token
*/
function setHarvestPoolToken(address _harvestPoolToken) public onlyOwner {
require(_harvestPoolToken != address(0), "TOKEN_0x0");
emit ChangedAddress("TOKEN", harvestPoolToken, _harvestPoolToken);
harvestPoolToken = _harvestPoolToken;
}
/**
* @notice Update the address of FARM
* @dev Can only be called by the owner
* @param _farmToken Address of FARM
*/
function setFarmToken(address _farmToken) public onlyOwner {
require(_farmToken != address(0), "FARM_0x0");
emit ChangedAddress("FARM", farmToken, _farmToken);
farmToken = _farmToken;
}
/**
* @notice Update the address for fees
* @dev Can only be called by the owner
* @param _feeAddress Fee's address
*/
function setTreasury(address payable _feeAddress) public onlyOwner {
require(_feeAddress != address(0), "0x0");
emit ChangedAddress(
"TREASURY",
address(treasuryAddress),
address(_feeAddress)
);
treasuryAddress = _feeAddress;
}
/**
* @notice Approve contract (only approved contracts or msg.sender==tx.origin can call this strategy)
* @dev Can only be called by the owner
* @param account Contract's address
*/
function approveContractAccess(address account) external onlyOwner {
require(account != address(0), "0x0");
approved[account] = true;
}
/**
* @notice Revoke contract's access (only approved contracts or msg.sender==tx.origin can call this strategy)
* @dev Can only be called by the owner
* @param account Contract's address
*/
function revokeContractAccess(address account) external onlyOwner {
require(account != address(0), "0x0");
approved[account] = false;
}
/**
* @notice Blacklist address; blacklisted addresses do not receive receipt tokens
* @dev Can only be called by the owner
* @param account User/contract address
*/
function blacklistAddress(address account) external onlyOwner {
require(account != address(0), "0x0");
emit BlacklistChanged("BLACKLIST", account, blacklisted[account], true);
blacklisted[account] = true;
}
/**
* @notice Remove address from blacklisted addresses; blacklisted addresses do not receive receipt tokens
* @dev Can only be called by the owner
* @param account User/contract address
*/
function removeFromBlacklist(address account) external onlyOwner {
require(account != address(0), "0x0");
emit BlacklistChanged("REMOVE", account, blacklisted[account], false);
blacklisted[account] = false;
}
/**
* @notice Set max ETH cap for this strategy
* @dev Can only be called by the owner
* @param _cap ETH amount
*/
function setCap(uint256 _cap) external onlyOwner {
cap = _cap;
}
/**
* @notice Set ETH price
* @dev Can only be called by the owner
* @param _price ETH price
*/
function setEthPrice(uint256 _price) external onlyOwner {
require(_price > 0, "PRICE_0");
ethPrice = _price;
}
/**
* @notice Set lock time
* @dev Can only be called by the owner
* @param _lockTime lock time in seconds
*/
function setLockTime(uint256 _lockTime) external onlyOwner {
require(_lockTime > 0, "TIME_0");
lockTime = _lockTime;
}
function setFeeAddress(address payable _feeAddress) public onlyOwner {
feeAddress = _feeAddress;
emit FeeAddressSet(msg.sender, _feeAddress);
}
function setFee(uint256 _fee) public onlyOwner {
require(_fee <= uint256(9000), "FEE_TOO_HIGH");
fee = _fee;
emit FeeSet(msg.sender, _fee);
}
/**
* @notice Rescue dust resulted from swaps/liquidity
* @dev Can only be called by the owner
*/
function rescueDust() public onlyOwner {
if (ethDust > 0) {
treasuryAddress.transfer(ethDust);
treasueryEthDust = treasueryEthDust.add(ethDust);
emit RescuedDust("ETH", ethDust);
ethDust = 0;
}
}
/**
* @notice Rescue any non-reward token that was airdropped to this contract
* @dev Can only be called by the owner
*/
function rescueAirdroppedTokens(address _token, address to)
public
onlyOwner
{
require(_token != address(0), "token_0x0");
require(to != address(0), "to_0x0");
require(_token != farmToken, "rescue_reward_error");
uint256 balanceOfToken = IERC20(_token).balanceOf(address(this));
require(balanceOfToken > 0, "balance_0");
require(IERC20(_token).transfer(to, balanceOfToken), "rescue_failed");
}
/**
* @notice Check if user can withdraw based on current lock time
* @param user Address of the user
* @return true or false
*/
function isWithdrawalAvailable(address user) public view returns (bool) {
if (lockTime > 0) {
return userInfo[user].timestamp.add(lockTime) <= block.timestamp;
}
return true;
}
/**
* @notice Deposit to this strategy for rewards
* @param deadline Number of blocks until transaction expires
* @return Amount of fDAI
*/
function deposit(uint256 deadline)
public
payable
nonReentrant
returns (uint256)
{
// -----
// validate
// -----
_defend();
require(msg.value > 0, "ETH_0");
require(deadline >= block.timestamp, "DEADLINE_ERROR");
require(totalEth.add(msg.value) <= cap, "CAP_REACHED");
DepositData memory results;
UserInfo storage user = userInfo[msg.sender];
if (user.amountfDai == 0) {
user.wasUserBlacklisted = blacklisted[msg.sender];
}
if (user.timestamp == 0) {
user.timestamp = block.timestamp;
}
uint256 sentEth = msg.value;
totalEth = totalEth.add(sentEth);
user.amountEth = user.amountEth.add(sentEth);
// -----
// obtain DAI from received ETH
// -----
results.swapPath = new address[](2);
results.swapPath[0] = weth;
results.swapPath[1] = dai;
results.swapAmounts = sushiswapRouter.swapExactETHForTokens{
value: sentEth
}(uint256(0), results.swapPath, address(this), deadline);
results.obtainedDai = results.swapAmounts[
results.swapAmounts.length - 1
];
user.amountDai = user.amountDai.add(results.obtainedDai);
// -----
// deposit DAI into harvest and get fDAI
// -----
IERC20(dai).safeIncreaseAllowance(
address(harvestRewardVault),
results.obtainedDai
);
results.prevfDaiBalance = IERC20(harvestPoolToken).balanceOf(
address(this)
);
harvestRewardVault.deposit(results.obtainedDai);
results.obtainedfDai = (
IERC20(harvestPoolToken).balanceOf(address(this))
)
.sub(results.prevfDaiBalance);
// -----
// stake fDAI into the NoMintRewardPool
// -----
IERC20(harvestPoolToken).safeIncreaseAllowance(
address(harvestRewardPool),
results.obtainedfDai
);
user.amountfDai = user.amountfDai.add(results.obtainedfDai);
if (!user.wasUserBlacklisted) {
user.amountReceiptToken = user.amountReceiptToken.add(
results.obtainedfDai
);
receiptToken.mint(msg.sender, results.obtainedfDai);
emit ReceiptMinted(msg.sender, results.obtainedfDai);
}
harvestRewardPool.stake(results.obtainedfDai);
emit Deposit(
msg.sender,
tx.origin,
sentEth,
results.obtainedDai,
results.obtainedfDai
);
if (firstDepositTimestamp == 0) {
firstDepositTimestamp = block.timestamp;
}
if (user.joinTimestamp == 0) {
user.joinTimestamp = block.timestamp;
}
totalDeposits = totalDeposits.add(results.obtainedfDai);
harvestRewardPool.getReward(); //transfers FARM to this contract
user.deposits.push(
UserDeposits({
timestamp: block.timestamp,
amountfDai: results.obtainedfDai
})
);
user.underlyingRatio = _getRatio(user.amountfDai, user.amountDai, 18);
return results.obtainedfDai;
}
function _updateDeposits(
bool removeAll,
uint256 remainingAmountfDai,
address account
) private {
UserInfo storage user = userInfo[account];
if (removeAll) {
delete user.deposits;
return;
}
for (uint256 i = user.deposits.length; i > 0; i--) {
if (remainingAmountfDai >= user.deposits[i - 1].amountfDai) {
remainingAmountfDai = remainingAmountfDai.sub(
user.deposits[i - 1].amountfDai
);
user.deposits[i - 1].amountfDai = 0;
} else {
user.deposits[i - 1].amountfDai = user.deposits[i - 1]
.amountfDai
.sub(remainingAmountfDai);
remainingAmountfDai = 0;
}
if (remainingAmountfDai == 0) {
break;
}
}
}
/**
* @notice Withdraw tokens and claim rewards
* @param deadline Number of blocks until transaction expires
* @return Amount of ETH obtained
*/
function withdraw(uint256 amount, uint256 deadline)
public
nonReentrant
returns (uint256)
{
// -----
// validation
// -----
uint256 receiptBalance = receiptToken.balanceOf(msg.sender);
_defend();
require(deadline >= block.timestamp, "DEADLINE_ERROR");
require(amount > 0, "AMOUNT_0");
UserInfo storage user = userInfo[msg.sender];
require(user.amountfDai >= amount, "AMOUNT_GREATER_THAN_BALANCE");
if (!user.wasUserBlacklisted) {
require(
receiptBalance >= user.amountReceiptToken,
"RECEIPT_AMOUNT"
);
}
if (lockTime > 0) {
require(
user.timestamp.add(lockTime) <= block.timestamp,
"LOCK_TIME"
);
}
WithdrawData memory results;
results.prevDustEthBalance = address(this).balance;
// -----
// withdraw from NoMintRewardPool and get fDai back
// -----
results.prevfDaiBalance = IERC20(harvestPoolToken).balanceOf(
address(this)
);
IERC20(harvestPoolToken).safeIncreaseAllowance(
address(harvestRewardPool),
amount
);
harvestRewardPool.getReward(); //transfers FARM to this contract
results.farmBalance = IERC20(farmToken).balanceOf(address(this));
results.rewards = getPendingRewards(msg.sender, amount);
_updateDeposits(amount == user.amountfDai, amount, msg.sender);
harvestRewardPool.withdraw(amount);
results.obtainedfDai = (
IERC20(harvestPoolToken).balanceOf(address(this))
)
.sub(results.prevfDaiBalance);
//not sure if it's possible to get more from harvest so better to protect
if (results.obtainedfDai < user.amountfDai) {
user.amountfDai = user.amountfDai.sub(results.obtainedfDai);
if (!user.wasUserBlacklisted) {
user.amountReceiptToken = user.amountReceiptToken.sub(
results.obtainedfDai
);
receiptToken.burn(msg.sender, results.obtainedfDai);
emit ReceiptBurned(msg.sender, results.obtainedfDai);
}
} else {
user.amountfDai = 0;
if (!user.wasUserBlacklisted) {
receiptToken.burn(msg.sender, user.amountReceiptToken);
emit ReceiptBurned(msg.sender, user.amountReceiptToken);
user.amountReceiptToken = 0;
}
}
// -----
// withdraw from Harvest-DAI vault and get Dai back
// -----
IERC20(harvestPoolToken).safeIncreaseAllowance(
address(harvestRewardVault),
results.obtainedfDai
);
results.prevDaiBalance = IERC20(dai).balanceOf(address(this));
harvestRewardVault.withdraw(results.obtainedfDai);
results.obtainedDai = (IERC20(dai).balanceOf(address(this))).sub(
results.prevDaiBalance
);
emit ObtainedInfo(
msg.sender,
results.obtainedDai,
results.obtainedfDai
);
if (amount == user.amountfDai) {
//there is no point to do the ratio math as we can just get the difference between current obtained tokens and initial obtained tokens
if (results.obtainedDai > user.amountDai) {
results.feeableDai = results.obtainedDai.sub(user.amountDai);
}
} else {
uint256 currentRatio =
_getRatio(results.obtainedfDai, results.obtainedDai, 18);
results.feeableDai = 0;
if (currentRatio < user.underlyingRatio) {
uint256 noOfOriginalTokensForCurrentAmount =
(amount.mul(10**18)).div(user.underlyingRatio);
if (noOfOriginalTokensForCurrentAmount < results.obtainedDai) {
results.feeableDai = results.obtainedDai.sub(
noOfOriginalTokensForCurrentAmount
);
}
}
}
if (results.feeableDai > 0) {
uint256 extraTokensFee = _calculateFee(results.feeableDai);
emit ExtraTokens(
msg.sender,
results.feeableDai.sub(extraTokensFee)
);
user.earnedTokens = user.earnedTokens.add(
results.feeableDai.sub(extraTokensFee)
);
}
//not sure if it's possible to get more from harvest so better to protect
if (results.obtainedDai <= user.amountDai) {
user.amountDai = user.amountDai.sub(results.obtainedDai);
} else {
user.amountDai = 0;
}
results.obtainedDai = results.obtainedDai.sub(results.feeableDai);
// -----
// swap DAI to ETH
// -----
address[] memory swapPath = new address[](2);
swapPath[0] = dai;
swapPath[1] = weth;
if (results.obtainedDai > 0) {
IERC20(dai).safeIncreaseAllowance(
address(sushiswapRouter),
results.obtainedDai.add(results.feeableDai)
);
uint256[] memory daiSwapAmounts =
sushiswapRouter.swapExactTokensForETH(
results.obtainedDai,
uint256(0),
swapPath,
address(this),
deadline
);
results.totalEth = results.totalEth.add(
daiSwapAmounts[daiSwapAmounts.length - 1]
);
}
if (results.feeableDai > 0) {
uint256[] memory daiFeeableSwapAmounts =
sushiswapRouter.swapExactTokensForETH(
results.feeableDai,
uint256(0),
swapPath,
address(this),
deadline
);
emit ExtraTokensExchanged(
msg.sender,
results.feeableDai,
daiFeeableSwapAmounts[daiFeeableSwapAmounts.length - 1]
);
results.feeableEth = results.feeableEth.add(
daiFeeableSwapAmounts[daiFeeableSwapAmounts.length - 1]
);
}
uint256 transferableRewards = results.rewards;
if (transferableRewards > results.farmBalance) {
transferableRewards = results.farmBalance;
}
if (transferableRewards > 0) {
emit RewardsEarned(msg.sender, transferableRewards);
user.earnedRewards = user.earnedRewards.add(transferableRewards);
swapPath[0] = farmToken;
IERC20(farmToken).safeIncreaseAllowance(
address(sushiswapRouter),
transferableRewards
);
uint256[] memory farmSwapAmounts =
sushiswapRouter.swapExactTokensForETH(
transferableRewards,
uint256(0),
swapPath,
address(this),
deadline
);
emit RewardsExchanged(
msg.sender,
transferableRewards,
farmSwapAmounts[farmSwapAmounts.length - 1]
);
results.feeableEth = results.feeableEth.add(
farmSwapAmounts[farmSwapAmounts.length - 1]
);
}
// -----
// transfer ETH to usert
// -----
results.auctionedEth = results.feeableEth.div(2);
results.feeableEth = results.feeableEth.sub(results.auctionedEth);
results.totalEth = results.totalEth.add(results.feeableEth);
totalDeposits = totalDeposits.sub(results.obtainedfDai);
if (user.amountfDai == 0) //full exit
{
//if user exits to early, obtained ETH might be lower than what user initially invested and there will be some left in amountEth
//making sure we reset it
user.amountEth = 0;
} else {
if (user.amountEth > results.totalEth) {
user.amountEth = user.amountEth.sub(results.totalEth);
} else {
user.amountEth = 0;
}
}
if (results.totalEth < totalEth) {
totalEth = totalEth.sub(results.totalEth);
} else {
totalEth = 0;
}
//at some point we might not have any fees
if (fee > 0) {
uint256 feeEth = _calculateFee(results.totalEth);
results.totalEth = results.totalEth.sub(feeEth);
feeAddress.transfer(feeEth);
user.userCollectedFees = user.userCollectedFees.add(feeEth);
}
msg.sender.transfer(results.totalEth);
treasuryAddress.transfer(results.auctionedEth);
user.userTreasuryEth = user.userTreasuryEth.add(results.auctionedEth);
emit Withdraw(
msg.sender,
tx.origin,
results.totalEth,
results.obtainedDai,
results.obtainedfDai,
results.auctionedEth
);
ethDust = ethDust.add(
address(this).balance.sub(results.prevDustEthBalance)
);
if (user.amountfDai == 0 || user.amountDai == 0) {
user.underlyingRatio = 0;
} else {
user.underlyingRatio = _getRatio(
user.amountfDai,
user.amountDai,
18
);
}
return results.totalEth;
}
/// @notice Transfer rewards to this strategy
function updateReward() public onlyOwner {
harvestRewardPool.getReward();
}
function _calculateFee(uint256 amount) private view returns (uint256) {
return (amount.mul(fee)).div(feeFactor);
}
function _defend() private view returns (bool) {
require(
approved[msg.sender] || msg.sender == tx.origin,
"access_denied"
);
}
//-----------------------------------------------------------------------------------------------------------------//
//------------------------------------ Getters -------------------------------------------------//
//-----------------------------------------------------------------------------------------------------------------//
/**
* @notice View function to see pending rewards for account.
* @param account user account to check
* @param amount amount you want to calculate for; if 0 will calculate for entire amount
* @return pending rewards
*/
function getPendingRewards(address account, uint256 amount)
public
view
returns (uint256)
{
UserInfo storage user = userInfo[account];
if (amount == 0) {
amount = user.amountfDai;
}
if (user.deposits.length == 0 || user.amountfDai == 0) {
return 0;
}
uint256 rewards = 0;
uint256 remaingAmount = amount;
uint256 i = user.deposits.length - 1;
while (remaingAmount > 0) {
uint256 depositRewards =
_getPendingRewards(user.deposits[i], remaingAmount);
rewards = rewards.add(depositRewards);
if (remaingAmount >= user.deposits[i].amountfDai) {
remaingAmount = remaingAmount.sub(user.deposits[i].amountfDai);
} else {
remaingAmount = 0;
}
if (i == 0) {
break;
}
i = i.sub(1);
}
return rewards;
}
function _getPendingRewards(
UserDeposits memory user,
uint256 remainingAmount
) private view returns (uint256) {
if (user.amountfDai == 0) {
return 0;
}
uint256 toCalculateForAmount = 0;
if (user.amountfDai <= remainingAmount) {
toCalculateForAmount = user.amountfDai;
} else {
toCalculateForAmount = remainingAmount;
}
uint256 rewardPerBlock = 0;
uint256 balance = IERC20(farmToken).balanceOf(address(this));
if (balance == 0) {
return 0;
}
uint256 diff = block.timestamp.sub(firstDepositTimestamp);
if (diff == 0) {
rewardPerBlock = balance;
} else {
rewardPerBlock = balance.div(diff);
}
uint256 rewardPerBlockUser =
rewardPerBlock.mul(block.timestamp.sub(user.timestamp));
uint256 ratio = _getRatio(toCalculateForAmount, totalDeposits, 18);
return (rewardPerBlockUser.mul(ratio)).div(10**18);
}
function _getRatio(
uint256 numerator,
uint256 denominator,
uint256 precision
) private pure returns (uint256) {
uint256 _numerator = numerator * 10**(precision + 1);
uint256 _quotient = ((_numerator / denominator) + 5) / 10;
return (_quotient);
}
receive() external payable {}
} | Revoke contract's access (only approved contracts or msg.sender==tx.origin can call this strategy) Can only be called by the owner account Contract's address/ | function revokeContractAccess(address account) external onlyOwner {
require(account != address(0), "0x0");
approved[account] = false;
}
| 361,859 |
// File: @openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @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 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) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.8.0;
/**
* @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/token/ERC20/extensions/IERC20Metadata.sol
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.8.0;
/**
* @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, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override 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 this function is
* overridden;
*
* 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 virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual 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);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
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] + 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) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
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);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += 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 += amount;
_balances[account] += 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);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= 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 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/extensions/ERC20Capped.sol
pragma solidity ^0.8.0;
/**
* @dev Extension of {ERC20} that adds a cap to the supply of tokens.
*/
abstract contract ERC20Capped is ERC20 {
uint256 immutable private _cap;
/**
* @dev Sets the value of the `cap`. This value is immutable, it can only be
* set once during construction.
*/
constructor (uint256 cap_) {
require(cap_ > 0, "ERC20Capped: cap is 0");
_cap = cap_;
}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view virtual returns (uint256) {
return _cap;
}
/**
* @dev See {ERC20-_mint}.
*/
function _mint(address account, uint256 amount) internal virtual override {
require(ERC20.totalSupply() + amount <= cap(), "ERC20Capped: cap exceeded");
super._mint(account, amount);
}
}
// File: contracts/libraries/SafeMath.sol
pragma solidity ^0.8.0;
/**
* @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, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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 (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @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) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @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) {
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, reverting 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) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting 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) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* 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);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* 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);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* 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: contracts/SpheriumToken.sol
pragma solidity ^0.8.0;
pragma solidity ^0.8.0;
interface ILiquidityProtectionService {
event Blocked(address pool, address trader, string trap);
function getLiquidityPool(address tokenA, address tokenB)
external view returns(address);
function LiquidityAmountTrap_preValidateTransfer(
address from, address to, uint amount,
address counterToken, uint8 trapBlocks, uint128 trapAmount)
external returns(bool passed);
function FirstBlockTrap_preValidateTransfer(
address from, address to, uint amount, address counterToken)
external returns(bool passed);
function LiquidityPercentTrap_preValidateTransfer(
address from, address to, uint amount,
address counterToken, uint8 trapBlocks, uint64 trapPercent)
external returns(bool passed);
function LiquidityActivityTrap_preValidateTransfer(
address from, address to, uint amount,
address counterToken, uint8 trapBlocks, uint8 trapCount)
external returns(bool passed);
function isBlocked(address counterToken, address who)
external view returns(bool);
}
pragma solidity ^0.8.0;
abstract contract UsingLiquidityProtectionService {
bool private protected = true;
uint64 internal constant HUNDRED_PERCENT = 1e18;
function liquidityProtectionService() internal pure virtual returns(address);
function LPS_isAdmin() internal view virtual returns(bool);
function LPS_balanceOf(address _holder) internal view virtual returns(uint);
function LPS_transfer(address _from, address _to, uint _value) internal virtual;
function counterToken() internal pure virtual returns(address) {
return 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // WETH
}
function protectionChecker() internal view virtual returns(bool) {
return ProtectionSwitch_manual();
}
function FirstBlockTrap_skip() internal pure virtual returns(bool) {
return false;
}
function LiquidityAmountTrap_skip() internal pure virtual returns(bool) {
return false;
}
function LiquidityAmountTrap_blocks() internal pure virtual returns(uint8) {
return 5;
}
function LiquidityAmountTrap_amount() internal pure virtual returns(uint128) {
return 5000 * 1e18; // Only valid for tokens with 18 decimals.
}
function LiquidityPercentTrap_skip() internal pure virtual returns(bool) {
return false;
}
function LiquidityPercentTrap_blocks() internal pure virtual returns(uint8) {
return 50;
}
function LiquidityPercentTrap_percent() internal pure virtual returns(uint64) {
return HUNDRED_PERCENT / 1000; // 0.1%
}
function LiquidityActivityTrap_skip() internal pure virtual returns(bool) {
return false;
}
function LiquidityActivityTrap_blocks() internal pure virtual returns(uint8) {
return 30;
}
function LiquidityActivityTrap_count() internal pure virtual returns(uint8) {
return 15;
}
function lps() private pure returns(ILiquidityProtectionService) {
return ILiquidityProtectionService(liquidityProtectionService());
}
function LPS_beforeTokenTransfer(address _from, address _to, uint _amount) internal {
if (protectionChecker()) {
if (!protected) {
return;
}
require(FirstBlockTrap_skip() || lps().FirstBlockTrap_preValidateTransfer(
_from, _to, _amount, counterToken()), 'FirstBlockTrap: blocked');
require(LiquidityAmountTrap_skip() || lps().LiquidityAmountTrap_preValidateTransfer(
_from,
_to,
_amount,
counterToken(),
LiquidityAmountTrap_blocks(),
LiquidityAmountTrap_amount()), 'LiquidityAmountTrap: blocked');
require(LiquidityPercentTrap_skip() || lps().LiquidityPercentTrap_preValidateTransfer(
_from,
_to,
_amount,
counterToken(),
LiquidityPercentTrap_blocks(),
LiquidityPercentTrap_percent()), 'LiquidityPercentTrap: blocked');
require(LiquidityActivityTrap_skip() || lps().LiquidityActivityTrap_preValidateTransfer(
_from,
_to,
_amount,
counterToken(),
LiquidityActivityTrap_blocks(),
LiquidityActivityTrap_count()), 'LiquidityActivityTrap: blocked');
}
}
function revokeBlocked(address[] calldata _holders, address _revokeTo) external {
require(LPS_isAdmin(), 'UsingLiquidityProtectionService: not admin');
require(protectionChecker(), 'UsingLiquidityProtectionService: protection removed');
protected = false;
for (uint i = 0; i < _holders.length; i++) {
address holder = _holders[i];
if (lps().isBlocked(counterToken(), _holders[i])) {
LPS_transfer(holder, _revokeTo, LPS_balanceOf(holder));
}
}
protected = true;
}
function disableProtection() external {
require(LPS_isAdmin(), 'UsingLiquidityProtectionService: not admin');
protected = false;
}
function isProtected() public view returns(bool) {
return protected;
}
function ProtectionSwitch_manual() internal view returns(bool) {
return protected;
}
function ProtectionSwitch_timestamp(uint _timestamp) internal view returns(bool) {
return not(passed(_timestamp));
}
function ProtectionSwitch_block(uint _block) internal view returns(bool) {
return not(blockPassed(_block));
}
function blockPassed(uint _block) internal view returns(bool) {
return _block < block.number;
}
function passed(uint _timestamp) internal view returns(bool) {
return _timestamp < block.timestamp;
}
function not(bool _condition) internal pure returns(bool) {
return !_condition;
}
}
contract spheriumToken is ERC20, ERC20Capped, Ownable, UsingLiquidityProtectionService{
using SafeMath for uint256;
/// @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);
constructor() ERC20("Spherium Token", "SPHRI") ERC20Capped(100000000 * (10**uint256(18))){}
function _mint(address account, uint256 amount) internal virtual override(ERC20, ERC20Capped) {
super._mint(account, amount);
}
function mint(address account, uint256 amount)public onlyOwner{
uint256 amount_ = amount * (10**uint256(18));
_mint(account,amount_);
}
/**
* @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 override {
super._transfer(sender,recipient,amount);
_moveDelegates(_delegates[sender], _delegates[recipient], amount);
}
/**
* @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), "SPHRI::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "SPHRI::delegateBySig: invalid nonce");
require(block.timestamp <= expiry, "SPHRI::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, "SPHRI::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);
_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, "SPHRI::_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 view returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
// Mandatory overrides.
function _beforeTokenTransfer(address _from, address _to, uint _amount) internal override {
super._beforeTokenTransfer(_from, _to, _amount);
LPS_beforeTokenTransfer(_from, _to, _amount);
}
function LPS_isAdmin() internal view override returns(bool) {
return _msgSender() == owner();
}
function liquidityProtectionService() internal pure override returns(address) {
return 0xaabAe39230233d4FaFf04111EF08665880BD6dFb; // Replace with the correct address.
}
// Expose balanceOf().
function LPS_balanceOf(address _holder) internal view override returns(uint) {
return balanceOf(_holder);
}
// Expose internal transfer function.
function LPS_transfer(address _from, address _to, uint _value) internal override {
_transfer(_from, _to, _value);
}
// All the following overrides are optional, if you want to modify default behavior.
// How the protection gets disabled.
function protectionChecker() internal view override returns(bool) {
return ProtectionSwitch_timestamp(1624665599); // Switch off protection on Friday, June 25, 2021 11:59:59 PM GMT
// return ProtectionSwitch_block(13000000); // Switch off protection on block 13000000.
//return ProtectionSwitch_manual(); // Switch off protection by calling disableProtection(); from owner. Default.
}
// This token will be pooled in pair with:
function counterToken() internal pure override returns(address) {
return 0xdAC17F958D2ee523a2206206994597C13D831ec7; // USDT
}
// Disable/Enable FirstBlockTrap
function FirstBlockTrap_skip() internal pure override returns(bool) {
return false;
}
// Disable/Enable absolute amount of tokens bought trap.
// Per address per LiquidityAmountTrap_blocks.
function LiquidityAmountTrap_skip() internal pure override returns(bool) {
return false;
}
function LiquidityAmountTrap_blocks() internal pure override returns(uint8) {
return 4;
}
function LiquidityAmountTrap_amount() internal pure override returns(uint128) {
return 19000 * 1e18; // Only valid for tokens with 18 decimals.
}
// Disable/Enable percent of remaining liquidity bought trap.
// Per address per block.
function LiquidityPercentTrap_skip() internal pure override returns(bool) {
return false;
}
function LiquidityPercentTrap_blocks() internal pure override returns(uint8) {
return 6;
}
function LiquidityPercentTrap_percent() internal pure override returns(uint64) {
return HUNDRED_PERCENT / 25; // 4%
}
// Disable/Enable number of trades trap.
// Per block.
function LiquidityActivityTrap_skip() internal pure override returns(bool) {
return false;
}
function LiquidityActivityTrap_blocks() internal pure override returns(uint8) {
return 3;
}
function LiquidityActivityTrap_count() internal pure override returns(uint8) {
return 8;
}
} | Mandatory overrides. | function _beforeTokenTransfer(address _from, address _to, uint _amount) internal override {
super._beforeTokenTransfer(_from, _to, _amount);
LPS_beforeTokenTransfer(_from, _to, _amount);
}
| 13,497,868 |
//โโโโโโโ โโโโโโ โโโ โโโโโโ โโโโโโโ โโโโโโโ โโโ
//โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โโโ
//โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโ โโโ
//โโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโโโโโ
//โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โโโโโโ
//โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโ โโโโโโ โโโโโ
pragma solidity ^0.7.6;
//SPDX-License-Identifier: MIT
import "./utils/Errors.sol";
import "./ControllerStorage.sol";
/** @title Paladin Controller contract */
/// @author Paladin
contract ControllerProxy is ControllerStorage {
event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);
event NewImplementation(address oldImplementation, address newImplementation);
constructor(){
admin = msg.sender;
}
/**
* @dev Proposes the address of a new Implementation (the new Controller contract)
*/
function proposeImplementation(address newPendingImplementation) public adminOnly {
address oldPendingImplementation = pendingImplementation;
pendingImplementation = newPendingImplementation;
emit NewPendingImplementation(oldPendingImplementation, newPendingImplementation);
}
/**
* @dev Accepts the Pending Implementation as new Current Implementation
* Only callable by the Pending Implementation contract
*/
function acceptImplementation() public returns(bool) {
require(msg.sender == pendingImplementation || pendingImplementation == address(0), Errors.CALLER_NOT_IMPLEMENTATION);
address oldImplementation = currentImplementation;
address oldPendingImplementation = pendingImplementation;
currentImplementation = pendingImplementation;
pendingImplementation = address(0);
emit NewImplementation(oldImplementation, currentImplementation);
emit NewPendingImplementation(oldPendingImplementation, pendingImplementation);
return true;
}
/**
* @dev Delegates execution to an implementation contract.
* It returns to the external caller whatever the implementation returns
* or forwards reverts.
*/
fallback() external payable {
// delegate all other functions to current implementation
(bool success, ) = currentImplementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize())
switch success
case 0 { revert(free_mem_ptr, returndatasize()) }
default { return(free_mem_ptr, returndatasize()) }
}
}
}
//โโโโโโโ โโโโโโ โโโ โโโโโโ โโโโโโโ โโโโโโโ โโโ
//โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โโโ
//โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโ โโโ
//โโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโโโโโ
//โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โโโโโโ
//โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโ โโโโโโ โโโโโ
pragma solidity ^0.7.6;
//SPDX-License-Identifier: MIT
library Errors {
// Admin error
string public constant CALLER_NOT_ADMIN = '1'; // 'The caller must be the admin'
string public constant CALLER_NOT_CONTROLLER = '29'; // 'The caller must be the admin or the controller'
string public constant CALLER_NOT_ALLOWED_POOL = '30'; // 'The caller must be a palPool listed in the controller'
string public constant CALLER_NOT_MINTER = '31';
string public constant CALLER_NOT_IMPLEMENTATION = '35'; // 'The caller must be the pending Implementation'
// ERC20 type errors
string public constant FAIL_TRANSFER = '2';
string public constant FAIL_TRANSFER_FROM = '3';
string public constant BALANCE_TOO_LOW = '4';
string public constant ALLOWANCE_TOO_LOW = '5';
string public constant SELF_TRANSFER = '6';
// PalPool errors
string public constant INSUFFICIENT_CASH = '9';
string public constant INSUFFICIENT_BALANCE = '10';
string public constant FAIL_DEPOSIT = '11';
string public constant FAIL_LOAN_INITIATE = '12';
string public constant FAIL_BORROW = '13';
string public constant ZERO_BORROW = '27';
string public constant BORROW_INSUFFICIENT_FEES = '23';
string public constant LOAN_CLOSED = '14';
string public constant NOT_LOAN_OWNER = '15';
string public constant LOAN_OWNER = '16';
string public constant FAIL_LOAN_EXPAND = '17';
string public constant NOT_KILLABLE = '18';
string public constant RESERVE_FUNDS_INSUFFICIENT = '19';
string public constant FAIL_MINT = '20';
string public constant FAIL_BURN = '21';
string public constant FAIL_WITHDRAW = '24';
string public constant FAIL_CLOSE_BORROW = '25';
string public constant FAIL_KILL_BORROW = '26';
string public constant ZERO_ADDRESS = '22';
string public constant INVALID_PARAMETERS = '28';
string public constant FAIL_LOAN_DELEGATEE_CHANGE = '32';
string public constant FAIL_LOAN_TOKEN_BURN = '33';
string public constant FEES_ACCRUED_INSUFFICIENT = '34';
//Controller errors
string public constant LIST_SIZES_NOT_EQUAL = '36';
string public constant POOL_LIST_ALREADY_SET = '37';
string public constant POOL_ALREADY_LISTED = '38';
string public constant POOL_NOT_LISTED = '39';
string public constant CALLER_NOT_POOL = '40';
string public constant REWARDS_CASH_TOO_LOW = '41';
string public constant FAIL_BECOME_IMPLEMENTATION = '42';
string public constant INSUFFICIENT_DEPOSITED = '43';
string public constant NOT_CLAIMABLE = '44';
string public constant LOCKED = '45';
}
//โโโโโโโ โโโโโโ โโโ โโโโโโ โโโโโโโ โโโโโโโ โโโ
//โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โโโ
//โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโ โโโ
//โโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโโโโโ
//โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โโโโโโ
//โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโ โโโโโโ โโโโโ
pragma solidity ^0.7.6;
//SPDX-License-Identifier: MIT
import "./utils/Admin.sol";
/** @title Paladin Controller contract */
/// @author Paladin
contract ControllerStorage is Admin {
/** @notice Layout for the Proxy contract */
address public currentImplementation;
address public pendingImplementation;
/** @notice List of current active palToken Pools */
address[] public palTokens;
address[] public palPools;
mapping(address => address) public palTokenToPalPool;
bool internal initialized;
/** @notice Struct with current SupplyIndex for a Pool, and the block of the last update */
struct PoolRewardsState {
uint224 index;
uint32 blockNumber;
}
/** @notice Initial index for Rewards */
uint224 public constant initialRewardsIndex = 1e36;
address public rewardTokenAddress; // PAL token address to put here
/** @notice State of the Rewards for each Pool */
mapping(address => PoolRewardsState) public supplyRewardState;
/** @notice Amount of reward tokens to distribute each block */
mapping(address => uint) public supplySpeeds;
/** @notice Last reward index for each Pool for each user */
/** PalPool => User => Index */
mapping(address => mapping(address => uint)) public supplierRewardIndex;
/** @notice Deposited amounts by user for each palToken (indexed by corresponding PalPool address) */
/** PalPool => User => Amount */
mapping(address => mapping(address => uint)) public supplierDeposits;
/** @notice Total amount of each palToken deposited (indexed by corresponding PalPool address) */
/** PalPool => Total Amount */
mapping(address => uint) public totalSupplierDeposits;
/** @notice Ratio to distribute Borrow Rewards */
mapping(address => uint) public borrowRatios; // scaled 1e18
/** @notice Ratio for each PalLoan (set at PalLoan creation) */
mapping(address => uint) public loansBorrowRatios; // scaled 1e18
/** @notice Amount of reward Tokens accrued by the user, and claimable */
mapping(address => uint) public accruedRewards;
/** @notice Is Auto Borrow Rewards is activated for the PalPool */
mapping(address => bool) public autoBorrowRewards;
/** @notice Was PalLoan Borrow Rewards distributed & claimed */
mapping(address => bool) public isLoanRewardClaimed;
/** @notice Block at which Borrow Rewards Ratio where set for the PalPool (if Ratio is put back to 0, this block number is set back to 0 too) */
/** So PalLoan started when no Borrow Rewards where set do not receive rewards */
/** PalPool => Block Number */
mapping(address => uint) public borrowRewardsStartBlock;
/** @dev Prevent reentry in some functions */
bool internal locked;
/*
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!! ALWAYS PUT NEW STORAGE AT THE BOTTOM !!!!!!!!!!!!!!!!!!
!!!!!!!!! WE DON'T WANT COLLISION WHEN SWITCHING IMPLEMENTATIONS !!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
*/
}
pragma solidity ^0.7.6;
//SPDX-License-Identifier: MIT
/** @title Admin contract */
/// @author Paladin
contract Admin {
/** @notice (Admin) Event when the contract admin is updated */
event NewAdmin(address oldAdmin, address newAdmin);
/** @dev Admin address for this contract */
address payable internal admin;
modifier adminOnly() {
//allows only the admin of this contract to call the function
require(msg.sender == admin, '1');
_;
}
/**
* @notice Set a new Admin
* @dev Changes the address for the admin parameter
* @param _newAdmin address of the new Controller Admin
*/
function setNewAdmin(address payable _newAdmin) external adminOnly {
address _oldAdmin = admin;
admin = _newAdmin;
emit NewAdmin(_oldAdmin, _newAdmin);
}
} | Proposes the address of a new Implementation (the new Controller contract)/ | function proposeImplementation(address newPendingImplementation) public adminOnly {
address oldPendingImplementation = pendingImplementation;
pendingImplementation = newPendingImplementation;
emit NewPendingImplementation(oldPendingImplementation, newPendingImplementation);
}
| 1,062,175 |
./full_match/5/0xFa485843F86074F35a05aDEF4F9e10f921aa5493/sources/contracts/CrowdFunding.sol | is everything okay? | function createCampaign(address _owner, string memory _title, string memory _description, uint256 _target, uint256 _deadline, string memory _image) public returns (uint256) {
Campaign storage campaign = campaigns[numberOfCampaigns];
require(campaign.deadline < block.timestamp, "Deadline should be date in future");
campaign.owner = _owner;
campaign.title = _title;
campaign.description = _description;
campaign.target = _target;
campaign.deadline = _deadline;
campaign.amountCollected = 0;
campaign.image = _image;
numberOfCampaigns++;
}
| 1,853,334 |
./full_match/80001/0xd55A0Ca328477b75d6f7F738237473005c90B809/sources/project_/contracts/KeyHolder.sol | implementation of the addKey function of the ERC-734 standard Adds a _key to the identity. The _purpose specifies the purpose of key. Initially we propose four purpose: 1: MANAGEMENT keys, which can manage the identity 2: ACTION keys, which perform actions in this identities name (signing, logins, transactions, etc.) 3: CLAIM signer keys, used to sign claims on other identities which need to be revokable. 4: ENCRYPTION keys, used to encrypt data e.g. hold in claims. MUST only be done by keys of purpose 1, or the identity itself. If its the identity itself, the approval process will determine its approval. key keccak256 representation of an ethereum address keyType type of key used, which would be a uint256 for different key types. e.g. 1 = ECDSA, 2 = RSA, etc. purposeType a uint256 specifying the key type, like 1 = MANAGEMENT, 2 = ACTION, 3 = CLAIM, 4 = ENCRYPTION return success Returns TRUE if the addition was successful and FALSE if not/ | function addKey(
bytes32 key,
uint256 purposeType,
uint256 keyType
) public override mOnlyManagementKey returns (bool success) {
if (_keys[key].key == key) {
uint256[] memory _purposes = _keys[key].purposes;
for (
uint256 keyPurposeIndex = 0;
keyPurposeIndex < _purposes.length;
keyPurposeIndex++
) {
uint256 purpose = _purposes[keyPurposeIndex];
if (purpose == purpose) {
revert("Conflict: Key already has purpose");
}
}
_keys[key].purposes.push(purposeType);
_keys[key].key = key;
_keys[key].purposes = [purposeType];
_keys[key].keyType = keyType;
}
_keysByPurpose[purposeType].push(key);
emit KeyAdded(key, purposeType, keyType);
return true;
}
| 5,638,151 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
import "Initiative_Legislative_lib.sol";
import "Register.sol";
import "Citizens_Register.sol";
import "IVote.sol";
import "IDelegation.sol";
*/
import "contracts/Initiative_Legislative_lib.sol";
import "contracts/Register.sol";
import "contracts/Citizens_Register.sol";
import "contracts/IVote.sol";
import "contracts/IDelegation.sol";
/**
* @notice Delegation_Uils library is used to reduce the size of Delegation contract in order to avoid to exceed contract limit size. It contains heavy functions and data structures.
*/
library Delegation_Uils{
using EnumerableSet for EnumerableSet.AddressSet;
/**
* @dev Parameters related to the democratic process of registers governance.
* - Member_Max_Token_Usage: The maximum amount of token a member is allowed to use for a specific law project elaboration
* - Law_Initialisation_Price: The price in token for creating a law project
* - FunctionCall_Price: The price in token for one FunctionCall.
* - Proposition_Duration: The duration of the stage in which members are allowed to submit propositions
* - Vote_Duration: The duration of the stage in which members are allowed to vote for the proposition they want
* - Law_Censor_Period_Duration: The duration of the stage in which all citizens are allowed to sign a etition against the law project proposed by the Delegation
* - Censor_Proposition_Petition_Rate The minimum ratio of citizens required to cancel a law project
* - Censor_Penalty_Rate The amount of token the delegation will lost if their law project is rejected by citizens
* - Ivote_address Address of the IVote contract that will be used during voting stage
*/
struct Law_Project_Parameters{
uint Member_Max_Token_Usage;
uint Law_Initialisation_Price;
uint FunctionCall_Price;
uint Proposition_Duration;
uint Vote_Duration;
uint Law_Censor_Period_Duration;
uint16 Censor_Proposition_Petition_Rate;
uint16 Censor_Penalty_Rate;
address Ivote_address;
}
/**
* @dev Structure reresenting parameters related to the democratic process of registers governance.
* - Election_Duration Duration of the stage in which citizens are allowed to vote for Candidats they prefer
* - Validation_Duration Duration of the stage in which citizens can validate their hased vote by revealing their choice and the salt that has been used for hasing
* - Mandate_Duration Duration of a delegation mandate
* - Immunity_Duration Amount of time after the beginning of a new mandate during which delegation's members can't be revoked
* - Next_Mandate_Max_Members Maximum number of members in the delegation.
* - New_Election_Petition_Rate The minimum ratio of citizens required to revoke the current delegation's members and start a new election
* - Ivote_address Address of the IVote contract that will be used during election stage
*/
struct Mandate_Parameter{
uint Election_Duration;
uint Validation_Duration;
uint Mandate_Duration;
uint Immunity_Duration;
uint16 Next_Mandate_Max_Members;
uint16 New_Election_Petition_Rate;
address Ivote_address;
}
/**
* @dev Structure representing a mandate.
* - Members Duration : List of members of the delegation
* - New_Election_Petitions: List of citizens who have signed petition for revoking the current delegation's members.
* - Next_Mandate_Candidats: List of accounts that are candidates for the next election
* - Inauguration_Timestamps: Beginning of current mandate
* - Election_Timestamps: Beginning of election
* - Version: Version of parameters (Id of {Mandate_Parameter} object) used by this mandate
*/
struct Mandate{
EnumerableSet.AddressSet Members;
EnumerableSet.AddressSet New_Election_Petitions;
EnumerableSet.AddressSet Next_Mandate_Candidats;
uint Inauguration_Timestamps;
uint Election_Timestamps;
uint Version;
}
event Governance_Parameters_Updated();
event Legislatif_Parameters_Updated();
event New_Candidat(address Candidat);
event Remove_Candidat(address Candidat);
event Sign();
event New_election(bytes32 Vote_key);
event New_Mandate();
///@dev Function used for updating parameters related to the democratic process of rmembers election. See {Update_Internal_Governance] function of {Delegation} or {IDelegation} contract
function Update_Mandate_Parameter(Mandate_Parameter storage mandate_param, uint Election_Duration, uint Validation_Duration, uint Mandate_Duration, uint Immunity_Duration,
uint16 Next_Mandate_Max_Members, uint16 New_Election_Petition_Rate, address Ivote_address) external {
mandate_param.Election_Duration = Election_Duration;
mandate_param.Validation_Duration = Validation_Duration;
mandate_param.Mandate_Duration = Mandate_Duration;
mandate_param.Immunity_Duration = Immunity_Duration;
mandate_param.Next_Mandate_Max_Members = Next_Mandate_Max_Members;
mandate_param.New_Election_Petition_Rate = New_Election_Petition_Rate;
mandate_param.Ivote_address = Ivote_address;
emit Governance_Parameters_Updated();
}
///@dev Function used for updating parameters related to the democratic process of registers governance. See {Update_Legislatif_Process] function of {Delegation} or {IDelegation} contract
function Update_Law_Parameters(Law_Project_Parameters storage projet_param, uint[6] calldata Uint256_Legislatifs_Arg, uint16 Censor_Proposition_Petition_Rate,
uint16 Censor_Penalty_Rate, address Ivote_address) external {
projet_param.Member_Max_Token_Usage = Uint256_Legislatifs_Arg[0];
projet_param.Law_Initialisation_Price = Uint256_Legislatifs_Arg[1];
projet_param.FunctionCall_Price = Uint256_Legislatifs_Arg[2];
projet_param.Proposition_Duration = Uint256_Legislatifs_Arg[3];
projet_param.Vote_Duration = Uint256_Legislatifs_Arg[4];
projet_param.Law_Censor_Period_Duration = Uint256_Legislatifs_Arg[5];
projet_param.Censor_Proposition_Petition_Rate = Censor_Proposition_Petition_Rate;
projet_param.Censor_Penalty_Rate = Censor_Penalty_Rate;
projet_param.Ivote_address = Ivote_address;
emit Legislatif_Parameters_Updated();
}
/**
* @dev Function called by {End_Election} function of {Delegation} Contract to end the current contract and start a new one.
* @param Mandates mapping of Mandate structure idexed by uint corresponding to their order of apparition
* @param ivote_address Address of IVote contract used by citizens to vote during election.
* @param last_mandate_num Index in {Mandates} mapping of the last mandate
* @param Internal_Governance_Version Version of Parameters ({Mandate_Parameter} structur) u.sed by the current mandate
* */
function Transition_Mandate(mapping (uint=>Mandate) storage Mandates, address ivote_address, uint last_mandate_num, uint Internal_Governance_Version) external{
uint new_mandate_num=last_mandate_num+1;
uint[] memory results;
IVote Vote_Instance = IVote(ivote_address);
results = Vote_Instance.Get_Winning_Propositions(keccak256(abi.encodePacked(address(this),Mandates[last_mandate_num].Election_Timestamps)));
if(results[0]==0){
uint actual_member_length = Mandates[last_mandate_num].Members.length();
for(uint i =0; i<actual_member_length; i++){
Mandates[new_mandate_num].Members.add(Mandates[last_mandate_num].Members.at(i));
}
}else{
for(uint i =0; i<results.length; i++){
Mandates[new_mandate_num].Members.add(Mandates[last_mandate_num].Next_Mandate_Candidats.at(results[i]-1));
}
}
Mandates[new_mandate_num].Inauguration_Timestamps = block.timestamp;
Mandates[new_mandate_num].Version = Internal_Governance_Version;
emit New_Mandate();
}
/**
* @dev Function called by {Candidate_Election} function of {Delegation} contract to add a new account to the list of candidats for next election
* @param mandate Current Mandate object
* @param new_candidat Account to add to the list of candidats
*/
function Add_Candidats(Mandate storage mandate, address new_candidat)external{
require(!mandate.Next_Mandate_Candidats.contains(new_candidat), "Already Candidate");
mandate.Next_Mandate_Candidats.add(new_candidat);
emit New_Candidat(new_candidat);
}
/**
* @dev Function called by {Remove_Candidature} function of {Delegation} contract to remove an account from the list of candidats for next election
* @param mandate Current Mandate object
* @param remove_candidat Account to remove from the list of candidats
*/
function Remove_Candidats(Mandate storage mandate, address remove_candidat)external{
require(mandate.Next_Mandate_Candidats.contains(remove_candidat), "Not Candidate");
mandate.Next_Mandate_Candidats.remove(remove_candidat);
emit Remove_Candidat(remove_candidat);
}
/**
* @dev Function called by {Sign_New_Election_Petition} function of {Delegation} contract to add an account to list petition for revoking current delegation members
* @param mandate Current Mandate object
* @param Immunity_Duration Amount of time after the beginning of a new mandate during which delegation's members can't be revoked
* @param signer Address of account who want to sign the petition
*/
function Sign_Petition(Mandate storage mandate, uint Immunity_Duration, address signer)external{
require(block.timestamp - mandate.Inauguration_Timestamps > Immunity_Duration, "Immunity Period");
require(!mandate.New_Election_Petitions.contains(signer), "Already signed petition");
mandate.New_Election_Petitions.add(signer);
emit Sign();
}
/**
* @dev Function called by {New_Election} function of {Delegation} contract to start a new election
* @param Mandates mapping of Mandate structure idexed by uint corresponding to their order of apparition
* @param mandate_version Mandate_Parameter object corresponding to parameters that are used by current mandate
* @param num_mandate Index of the current mandate in the {Mandates} mapping
* @param citizen_register_address Address of {Citizens_Register} contract used in the current project to handle citizens registration
*/
function New_Election(mapping(uint=>Mandate) storage Mandates, Mandate_Parameter storage mandate_version, uint num_mandate, address citizen_register_address)external returns(bool new_election){
uint candidats_number = Mandates[num_mandate].Next_Mandate_Candidats.length();
Citizens_Register citizen = Citizens_Register(citizen_register_address);
require(candidats_number>0, "No Candidats");
require(Mandates[num_mandate].New_Election_Petitions.length() >= Percentage(mandate_version.New_Election_Petition_Rate, citizen.Get_Citizen_Number()) || (block.timestamp - Mandates[num_mandate].Inauguration_Timestamps) > mandate_version.Mandate_Duration, "New election impossible for now");
if(candidats_number <= mandate_version.Next_Mandate_Max_Members){
uint new_mandate_num = num_mandate+1;
for(uint i =0; i<candidats_number; i++){
Mandates[new_mandate_num].Members.add(Mandates[num_mandate].Next_Mandate_Candidats.at(i));
}
Mandates[new_mandate_num].Inauguration_Timestamps = block.timestamp;
emit New_Mandate();
return false;
}else{
Mandates[num_mandate].Election_Timestamps = block.timestamp;
IVote Vote_Instance = IVote(mandate_version.Ivote_address);
bytes32 key = keccak256(abi.encodePacked(address(this),block.timestamp));
emit New_election(key);
Vote_Instance.Create_Ballot(key, citizen_register_address, Citizens_Register(citizen_register_address).Contains_Function_Selector(), mandate_version.Election_Duration, mandate_version.Validation_Duration, candidats_number, mandate_version.Next_Mandate_Max_Members);
return true;
}
}
/**
* @dev Function called by the constructor function of {Delegation} contract to start the first mandate.
* @param mandate Current Mandate object
* @param Initial_members Members of the first Delegation
*/
function Set_First_Mandate(Mandate storage mandate, address[] memory Initial_members)external{
mandate.Inauguration_Timestamps = block.timestamp;
for(uint i=0; i<Initial_members.length; i++){
mandate.Members.add(Initial_members[i]);
}
mandate.Version= 1;
}
/**
* @dev Utility function for computing Percentage.
* @param ratio The ratio is represented with 2 decimals
* @param base The base's number of decimal is arbitrary
* @return Return the {ratio}% of {base}. The result is represented with the number of decimals of {base}
*/
function Percentage(uint16 ratio, uint base) internal pure returns(uint){
return (ratio*base)/10000 ;// ((ratio*base)/100) * 10^(-ratio_decimals)
}
}
/**
* @notice Delegation contract is an implementation of IDelegation and thus aims at implementing a governance system in which a group of elected accounts is allowed to rule one or more controled registers contract.
*/
contract Delegation is Institution, IDelegation{// Initiative_Legislative{
using EnumerableSet for EnumerableSet.AddressSet;
using SafeMath for uint;
using Initiative_Legislative_Lib for Initiative_Legislative_Lib.Law_Project;
using Delegation_Uils for Delegation_Uils.Mandate_Parameter;
using Delegation_Uils for Delegation_Uils.Mandate;
using Delegation_Uils for Delegation_Uils.Law_Project_Parameters;
/**
* @dev status of a law project
*/
enum Status{
PROPOSITION,
VOTE,
CENSOR_LAW_PERIOD,
ADOPTED,
EXECUTED,
ABORTED
}
/**
* @dev Structure representing parameters related to the democratic process of registers governance.
*
* - Member_Max_Token_Usage: The maximum amount of token a member is allowed to use for a law project elaboration
* - Law_Initialisation_Price: The price in token for creating a law project
* - FunctionCall_Price: The price in token for one FunctionCall.
* - Proposition_Duration: The duration of the stage in which members are allowed to submit propositions
* - Vote_Duration: The duration of the stage in which members are allowed to vote for the proposition they want
* - Law_Censor_Period_Duration: The duration of the stage in which all citizens are allowed to sign a etition against the law project proposed by the Delegation
* - Censor_Proposition_Petition_Rate The minimum ratio of citizens required to cancel a law project
* - Censor_Penalty_Rate Ratio of total amount of token belonged by the delegation that will be lost if a law project is rejected by citizens
* - Ivote_address Address of the IVote contract that will be used during voting stage
*/
struct Law_Project_Parameters{
//uint Revert_Penalty_Limit;
uint Member_Max_Token_Usage;
uint Law_Initialisation_Price;
uint FunctionCall_Price;
uint Proposition_Duration;
uint Vote_Duration;
uint Law_Censor_Period_Duration;
uint16 Censor_Proposition_Petition_Rate;
uint16 Censor_Penalty_Rate;
address Ivote_address;
}
/**
* @dev Structure representing {Register} contract that are controled by the Delegation
* - Active: Whether the register is still under the actual Delegation control in the Constitution.
* - Law_Project_Counter: Number of pending law project related to this register
* The Register can't be removed from delegation's control if there are pending law project related to it. However if {Active} field is false, then we can't start a new law project whose controled register is the current one.
*/
struct Controlable_Register{
bool Active;
uint Law_Project_Counter;
}
/**
* @dev Structure representing a law project
* - Institution_Address: Address of register being concerned by this law project
* - Law_Project_Status: Status ({Status} structure) of the law project
* - Version: Version of Parameters ({Law_Project_Parameters} structure) used by the current law project
* - Creation_Timestamp: Beginning of current law project
* - Start_Vote_Timestamps: Beginning of voting stage
* - Start_Censor_Law_Period_Timestamps: Beginning of law project censorable stage
* - Law_Total_Potentialy_Lost: Amount of token that could be lost in penalty fee if all pending law project were to be censored by citizens petition
* - Censor_Law_Petition_Counter: Number of citizens that have signed the petition to censor the current law project
* - Censor_Law_Petitions: List of citizens that have signed the petition to censor the current law project
* - Members_Token_Consumption: Mapping of the amount of token consummed by each member of the delegation
*/
struct Delegation_Law_Project{
address Institution_Address;
Status Law_Project_Status;
uint Version;
uint Creation_Timestamp;
uint Start_Vote_Timestamps;
uint Start_Censor_Law_Period_Timestamps;
uint Law_Total_Potentialy_Lost;
uint Censor_Law_Petition_Counter;
mapping(address=>bool) Censor_Law_Petitions;
mapping(address=>uint) Members_Token_Consumption;
}
modifier Citizen_Only{
require(Citizens.Contains(msg.sender),"Citizen Only");
_;
}
modifier Delegation_Only{
require(Mandates[Actual_Mandate].Members.contains(msg.sender), "Delegation Only");
_;
}
event Governance_Parameters_Updated();
event Legislatif_Parameters_Updated();
event New_Candidat(address Candidat);
event Remove_Candidat(address Candidat);
event Sign();
event New_election(bytes32 Vote_key);
event New_Mandate();
event Controled_Register_Added(address register);
event Controled_Register_Canceled(address register);
event Controled_Register_Removed(address register);
event New_Law(bytes32 key);
event New_Proposal(bytes32 key, uint proposal_index);
event Proposal_Modified(bytes32 key, uint proposal_index);
event Voting_Stage_Started(bytes32 law_project, bytes32 key);
event Voting_Stage_Achieved(bytes32 key);
event Law_Aborted(bytes32 key);
event Law_Adopted(bytes32 key);
event Law_executed(bytes32 key);
event Function_Call_Executed( bytes32 key, uint num_function_call_ToExecute);
//event New_Proposal(bytes32 key, uint num);
/// @dev function selector of {Contains} function used to check Whether an account is member of the delegation
bytes4 constant Contains_Function_Selector = 0x57f98d32;
///@dev Instance of the {DemoCoin} token used by the Project
DemoCoin Democoin;
///@dev Instance of the {Citizens_Register} contract used by the Project
Citizens_Register Citizens;
//dev Address of the {Agora} contract used by the Project
address Agora_address;
///@dev Total amount of token potentially lost via penalty fee.
uint Potentialy_Lost_Amount;
/*Legislatif Process*/
/** @dev Mapping of {Law_Project} structure ({Initiative_Legislative_Lib} library)
*
* */
mapping(bytes32 => Initiative_Legislative_Lib.Law_Project) public List_Law_Project;
///@dev Mapping of Registers ({Controlable_Register} structure) that can receive orders from the actual Delegation
mapping(address=>Controlable_Register) public Controled_Registers;
/// @dev List of Controled Registers
EnumerableSet.AddressSet List_Controled_Registers;
///@dev Mapping of {Delegation_Law_Project} structure corresponding to law project of delegation (pending, aborted and passed)
mapping(bytes32=>Delegation_Law_Project) public Delegation_Law_Projects;
///@dev List of law projects
bytes32[] List_Delegation_Law_Projects;
///@dev Mapping of versions of Parameters ({Law_Project_Parameters} of {Delegation_Uils} library) used for law project process
mapping(uint=>Delegation_Uils.Law_Project_Parameters) public Law_Parameters_Versions;
/*Internal Governance*/
///@dev Mapping of {Mandate} structure ({Delegation_Uils} library) corresponding to mandates of delegation (pending and passed)
mapping(uint=>Delegation_Uils.Mandate) Mandates;
///@dev Mapping of versions of Parameters ({Mandate_Parameter} of {Delegation_Uils} library) used for delegation internal governance.
mapping(uint=>Delegation_Uils.Mandate_Parameter) public Mandates_Versions;
///@dev Current version of parameters related to law project process
uint Legislatif_Process_Version;
///@dev Current version of parameters related to delegation internal governance
uint Internal_Governance_Version;
/// @dev Id in {Mandate} mapping of the current mandate
uint Actual_Mandate;
/// @dev Boolean set whether we are in election stage or not.
bool In_election_stage;
/**
* @param Name name of the Institution
* @param Initial_members List of initial members of the delegation
* @param token_address Address of {DemoCoin} token that will be used to transfert initial token amount to new registered citizens
* @param citizen_address Address of the {Citizens_Register} contract used in the Project
* @param agora_address Address of the {Agora} contract used in the project.
*/
constructor(string memory Name, address[] memory Initial_members, address token_address, address citizen_address, address agora_address) Institution(Name) {
Type_Institution = Institution_Type.DELEGATION;
Democoin = DemoCoin(token_address);
Citizens = Citizens_Register(citizen_address);
Agora_address = agora_address;
Mandates[0].Set_First_Mandate( Initial_members);
}
/*Members Election related functions*/
/**
* @dev Function called by a citizen who wish to candidate to next mandate's elections.
*/
function Candidate_Election() external override Citizen_Only{
require(!In_election_stage, "Election Time");
Mandates[Actual_Mandate].Add_Candidats(msg.sender);
emit New_Candidat(msg.sender);
}
/**
* @dev Function called by a citizen who wish to remove his candidature from next mandate's elections.
*/
function Remove_Candidature()external override{
require(!In_election_stage, "Election Time");
Mandates[Actual_Mandate].Remove_Candidats(msg.sender);
emit Remove_Candidat(msg.sender);
}
/**
* @dev When the current mandate duration is over or if the {New_Election_Petition_Rate} (see {Mandate} struct of {Delegation_Uils} library) is reached, any citizen can call this function to start a new election
*/
function New_Election() external override Citizen_Only {
require(!In_election_stage, "An Election is Pending");
uint num_mandate = Actual_Mandate;
if(Delegation_Uils.New_Election(Mandates,Mandates_Versions[Mandates[num_mandate].Version], num_mandate, address(Citizens))){
In_election_stage= true;
emit New_election(keccak256(abi.encodePacked(address(this),block.timestamp)));
}else{
uint new_mandate_num = num_mandate+1;
Actual_Mandate = new_mandate_num;
Mandates[new_mandate_num].Version = Internal_Governance_Version;
emit New_Mandate();
}
}
/**
* @dev Function can be called by a citizen to sign petition for a new election
*/
function Sign_New_Election_Petition() external override Citizen_Only{
uint num_mandate = Actual_Mandate;
Mandates[num_mandate].Sign_Petition(Mandates_Versions[Mandates[num_mandate].Version].Immunity_Duration, msg.sender);
emit Sign();
}
/**
* @dev When voting stage is over, any citizen can call this function to end the election and start a new mandate.
*/
function End_Election()external override {
require(In_election_stage, "Not in Election time");
uint num_mandate = Actual_Mandate;
//uint new_num_mandate = num_mandate.add(1);
In_election_stage=false;
Actual_Mandate = num_mandate + 1;
emit New_Mandate();
Delegation_Uils.Transition_Mandate(Mandates, Mandates_Versions[Mandates[num_mandate].Version].Ivote_address, num_mandate, Internal_Governance_Version);
}
/*Legislatif Process related functions*/
/**
* @dev Function can be called by a delegation member to submit a new law project. This function put {Law_Initialisation_Price} (see {Law_Project_Parameters} struct of {Delegation_Uils library}) DemoCoin token of Delegation contract in Escrow.
* @param register_address Address of the register contract the law project is about. Must be contained in Controled_Registers mapping.
* @param Title Title of the law project. Can be an hash.
* @param Description Text explaining the spirit and generals goals of the law project. Can be an hash.
*/
function Add_Law_Project(address register_address, bytes calldata Title, bytes calldata Description)external override Delegation_Only{
//_Update_Law_Project();
require(Controled_Registers[register_address].Active, "Register Not Controled");
bytes32 key = keccak256(abi.encode(Title,Description));
require(Delegation_Law_Projects[key].Version==0,"Law project already created");
uint version =Legislatif_Process_Version;
Delegation_Law_Projects[key].Version = version;
Token_Consumption_Handler(msg.sender, Law_Parameters_Versions[version].Law_Initialisation_Price, key);
Delegation_Law_Projects[key].Institution_Address = register_address;
Delegation_Law_Projects[key].Creation_Timestamp = block.timestamp;
List_Delegation_Law_Projects.push(key);
List_Law_Project[key].Title = Title;
List_Law_Project[key].Description = Description;
Controled_Registers[register_address].Law_Project_Counter++;
emit New_Law(key);
}
/**
* @dev Function can be called by a delegation member to submit a corpus of function calls propositions to an existing pending law project. This function put in Escrow {FunctionCall_Price} (see {Law_Project_Parameters} struct of {Delegation_Uils library}) DemoCoin token
* multiplied by the number of function call contained in the proposition.
* @param law_project Id of the law project hte caller wants to add a proposition to. The Id is obtained by hashing the Title with the Description of the law project.
* @param Parent Proposition Id the caller wants to attach his proposition to. It's the parent proposition in the proposal tree. If there isn't any proposition in the tree we want to attach the new proposition to, we set Parent to 0
* @param Parent_Proposals_Reuse List of Parent's function calls index we want to reuse in the new proposition. Function calls are ordered in the order we want them to be executed. 0 elements correspond to new function calls that have to be added by the caller in {New_Function_Call} argument.
* @param New_Function_Call List of new function calls added by the caller. For each element of the New_Function_Call array, caller must set a 0 element in {Parent_Proposals_Reuse} array at the index he want the custom function call to be positioned
* @param Description Text to justify the new proposal. Can be an hash.
*/
function Add_Proposal(bytes32 law_project, uint Parent, uint[] calldata Parent_Proposals_Reuse, bytes[] calldata New_Function_Call, bytes calldata Description) external override Delegation_Only{
require(Delegation_Law_Projects[law_project].Law_Project_Status == Status.PROPOSITION, "Not at PROPOSITION status");
uint version = Delegation_Law_Projects[law_project].Version;
require( version != 0, "No existing Law Project");
Token_Consumption_Handler(msg.sender, Law_Parameters_Versions[version].FunctionCall_Price.mul(New_Function_Call.length), law_project);
uint proposal_index = List_Law_Project[law_project].Proposal_Count.add(1);
List_Law_Project[law_project].Proposals_Tree[proposal_index].Author = msg.sender;
List_Law_Project[law_project].Add_Corpus_Proposal(Parent, Parent_Proposals_Reuse, New_Function_Call, Description);
emit New_Proposal( law_project, proposal_index);
}
/**
* @dev Function can be called by a delegation member to add function calls to a proposition that he has already created (He have to be the author of the proposition).
* Caller must approve {FunctionCall_Price} (see {Law_Project_Parameters} struct of {Delegation_Uils library})
* multiplied by the number of function call he wants to add to the proposition, token for Delegation contract.
* @param law_project Id of the law project the caller wants to add a proposition to. The Id is obtained by hashing the Title with the Description of the law project.
* @param Proposal Proposition Id to modify.
* @param New_Items Array of new function calls to add to the Proposition.
* @param Indexs array of Proposition's function call list indexs to inser new function call (contained in {New_Items}) to. {New_Items} and {Indexs} have the same length.
*/
function Add_Item(bytes32 law_project, uint Proposal, bytes[] calldata New_Items, uint[] calldata Indexs) external override Delegation_Only{
require(Delegation_Law_Projects[law_project].Law_Project_Status == Status.PROPOSITION, "Law Not at PROPOSITION status");
uint version = Delegation_Law_Projects[law_project].Version;
require( version != 0, "No existing Law Project");
Token_Consumption_Handler(msg.sender, Law_Parameters_Versions[version].FunctionCall_Price.mul(New_Items.length), law_project);
List_Law_Project[law_project].Add_Item_Proposal( Proposal, New_Items, Indexs, msg.sender);
emit Proposal_Modified(law_project, Proposal);
}
/**
* @dev When the period of proposition submiting is over, any citizen can call this function to start the voting stage. The Id of the ballot corresponding to current law project the IVote contract is computed by hashing {law_project} Id with current block timestamps.
* @param law_project Id of the law project the caller wants to add a proposition to. The Id is obtained by hashing the Title with the Description of the law project.
*/
function Start_Vote(bytes32 law_project)external override Delegation_Only{
uint version = Delegation_Law_Projects[law_project].Version;
require( version != 0, "No existing Law Project");
require(Delegation_Law_Projects[law_project].Law_Project_Status == Status.PROPOSITION, "Law Not at PROPOSITION status");
require(block.timestamp.sub(Delegation_Law_Projects[law_project].Creation_Timestamp) > Law_Parameters_Versions[version].Proposition_Duration, "PROPOSITION stage not finished");
bytes32 key=keccak256(abi.encodePacked(law_project,block.timestamp));
Delegation_Law_Projects[law_project].Start_Vote_Timestamps = block.timestamp;
Delegation_Law_Projects[law_project].Law_Project_Status = Status.VOTE;
emit Voting_Stage_Started(law_project, key);
IVote Vote_Instance = IVote(Law_Parameters_Versions[version].Ivote_address);
Vote_Instance.Create_Ballot(key, address(this), Contains_Function_Selector, Law_Parameters_Versions[version].Vote_Duration,0, List_Law_Project[law_project].Proposal_Count, 1);
}
/**
* @dev When the voting period is over, any citizen can call this function to end the voting stage. If the winning proposition is the default proposition is the default one (Proposition 0) the law proejct is aborted. Otherwise, the Law Censoring stage is started.
* @param law_project Id of the law project the caller wants to add a proposition to. The Id is obtained by hashing the Title with the Description of the law project.
*/
function Achiev_Vote(bytes32 law_project) external override Delegation_Only{
IVote Vote_Instance = IVote(Law_Parameters_Versions[Delegation_Law_Projects[law_project].Version].Ivote_address);
bytes32 key = keccak256(abi.encodePacked(law_project,Delegation_Law_Projects[law_project].Start_Vote_Timestamps));
uint winning_proposal= Vote_Instance.Get_Winning_Proposition_byId(key,0);
List_Law_Project[law_project].Winning_Proposal = winning_proposal;
if(winning_proposal==0){
Delegation_Law_Projects[law_project].Law_Project_Status = Status.ABORTED;
emit Law_Aborted(law_project);
}else{
Delegation_Law_Projects[law_project].Start_Censor_Law_Period_Timestamps = block.timestamp;
Delegation_Law_Projects[law_project].Law_Project_Status = Status.CENSOR_LAW_PERIOD;
emit Voting_Stage_Achieved(law_project);
}
}
/**
* @dev If we are at the Law censor stage, any citizen can call this function to sign the petition for canceling the law project. If the {Censor_Proposition_Petition_Rate} (see {Law_Project_Parameters} structure) is reached, the law project is aborted.
* @param law_project Id of the law project the caller wants to add a proposition to. The Id is obtained by hashing the Title with the Description of the law project.
*/
function Censor_Law(bytes32 law_project)external override Citizen_Only{
require(Delegation_Law_Projects[law_project].Law_Project_Status == Status.CENSOR_LAW_PERIOD, "Law Not at CENSOR LAW status");
require(!Delegation_Law_Projects[law_project].Censor_Law_Petitions[msg.sender], "Already Signed");
uint counter =Delegation_Law_Projects[law_project].Censor_Law_Petition_Counter.add(1);
Delegation_Law_Projects[law_project].Censor_Law_Petitions[msg.sender]=true;
if(counter>= Percentage(Law_Parameters_Versions[Delegation_Law_Projects[law_project].Version].Censor_Proposition_Petition_Rate, Citizens.Get_Citizen_Number())){ //If the number of censure petitions signatures reach the minimum ratio.
uint law_total_potentialy_lost = Delegation_Law_Projects[law_project].Law_Total_Potentialy_Lost;
Delegation_Law_Projects[law_project].Law_Project_Status = Status.ABORTED;
Potentialy_Lost_Amount = Potentialy_Lost_Amount.sub(law_total_potentialy_lost);
Update_Controled_Registers(Delegation_Law_Projects[law_project].Institution_Address);
Democoin.transfer(Agora_address,law_total_potentialy_lost);
emit Law_Aborted(law_project);
}
Delegation_Law_Projects[law_project].Censor_Law_Petition_Counter = counter;
}
/**
* @dev If the Law censor period is over and the law project hasn't been rejected by citizens, then any delegation member can call this function to set the law project as ADOPTED (see {Status} enumeration).
* @param law_project Id of the law project the caller wants to add a proposition to. The Id is obtained by hashing the Title with the Description of the law project.
*/
function Adopt_Law(bytes32 law_project)external override Delegation_Only{
require(Delegation_Law_Projects[law_project].Law_Project_Status == Status.CENSOR_LAW_PERIOD, "Law Not at CENSOR LAW status");
require(block.timestamp.sub(Delegation_Law_Projects[law_project].Start_Censor_Law_Period_Timestamps) > Law_Parameters_Versions[Delegation_Law_Projects[law_project].Version].Law_Censor_Period_Duration, "CENSOR LAW PERIOD not over");
Delegation_Law_Projects[law_project].Law_Project_Status = Status.ADOPTED;
emit Law_Adopted(law_project);
}
/**
* @dev Once the law project has been adopted (ADOPTED value of {Status} enum) then any delegation member can call this function to execute all or some of the remaining function call of the winning proposition.
* For the law project to be fully executed all function call have to be executed.
* @param law_project Id of the law project the caller wants to add a proposition to. The Id is obtained by hashing the Title with the Description of the law project.
* @param num_function_call_ToExecute Number of function calls to execute.
*/
function Execute_Law(bytes32 law_project, uint num_function_call_ToExecute)external override Delegation_Only nonReentrant{
require(Delegation_Law_Projects[law_project].Law_Project_Status == Status.ADOPTED, "Law Not ADOPTED");
emit Function_Call_Executed( law_project, num_function_call_ToExecute);
if(List_Law_Project[law_project].Execute_Winning_Proposal(num_function_call_ToExecute, Delegation_Law_Projects[law_project].Institution_Address)){
Delegation_Law_Projects[law_project].Law_Project_Status = Status.EXECUTED;
Potentialy_Lost_Amount = Potentialy_Lost_Amount.sub(Delegation_Law_Projects[law_project].Law_Total_Potentialy_Lost);
Update_Controled_Registers(Delegation_Law_Projects[law_project].Institution_Address);
emit Law_executed(law_project);
}
}
/*Constitution_Only Delegation parameters initialisation*/
/**
* @dev See {IDelegation} interface
*/
function Update_Legislatif_Process(uint[6] calldata Uint256_Legislatifs_Arg, uint16 Censor_Proposition_Petition_Rate,
uint16 Censor_Penalty_Rate, address Ivote_address)external override Constitution_Only{
uint version = Legislatif_Process_Version.add(1);
Law_Parameters_Versions[version].Update_Law_Parameters(Uint256_Legislatifs_Arg, Censor_Proposition_Petition_Rate,
Censor_Penalty_Rate, Ivote_address);
/*Law_Parameters_Versions[version].Member_Max_Token_Usage = Uint256_Legislatifs_Arg[0];
Law_Parameters_Versions[version].Law_Initialisation_Price = Uint256_Legislatifs_Arg[1];
Law_Parameters_Versions[version].FunctionCall_Price = Uint256_Legislatifs_Arg[2];
Law_Parameters_Versions[version].Proposition_Duration = Uint256_Legislatifs_Arg[3];
Law_Parameters_Versions[version].Vote_Duration = Uint256_Legislatifs_Arg[4];
Law_Parameters_Versions[version].Law_Censor_Period_Duration = Uint256_Legislatifs_Arg[5];
Law_Parameters_Versions[version].Censor_Proposition_Petition_Rate = Censor_Proposition_Petition_Rate;
Law_Parameters_Versions[version].Censor_Penalty_Rate = Censor_Penalty_Rate;
Law_Parameters_Versions[version].Ivote_address = Ivote_address;*/
Legislatif_Process_Version = version;
emit Legislatif_Parameters_Updated();
}
/**
* @dev See {IDelegation} interface
*/
function Update_Internal_Governance( uint Election_Duration, uint Validation_Duration, uint Mandate_Duration, uint Immunity_Duration,
uint16 Num_Max_Members, uint16 New_Election_Petition_Rate, address Ivote_address)external override Constitution_Only{
uint version = Internal_Governance_Version.add(1);
Mandates_Versions[version].Update_Mandate_Parameter(Election_Duration, Validation_Duration, Mandate_Duration, Immunity_Duration,
Num_Max_Members, New_Election_Petition_Rate, Ivote_address);
/*Mandates_Versions[version].Election_Duration = Election_Duration;
Mandates_Versions[version].Validation_Duration = Validation_Duration;
Mandates_Versions[version].Mandate_Duration = Mandate_Duration;
Mandates_Versions[version].Immunity_Duration = Immunity_Duration;
Mandates_Versions[version].Num_Max_Members = Num_Max_Members;
Mandates_Versions[version].New_Election_Petition_Rate = New_Election_Petition_Rate;
Mandates_Versions[version].Ivote_address = Ivote_address;*/
Internal_Governance_Version = version;
emit Governance_Parameters_Updated();
}
/**
* @dev See {IDelegation} interface
* */
function Add_Controled_Register(address register_address) external override Constitution_Only {
require(!Controled_Registers[register_address].Active, "Register already Controled");
Controled_Registers[register_address].Active = true;
List_Controled_Registers.add(register_address);
emit Controled_Register_Added(register_address);
}
/**
* @dev See {IDelegation} interface
* */
function Remove_Controled_Register(address register_address) external override Constitution_Only {
require(Controled_Registers[register_address].Active, "Register Not Controled");
Controled_Registers[register_address].Active = false;
if(Controled_Registers[register_address].Law_Project_Counter ==0){
Register(register_address).Remove_Authority(address(this));
List_Controled_Registers.remove(register_address);
emit Controled_Register_Removed(register_address);
}else{
emit Controled_Register_Canceled(register_address);
}
}
/*Utils*/
/**
* @notice Handle token consumption in the context of law project elaboration
* @dev The function: check that:
* - check that the member's max token consumption limit for the current law project isn't exceeded by the sender
* - check that the Delegation has enough funds to afford penalties if current pending were to be reverted by citizens.
* - Update the value of the amount of token consumed by the sender for the law project identified by "key".
* - Update the "Law_Total_Potentialy_Lost" field of the corresponding "Delegation_Law_Project" struct.
* - Update the "Potentialy_Lost_Amount" state variable
*
* @param sender Address of the sender of the transaction
* @param amount Amount of DemoCoin sent in the transaction
* @param key Id of the law project
* */
function Token_Consumption_Handler(address sender, uint amount, bytes32 key) internal{
uint version = Delegation_Law_Projects[key].Version;
require(Delegation_Law_Projects[key].Members_Token_Consumption[sender] +amount <= Law_Parameters_Versions[version].Member_Max_Token_Usage, "Member consumption exceeded");
uint amount_potentialy_lost = Percentage(Law_Parameters_Versions[version].Censor_Penalty_Rate, amount);
uint new_potentialy_lost_amount = Potentialy_Lost_Amount.add(amount_potentialy_lost);
require(new_potentialy_lost_amount <= Democoin.balanceOf(address(this)), "No enough colaterals funds");
Delegation_Law_Projects[key].Members_Token_Consumption[sender] += amount;
Delegation_Law_Projects[key].Law_Total_Potentialy_Lost = Delegation_Law_Projects[key].Law_Total_Potentialy_Lost.add(amount_potentialy_lost);
Potentialy_Lost_Amount = new_potentialy_lost_amount;
}
/**
* @dev Decrease the counter ("Law_Project_Counter" field of Controlable_Register struct) of pending law project related to the register of address "institution_address". If the counter becomes null and the "Actual" field of Controlable_Registers struct is false,
* then the corresponding register is removed from List_Controled_Registers and the delegation removes it self from the register's Authorithies list ("Register_Authorities" state variable)
* @param institution_address Address of the controled register to be updated.
*/
function Update_Controled_Registers(address institution_address) internal{
uint counter = Controled_Registers[institution_address].Law_Project_Counter.sub(1);
Controled_Registers[institution_address].Law_Project_Counter = counter;
if(counter==0 && !Controled_Registers[institution_address].Active){
Register(institution_address).Remove_Authority(address(this));
List_Controled_Registers.remove(institution_address);
}
}
/*Getters*/
/**
* @dev See {IDelegation} interface
*
*/
function Contains(address member_address) external view override returns(bool contain){
return Mandates[Actual_Mandate].Members.contains(member_address);
}
/**
* @dev Get 2 arrays:
* - The list of law project Id
* - The list of controled Register
* @return Law_Project_List List of law project (pending, executed and aborted)
* @return Controled_Register List of register address (represented in bytes32) whose contract is under Delegation control
*/
function Get_List_Law_Register()external view returns(bytes32[] memory Law_Project_List, bytes32[] memory Controled_Register ){
return (List_Delegation_Law_Projects, List_Controled_Registers._inner._values);
}
/**
* @dev Get informations about a mandate
* @param Id Id of the mandate
* @return version Parameter Version used for this mandate
* @return Inauguration_Timestamps Inauguration_Timestamps: Beginning of current mandate
* @return Election_Timestamps Beginning of election
* @return New_Election_Petition_Number Number of signatures obtained for revoking the delegation members related to {Id} Mandate
* @return Members Array of {Id} mandate delegation member's address (represented in bytes32)
* @return Candidats Array candidats address (represented in bytes32)
*/
function Get_Mandate(uint Id)external view returns(uint version, uint Inauguration_Timestamps, uint Election_Timestamps, uint New_Election_Petition_Number, bytes32[] memory Members, bytes32[] memory Candidats){
version = Mandates[Id].Version;
Inauguration_Timestamps = Mandates[Id].Inauguration_Timestamps;
Election_Timestamps= Mandates[Id].Election_Timestamps;
New_Election_Petition_Number=Mandates[Id].New_Election_Petitions.length();
Members = Mandates[Id].Members._inner._values;
Candidats = Mandates[Id].Next_Mandate_Candidats._inner._values;
}
/**
* @dev Get the amount of DemoCoin token owned by the Delegation and used by a Delegation member for a specific delegation law project.
* @param key Id of law project
* @param member Address of delegation member
* @return amount Amount of token used by {member} address for {key} law project
*
*/
function Get_Member_Amount_Consumed(bytes32 key, address member)external view returns(uint amount){
return Delegation_Law_Projects[key].Members_Token_Consumption[member];
}
/**
* @dev Get various Delegation state variables values.
* @return legislatif_process_version Current version of parameters related to delegation law project process.
* @return internal_governance_version Current version of parameters related to delegation internal governance.
* @return actual_mandate Id number of the current mandate
* @return potentialy_lost_amount Total amount of token potentially lost via penalty fee.
* @return in_election_stage Boolean assesing whether we are in election stage or not.
*/
function Get_Delegation_Infos()external view returns (uint legislatif_process_version, uint internal_governance_version, uint actual_mandate, uint potentialy_lost_amount, bool in_election_stage){
return (Legislatif_Process_Version, Internal_Governance_Version, Actual_Mandate, Potentialy_Lost_Amount, In_election_stage);
}
/**
* @dev Get informations about a law project proposition
* @param key Id of the law project
* @param id Id of the proposition
* @return description Description of the proposition
* @return childrens Proposition node's children in the Proposal Tree. (See {Add_Corpus_Proposal} function of {Initiative_Legislative_Lib} library)
* @return function_calls List of function calls proposed by the proposition
* @return func_call_counter Number of function calls proposed by the proposition.
* @return parent Id of the proposition's parent in the Proposal Tree
* @return author Address of the author of the proposition.
*/
function Get_Proposal(bytes32 key, uint id)external view returns(bytes memory description, uint[] memory childrens, bytes[] memory function_calls, uint func_call_counter, uint parent, address author){
function_calls = List_Law_Project[key].Get_Proposal_FunctionCall_List(id);
(description, childrens,func_call_counter, parent, author) = List_Law_Project[key].Get_Proposal_Infos(id);
}
/**
* @dev Get Results of a law project
* @return Winning_Proposal Id of the proposition that has been voted.
* @return Receipts List of receipts of {Winning_Proposal} function call's execution.
*/
function Get_Law_Results(bytes32 key)external view returns(uint Winning_Proposal, Initiative_Legislative_Lib.Function_Call_Result[] memory Receipts){
return(List_Law_Project[key].Winning_Proposal, List_Law_Project[key].Function_Call_Receipts);
}
}
| Get various Delegation state variables values. return legislatif_process_version Current version of parameters related to delegation law project process. return internal_governance_version Current version of parameters related to delegation internal governance. return actual_mandate Id number of the current mandate return potentialy_lost_amount Total amount of token potentially lost via penalty fee. return in_election_stage Boolean assesing whether we are in election stage or not./ | function Get_Delegation_Infos()external view returns (uint legislatif_process_version, uint internal_governance_version, uint actual_mandate, uint potentialy_lost_amount, bool in_election_stage){
return (Legislatif_Process_Version, Internal_Governance_Version, Actual_Mandate, Potentialy_Lost_Amount, In_election_stage);
}
| 12,618,302 |
./full_match/5/0x2743d6F0fb1E4CCb768D4530841d35dC44C59789/sources/contracts/extension/upgradeable/PermissionsEnumerable.sol | Returns the PermissionsEnumerable storage. | function _permissionsEnumerableStorage() internal pure returns (PermissionsEnumerableStorage.Data storage data) {
data = PermissionsEnumerableStorage.data();
}
| 11,603,080 |
./full_match/84531/0x9E8962EdF2f07DcA542f6C51d07Fcf6DFf17E8af/sources/votewithfrens.sol | Modified function to get vote options and votes by Proposal index | function getVoteOptionsAndVotesByProposal(address _address, uint256 index, bool isActive) public view returns (string[] memory voteOptions, uint256[] memory voteCounts) {
require(index < (isActive ? activeProposals[_address].length : inactiveProposals[_address].length), "Index out of bounds");
Proposal storage proposal = isActive ? activeProposals[_address][index] : inactiveProposals[_address][index];
voteOptions = proposal.voteOptions;
voteCounts = proposal.voteCounts;
return (voteOptions, voteCounts);
}
| 11,516,268 |
pragma solidity 0.5.11;
/**
* @title OUSD Vault Contract
* @notice The Vault contract stores assets. On a deposit, OUSD will be minted
and sent to the depositor. On a withdrawal, OUSD will be burned and
assets will be sent to the withdrawer. The Vault accepts deposits of
interest form yield bearing strategies which will modify the supply
of OUSD.
* @author Origin Protocol Inc
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
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.
*
* _Available since v2.4.0._
*/
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.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
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.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
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);
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view 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 returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public 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 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 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 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 {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_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 {
require(account != address(0), "ERC20: mint to the zero address");
_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 {
require(account != address(0), "ERC20: burn from the zero address");
_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 is 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 {
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 Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
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));
}
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.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "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");
}
}
}
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @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].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
contract Governable {
// Storage position of the owner and pendingOwner of the contract
bytes32
private constant governorPosition = 0x7bea13895fa79d2831e0a9e28edede30099005a50d652d8957cf8a607ee6ca4a;
//keccak256("OUSD.governor");
bytes32
private constant pendingGovernorPosition = 0x44c4d30b2eaad5130ad70c3ba6972730566f3e6359ab83e800d905c61b1c51db;
//keccak256("OUSD.pending.governor");
event PendingGovernorshipTransfer(
address indexed previousGovernor,
address indexed newGovernor
);
event GovernorshipTransferred(
address indexed previousGovernor,
address indexed newGovernor
);
/**
* @dev Initializes the contract setting the deployer as the initial Governor.
*/
constructor() internal {
_setGovernor(msg.sender);
emit GovernorshipTransferred(address(0), _governor());
}
/**
* @dev Returns the address of the current Governor.
*/
function governor() public view returns (address) {
return _governor();
}
function _governor() internal view returns (address governorOut) {
bytes32 position = governorPosition;
assembly {
governorOut := sload(position)
}
}
function _pendingGovernor()
internal
view
returns (address pendingGovernor)
{
bytes32 position = pendingGovernorPosition;
assembly {
pendingGovernor := sload(position)
}
}
/**
* @dev Throws if called by any account other than the Governor.
*/
modifier onlyGovernor() {
require(isGovernor(), "Caller is not the Governor");
_;
}
/**
* @dev Returns true if the caller is the current Governor.
*/
function isGovernor() public view returns (bool) {
return msg.sender == _governor();
}
function _setGovernor(address newGovernor) internal {
bytes32 position = governorPosition;
assembly {
sstore(position, newGovernor)
}
}
function _setPendingGovernor(address newGovernor) internal {
bytes32 position = pendingGovernorPosition;
assembly {
sstore(position, newGovernor)
}
}
/**
* @dev Transfers Governance of the contract to a new account (`newGovernor`).
* Can only be called by the current Governor. Must be claimed for this to complete
* @param _newGovernor Address of the new Governor
*/
function transferGovernance(address _newGovernor) external onlyGovernor {
_setPendingGovernor(_newGovernor);
emit PendingGovernorshipTransfer(_governor(), _newGovernor);
}
/**
* @dev Claim Governance of the contract to a new account (`newGovernor`).
* Can only be called by the new Governor.
*/
function claimGovernance() external {
require(
msg.sender == _pendingGovernor(),
"Only the pending Governor can complete the claim"
);
_changeGovernor(msg.sender);
}
/**
* @dev Change Governance of the contract to a new account (`newGovernor`).
* @param _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);
}
}
interface IBasicToken {
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
interface IMinMaxOracle {
//Assuming 8 decimals
function priceMin(string calldata symbol) external returns (uint256);
function priceMax(string calldata symbol) external returns (uint256);
}
interface IViewMinMaxOracle {
function priceMin(string calldata symbol) external view returns (uint256);
function priceMax(string calldata symbol) external view returns (uint256);
}
interface IStrategy {
/**
* @dev Deposit the given asset to Lending platform.
* @param _asset asset address
* @param _amount Amount to deposit
*/
function deposit(address _asset, uint256 _amount)
external
returns (uint256 amountDeposited);
/**
* @dev Withdraw given asset from Lending platform
*/
function withdraw(
address _recipient,
address _asset,
uint256 _amount
) external returns (uint256 amountWithdrawn);
/**
* @dev Returns the current balance of the given asset.
*/
function checkBalance(address _asset)
external
view
returns (uint256 balance);
/**
* @dev Returns bool indicating whether strategy supports asset.
*/
function supportsAsset(address _asset) external view returns (bool);
/**
* @dev Liquidate all assets in strategy and return them to Vault.
*/
function liquidate() external;
/**
* @dev Get the APR for the Strategy.
*/
function getAPR() external view returns (uint256);
/**
* @dev Collect reward tokens from the Strategy.
*/
function collectRewardToken() external;
}
library Helpers {
/**
* @notice Fetch the `symbol()` from an ERC20 token
* @dev Grabs the `symbol()` from a contract
* @param _token Address of the ERC20 token
* @return string Symbol of the ERC20 token
*/
function getSymbol(address _token) internal view returns (string memory) {
string memory symbol = IBasicToken(_token).symbol();
return symbol;
}
/**
* @notice Fetch the `decimals()` from an ERC20 token
* @dev Grabs the `decimals()` from a contract and fails if
* the decimal value does not live within a certain range
* @param _token Address of the ERC20 token
* @return uint256 Decimals of the ERC20 token
*/
function getDecimals(address _token) internal view returns (uint256) {
uint256 decimals = IBasicToken(_token).decimals();
require(
decimals >= 4 && decimals <= 18,
"Token must have sufficient decimal places"
);
return decimals;
}
}
contract InitializableERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
* @notice To avoid variable shadowing appended `Arg` after arguments name.
*/
function _initialize(
string memory nameArg,
string memory symbolArg,
uint8 decimalsArg
) internal {
_name = nameArg;
_symbol = symbolArg;
_decimals = decimalsArg;
}
/**
* @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.
*
* 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;
}
}
contract InitializableToken is ERC20, InitializableERC20Detailed {
/**
* @dev Initialization function for implementing contract
* @notice To avoid variable shadowing appended `Arg` after arguments name.
*/
function _initialize(string memory _nameArg, string memory _symbolArg)
internal
{
InitializableERC20Detailed._initialize(_nameArg, _symbolArg, 18);
}
}
contract OUSD is Initializable, InitializableToken, Governable {
using SafeMath for uint256;
using StableMath for uint256;
event TotalSupplyUpdated(
uint256 totalSupply,
uint256 totalCredits,
uint256 creditsPerToken
);
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 private _totalSupply;
uint256 private totalCredits;
// Exchange rate between internal credits and OUSD
uint256 private creditsPerToken;
mapping(address => uint256) private _creditBalances;
// Allowances denominated in OUSD
mapping(address => mapping(address => uint256)) private _allowances;
address public vaultAddress = address(0);
function initialize(
string calldata _nameArg,
string calldata _symbolArg,
address _vaultAddress
) external onlyGovernor initializer {
InitializableToken._initialize(_nameArg, _symbolArg);
_totalSupply = 0;
totalCredits = 0;
creditsPerToken = 1e18;
vaultAddress = _vaultAddress;
}
/**
* @dev Verifies that the caller is the Savings Manager contract
*/
modifier onlyVault() {
require(vaultAddress == msg.sender, "Caller is not the Vault");
_;
}
/**
* @return The total supply of OUSD.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param _account The address to query the balance of.
* @return A unit256 representing the _amount of base units owned by the
* specified address.
*/
function balanceOf(address _account) public view returns (uint256) {
if (creditsPerToken == 0) return 0;
return _creditBalances[_account].divPrecisely(creditsPerToken);
}
/**
* @dev Gets the credits balance of the specified address.
* @param _account The address to query the balance of.
* @return A uint256 representing the _amount of base units owned by the
* specified address.
*/
function creditsBalanceOf(address _account) public view returns (uint256) {
return _creditBalances[_account];
}
/**
* @dev Transfer tokens to a specified address.
* @param _to the address to transfer to.
* @param _value the _amount to be transferred.
* @return true on success.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
uint256 creditValue = _removeCredits(msg.sender, _value);
_creditBalances[_to] = _creditBalances[_to].add(creditValue);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param _from The address you want to send tokens from.
* @param _to The address you want to transfer to.
* @param _value The _amount of tokens to be transferred.
*/
function transferFrom(
address _from,
address _to,
uint256 _value
) public returns (bool) {
_allowances[_from][msg.sender] = _allowances[_from][msg.sender].sub(
_value
);
uint256 creditValue = _removeCredits(_from, _value);
_creditBalances[_to] = _creditBalances[_to].add(creditValue);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Function to check the _amount of tokens that an owner has allowed to a _spender.
* @param _owner The address which owns the funds.
* @param _spender The address which will spend the funds.
* @return The number of tokens still available for the _spender.
*/
function allowance(address _owner, address _spender)
public
view
returns (uint256)
{
return _allowances[_owner][_spender];
}
/**
* @dev Approve the passed address to spend the specified _amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param _spender The address which will spend the funds.
* @param _value The _amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
_allowances[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Increase the _amount of tokens that an owner has allowed to a _spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param _spender The address which will spend the funds.
* @param _addedValue The _amount of tokens to increase the allowance by.
*/
function increaseAllowance(address _spender, uint256 _addedValue)
public
returns (bool)
{
_allowances[msg.sender][_spender] = _allowances[msg.sender][_spender]
.add(_addedValue);
emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the _amount of tokens that an owner has allowed to a _spender.
* @param _spender The address which will spend the funds.
* @param _subtractedValue The _amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address _spender, uint256 _subtractedValue)
public
returns (bool)
{
uint256 oldValue = _allowances[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
_allowances[msg.sender][_spender] = 0;
} else {
_allowances[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]);
return true;
}
/**
* @notice Mints new tokens, increasing totalSupply.
*/
function mint(address _account, uint256 _amount) external onlyVault {
return _mint(_account, _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 {
require(_account != address(0), "Mint to the zero address");
_totalSupply = _totalSupply.add(_amount);
uint256 creditAmount = _amount.mulTruncate(creditsPerToken);
_creditBalances[_account] = _creditBalances[_account].add(creditAmount);
totalCredits = totalCredits.add(creditAmount);
emit Transfer(address(0), _account, _amount);
}
/**
* @notice Burns tokens, decreasing totalSupply.
*/
function burn(address account, uint256 amount) external onlyVault {
return _burn(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 {
require(_account != address(0), "Burn from the zero address");
_totalSupply = _totalSupply.sub(_amount);
uint256 creditAmount = _removeCredits(_account, _amount);
totalCredits = totalCredits.sub(creditAmount);
emit Transfer(_account, address(0), _amount);
}
/**
* @dev Removes credits from a credit balance and burns rounding errors.
* @param _account Account to remove credits from
* @param _amount Amount in OUSD which will be converted to credits and
* removed
*/
function _removeCredits(address _account, uint256 _amount)
internal
returns (uint256 creditAmount)
{
creditAmount = _amount.mulTruncate(creditsPerToken);
uint256 currentCredits = _creditBalances[_account];
if (
currentCredits == creditAmount || currentCredits - 1 == creditAmount
) {
_creditBalances[_account] = 0;
} else if (currentCredits > creditAmount) {
_creditBalances[_account] = currentCredits - creditAmount;
} else {
revert("Remove exceeds balance");
}
}
/**
* @dev Modify the supply without minting new tokens. This uses a change in
* the exchange rate between "credits" and OUSD tokens to change balances.
* @param _newTotalSupply New total supply of OUSD.
* @return uint256 representing the new total supply.
*/
function changeSupply(uint256 _newTotalSupply)
external
onlyVault
returns (uint256)
{
require(_totalSupply > 0, "Cannot increase 0 supply");
if (_totalSupply == _newTotalSupply) {
emit TotalSupplyUpdated(
_totalSupply,
totalCredits,
creditsPerToken
);
return _totalSupply;
}
_totalSupply = _newTotalSupply;
if (_totalSupply > MAX_SUPPLY) _totalSupply = MAX_SUPPLY;
creditsPerToken = totalCredits.divPrecisely(_totalSupply);
emit TotalSupplyUpdated(_totalSupply, totalCredits, creditsPerToken);
return _totalSupply;
}
}
library StableMath {
using SafeMath for uint256;
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/***************************************
Helpers
****************************************/
/**
* @dev Adjust the scale of an integer
* @param adjustment Amount to adjust by e.g. scaleBy(1e18, -1) == 1e17
*/
function scaleBy(uint256 x, int8 adjustment)
internal
pure
returns (uint256)
{
if (adjustment > 0) {
x = x.mul(10**uint256(adjustment));
} else if (adjustment < 0) {
x = x.div(10**uint256(adjustment * -1));
}
return x;
}
/***************************************
Precise Arithmetic
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) {
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(
uint256 x,
uint256 y,
uint256 scale
) internal pure returns (uint256) {
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
uint256 z = x.mul(y);
// return 9e38 / 1e18 = 9e18
return z.div(scale);
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x.mul(y);
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled.add(FULL_SCALE.sub(1));
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil.div(FULL_SCALE);
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e18 * 1e18 = 8e36
uint256 z = x.mul(FULL_SCALE);
// e.g. 8e36 / 10e18 = 8e17
return z.div(y);
}
}
contract Vault is Initializable, Governable {
using SafeMath for uint256;
using StableMath for uint256;
using SafeMath for int256;
using SafeERC20 for IERC20;
event AssetSupported(address _asset);
event StrategyAdded(address _addr);
event StrategyRemoved(address _addr);
event Mint(address _addr, uint256 _value);
event Redeem(address _addr, uint256 _value);
event StrategyWeightsUpdated(
address[] _strategyAddresses,
uint256[] weights
);
event DepositsPaused();
event DepositsUnpaused();
// Assets supported by the Vault, i.e. Stablecoins
struct Asset {
bool isSupported;
}
mapping(address => Asset) assets;
address[] allAssets;
// Strategies supported by the Vault
struct Strategy {
bool isSupported;
uint256 targetWeight; // 18 decimals. 100% = 1e18
}
mapping(address => Strategy) strategies;
address[] allStrategies;
// Address of the Oracle price provider contract
address public priceProvider;
// Pausing bools
bool public rebasePaused = false;
bool public depositPaused = true;
// Redemption fee in basis points
uint256 public redeemFeeBps;
// Buffer of assets to keep in Vault to handle (most) withdrawals
uint256 public vaultBuffer;
// Mints over this amount automatically allocate funds. 18 decimals.
uint256 public autoAllocateThreshold;
// Mints over this amount automatically rebase. 18 decimals.
uint256 public rebaseThreshold;
OUSD oUSD;
/**
* @dev Verifies that the rebasing is not paused.
*/
modifier whenNotRebasePaused() {
require(!rebasePaused, "Rebasing paused");
_;
}
/***************************************
Configuration
****************************************/
/**
* @dev Set address of price provider.
* @param _priceProvider Address of price provider
*/
function setPriceProvider(address _priceProvider) external onlyGovernor {
priceProvider = _priceProvider;
}
/**
* @dev Set a fee in basis points to be charged for a redeem.
* @param _redeemFeeBps Basis point fee to be charged
*/
function setRedeemFeeBps(uint256 _redeemFeeBps) external onlyGovernor {
redeemFeeBps = _redeemFeeBps;
}
/**
* @dev Set a buffer of assets to keep in the Vault to handle most
* redemptions without needing to spend gas unwinding assets from a Strategy.
* @param _vaultBuffer Percentage using 18 decimals. 100% = 1e18.
*/
function setVaultBuffer(uint256 _vaultBuffer) external onlyGovernor {
vaultBuffer = _vaultBuffer;
}
/**
* @dev Sets the minimum amount of OUSD in a mint to trigger an
* automatic allocation of funds afterwords.
* @param _threshold OUSD amount with 18 fixed decimals.
*/
function setAutoAllocateThreshold(uint256 _threshold)
external
onlyGovernor
{
autoAllocateThreshold = _threshold;
}
/**
* @dev Set a minimum amount of OUSD in a mint or redeem that triggers a
* rebase
* @param _threshold OUSD amount with 18 fixed decimals.
*/
function setRebaseThreshold(uint256 _threshold) external onlyGovernor {
rebaseThreshold = _threshold;
}
/** @dev Add a supported asset to the contract, i.e. one that can be
* to mint OUSD.
* @param _asset Address of asset
*/
function supportAsset(address _asset) external onlyGovernor {
require(!assets[_asset].isSupported, "Asset already supported");
assets[_asset] = Asset({ isSupported: true });
allAssets.push(_asset);
emit AssetSupported(_asset);
}
/**
* @dev Add a strategy to the Vault.
* @param _addr Address of the strategy to add
* @param _targetWeight Target percentage of asset allocation to strategy
*/
function addStrategy(address _addr, uint256 _targetWeight)
external
onlyGovernor
{
require(!strategies[_addr].isSupported, "Strategy already added");
strategies[_addr] = Strategy({
isSupported: true,
targetWeight: _targetWeight
});
allStrategies.push(_addr);
emit StrategyAdded(_addr);
}
/**
* @dev Remove a strategy from the Vault. Removes all invested assets and
* returns them to the Vault.
* @param _addr Address of the strategy to remove
*/
function removeStrategy(address _addr) external onlyGovernor {
require(strategies[_addr].isSupported, "Strategy not added");
// Initialize strategyIndex with out of bounds result so function will
// revert if no valid index found
uint256 strategyIndex = allStrategies.length;
for (uint256 i = 0; i < allStrategies.length; i++) {
if (allStrategies[i] == _addr) {
strategyIndex = i;
break;
}
}
assert(strategyIndex < allStrategies.length);
allStrategies[strategyIndex] = allStrategies[allStrategies.length - 1];
allStrategies.length--;
// Liquidate all assets
IStrategy strategy = IStrategy(_addr);
strategy.liquidate();
emit StrategyRemoved(_addr);
}
/**
* @notice Set the weights for multiple strategies.
* @param _strategyAddresses Array of strategy addresses
* @param _weights Array of corresponding weights, with 18 decimals.
* For ex. 100%=1e18, 30%=3e17.
*/
function setStrategyWeights(
address[] calldata _strategyAddresses,
uint256[] calldata _weights
) external onlyGovernor {
require(
_strategyAddresses.length == _weights.length,
"Parameter length mismatch"
);
for (uint256 i = 0; i < _strategyAddresses.length; i++) {
strategies[_strategyAddresses[i]].targetWeight = _weights[i];
}
emit StrategyWeightsUpdated(_strategyAddresses, _weights);
}
/***************************************
Core
****************************************/
/**
* @dev Deposit a supported asset and mint OUSD.
* @param _asset Address of the asset being deposited
* @param _amount Amount of the asset being deposited
*/
function mint(address _asset, uint256 _amount) external {
require(!depositPaused, "Deposits are paused");
require(assets[_asset].isSupported, "Asset is not supported");
require(_amount > 0, "Amount must be greater than 0");
uint256[] memory assetPrices;
// For now we have to live with the +1 oracle call because we need to
// know the priceAdjustedDeposit before we decide wether or not to grab
// assets. This will not effect small non-rebase/allocate mints
uint256 priceAdjustedDeposit = _amount.mulTruncateScale(
IMinMaxOracle(priceProvider)
.priceMin(Helpers.getSymbol(_asset))
.scaleBy(int8(10)), // 18-8 because oracles have 8 decimals precision
10**Helpers.getDecimals(_asset)
);
if (
(priceAdjustedDeposit > rebaseThreshold && !rebasePaused) ||
(priceAdjustedDeposit >= autoAllocateThreshold)
) {
assetPrices = _getAssetPrices(false);
}
// Rebase must happen before any transfers occur.
if (priceAdjustedDeposit > rebaseThreshold && !rebasePaused) {
rebase(assetPrices);
}
// Transfer the deposited coins to the vault
IERC20 asset = IERC20(_asset);
asset.safeTransferFrom(msg.sender, address(this), _amount);
// Mint matching OUSD
oUSD.mint(msg.sender, priceAdjustedDeposit);
emit Mint(msg.sender, priceAdjustedDeposit);
if (priceAdjustedDeposit >= autoAllocateThreshold) {
allocate(assetPrices);
}
}
/**
* @dev Mint for multiple assets in the same call.
* @param _assets Addresses of assets being deposited
* @param _amounts Amount of each asset at the same index in the _assets
* to deposit.
*/
function mintMultiple(
address[] calldata _assets,
uint256[] calldata _amounts
) external {
require(_assets.length == _amounts.length, "Parameter length mismatch");
uint256 priceAdjustedTotal = 0;
uint256[] memory assetPrices = _getAssetPrices(false);
for (uint256 i = 0; i < allAssets.length; i++) {
for (uint256 j = 0; j < _assets.length; j++) {
if (_assets[j] == allAssets[i]) {
if (_amounts[j] > 0) {
uint256 assetDecimals = Helpers.getDecimals(
allAssets[i]
);
priceAdjustedTotal += _amounts[j].mulTruncateScale(
assetPrices[i],
10**assetDecimals
);
}
}
}
}
// Rebase must happen before any transfers occur.
if (priceAdjustedTotal > rebaseThreshold && !rebasePaused) {
rebase(assetPrices);
}
for (uint256 i = 0; i < _assets.length; i++) {
IERC20 asset = IERC20(_assets[i]);
asset.safeTransferFrom(msg.sender, address(this), _amounts[i]);
}
oUSD.mint(msg.sender, priceAdjustedTotal);
emit Mint(msg.sender, priceAdjustedTotal);
if (priceAdjustedTotal >= autoAllocateThreshold) {
allocate(assetPrices);
}
}
/**
* @dev Withdraw a supported asset and burn OUSD.
* @param _amount Amount of OUSD to burn
*/
function redeem(uint256 _amount) public {
uint256[] memory assetPrices = _getAssetPrices(false);
if (_amount > rebaseThreshold && !rebasePaused) {
rebase(assetPrices);
}
_redeem(_amount, assetPrices);
}
function _redeem(uint256 _amount, uint256[] memory assetPrices) internal {
require(_amount > 0, "Amount must be greater than 0");
uint256 feeAdjustedAmount;
if (redeemFeeBps > 0) {
uint256 redeemFee = _amount.mul(redeemFeeBps).div(10000);
feeAdjustedAmount = _amount.sub(redeemFee);
} else {
feeAdjustedAmount = _amount;
}
// Calculate redemption outputs
uint256[] memory outputs = _calculateRedeemOutputs(feeAdjustedAmount);
// Send outputs
for (uint256 i = 0; i < allAssets.length; i++) {
if (outputs[i] == 0) continue;
IERC20 asset = IERC20(allAssets[i]);
if (asset.balanceOf(address(this)) >= outputs[i]) {
// Use Vault funds first if sufficient
asset.safeTransfer(msg.sender, outputs[i]);
} else {
address strategyAddr = _selectWithdrawStrategyAddr(
allAssets[i],
outputs[i],
assetPrices
);
if (strategyAddr != address(0)) {
// Nothing in Vault, but something in Strategy, send from there
IStrategy strategy = IStrategy(strategyAddr);
strategy.withdraw(msg.sender, allAssets[i], outputs[i]);
} else {
// Cant find funds anywhere
revert("Liquidity error");
}
}
}
oUSD.burn(msg.sender, _amount);
// Until we can prove that we won't affect the prices of our assets
// by withdrawing them, this should be here.
// It's possible that a strategy was off on its asset total, perhaps
// a reward token sold for more or for less than anticipated.
if (_amount > rebaseThreshold && !rebasePaused) {
rebase(assetPrices);
}
emit Redeem(msg.sender, _amount);
}
/**
* @notice Withdraw a supported asset and burn all OUSD.
*/
function redeemAll() external {
uint256[] memory assetPrices = _getAssetPrices(false);
//unfortunately we have to do balanceOf twice
if (oUSD.balanceOf(msg.sender) > rebaseThreshold && !rebasePaused) {
rebase(assetPrices);
}
_redeem(oUSD.balanceOf(msg.sender), assetPrices);
}
/**
* @notice Allocate unallocated funds on Vault to strategies.
* @dev Allocate unallocated funds on Vault to strategies.
**/
function allocate() public {
uint256[] memory assetPrices = _getAssetPrices(false);
allocate(assetPrices);
}
/**
* @notice Allocate unallocated funds on Vault to strategies.
* @dev Allocate unallocated funds on Vault to strategies.
**/
function allocate(uint256[] memory assetPrices) internal {
uint256 vaultValue = _totalValueInVault(assetPrices);
// Nothing in vault to allocate
if (vaultValue == 0) return;
uint256 strategiesValue = _totalValueInStrategies(assetPrices);
// We have a method that does the same as this, gas optimisation
uint256 totalValue = vaultValue + strategiesValue;
// We want to maintain a buffer on the Vault so calculate a percentage
// modifier to multiply each amount being allocated by to enforce the
// vault buffer
uint256 vaultBufferModifier;
if (strategiesValue == 0) {
// Nothing in Strategies, allocate 100% minus the vault buffer to
// strategies
vaultBufferModifier = 1e18 - vaultBuffer;
} else {
vaultBufferModifier = vaultBuffer.mul(totalValue).div(vaultValue);
if (1e18 > vaultBufferModifier) {
// E.g. 1e18 - (1e17 * 10e18)/5e18 = 8e17
// (5e18 * 8e17) / 1e18 = 4e18 allocated from Vault
vaultBufferModifier = 1e18 - vaultBufferModifier;
} else {
// We need to let the buffer fill
return;
}
}
if (vaultBufferModifier == 0) return;
// Iterate over all assets in the Vault and allocate the the appropriate
// strategy
for (uint256 i = 0; i < allAssets.length; i++) {
IERC20 asset = IERC20(allAssets[i]);
uint256 assetBalance = asset.balanceOf(address(this));
// No balance, nothing to do here
if (assetBalance == 0) continue;
// Multiply the balance by the vault buffer modifier and truncate
// to the scale of the asset decimals
uint256 allocateAmount = assetBalance.mulTruncate(
vaultBufferModifier
);
// Get the target Strategy to maintain weightings
address depositStrategyAddr = _selectDepositStrategyAddr(
address(asset),
assetPrices
);
if (depositStrategyAddr != address(0) && allocateAmount > 0) {
IStrategy strategy = IStrategy(depositStrategyAddr);
// Transfer asset to Strategy and call deposit method to
// mint or take required action
asset.safeTransfer(address(strategy), allocateAmount);
strategy.deposit(address(asset), allocateAmount);
}
}
}
/**
* @dev Calculate the total value of assets held by the Vault and all
* strategies and update the supply of oUSD
*/
function rebase() public whenNotRebasePaused returns (uint256) {
uint256[] memory assetPrices = _getAssetPrices(false);
rebase(assetPrices);
}
/**
* @dev Calculate the total value of assets held by the Vault and all
* strategies and update the supply of oUSD
*/
function rebase(uint256[] memory assetPrices)
internal
whenNotRebasePaused
returns (uint256)
{
if (oUSD.totalSupply() == 0) return 0;
return oUSD.changeSupply(_totalValue(assetPrices));
}
/**
* @dev Determine the total value of assets held by the vault and its
* strategies.
* @return uint256 value Total value in USD (1e18)
*/
function totalValue() external returns (uint256 value) {
uint256[] memory assetPrices = _getAssetPrices(false);
value = _totalValue(assetPrices);
}
/**
* @dev Internal Calculate the total value of the assets held by the
* vault and its strategies.
* @return uint256 value Total value in USD (1e18)
*/
function _totalValue(uint256[] memory assetPrices)
internal
view
returns (uint256 value)
{
return
_totalValueInVault(assetPrices) +
_totalValueInStrategies(assetPrices);
}
/**
* @dev Internal to calculate total value of all assets held in Vault.
* @return uint256 Total value in ETH (1e18)
*/
function _totalValueInVault(uint256[] memory assetPrices)
internal
view
returns (uint256 value)
{
value = 0;
for (uint256 y = 0; y < allAssets.length; y++) {
IERC20 asset = IERC20(allAssets[y]);
uint256 assetDecimals = Helpers.getDecimals(allAssets[y]);
uint256 balance = asset.balanceOf(address(this));
if (balance > 0) {
value += balance.mulTruncateScale(
assetPrices[y],
10**assetDecimals
);
}
}
}
/**
* @dev Internal to calculate total value of all assets held in Strategies.
* @return uint256 Total value in ETH (1e18)
*/
function _totalValueInStrategies(uint256[] memory assetPrices)
internal
view
returns (uint256 value)
{
value = 0;
for (uint256 i = 0; i < allStrategies.length; i++) {
value += _totalValueInStrategy(allStrategies[i], assetPrices);
}
}
/**
* @dev Internal to calculate total value of all assets held by strategy.
* @param _strategyAddr Address of the strategy
* @return uint256 Total value in ETH (1e18)
*/
function _totalValueInStrategy(
address _strategyAddr,
uint256[] memory assetPrices
) internal view returns (uint256 value) {
value = 0;
IStrategy strategy = IStrategy(_strategyAddr);
for (uint256 y = 0; y < allAssets.length; y++) {
uint256 assetDecimals = Helpers.getDecimals(allAssets[y]);
if (strategy.supportsAsset(allAssets[y])) {
uint256 balance = strategy.checkBalance(allAssets[y]);
if (balance > 0) {
value += balance.mulTruncateScale(
assetPrices[y],
10**assetDecimals
);
}
}
}
}
/**
* @dev Calculate difference in percent of asset allocation for a
strategy.
* @param _strategyAddr Address of the strategy
* @return int256 Difference between current and target. 18 decimals. For ex. 10%=1e17.
*/
function _strategyWeightDifference(
address _strategyAddr,
uint256[] memory assetPrices
) internal view returns (int256 difference) {
difference =
int256(strategies[_strategyAddr].targetWeight) -
int256(
_totalValueInStrategy(_strategyAddr, assetPrices).divPrecisely(
_totalValue(assetPrices)
)
);
}
/**
* @dev Select a strategy for allocating an asset to.
* @param _asset Address of asset
* @return address Address of the target strategy
*/
function _selectDepositStrategyAddr(
address _asset,
uint256[] memory assetPrices
) internal view returns (address depositStrategyAddr) {
depositStrategyAddr = address(0);
int256 maxDifference = 0;
for (uint256 i = 0; i < allStrategies.length; i++) {
IStrategy strategy = IStrategy(allStrategies[i]);
if (strategy.supportsAsset(_asset)) {
int256 diff = _strategyWeightDifference(
allStrategies[i],
assetPrices
);
if (diff >= maxDifference) {
maxDifference = diff;
depositStrategyAddr = allStrategies[i];
}
}
}
}
/**
* @dev Select a strategy for withdrawing an asset from.
* @param _asset Address of asset
* @return address Address of the target strategy for withdrawal
*/
function _selectWithdrawStrategyAddr(
address _asset,
uint256 _amount,
uint256[] memory assetPrices
) internal view returns (address withdrawStrategyAddr) {
withdrawStrategyAddr = address(0);
int256 minDifference = 1e18;
for (uint256 i = 0; i < allStrategies.length; i++) {
IStrategy strategy = IStrategy(allStrategies[i]);
if (
strategy.supportsAsset(_asset) &&
strategy.checkBalance(_asset) > _amount
) {
int256 diff = _strategyWeightDifference(
allStrategies[i],
assetPrices
);
if (diff <= minDifference) {
minDifference = diff;
withdrawStrategyAddr = allStrategies[i];
}
}
}
}
/**
* @notice Get the balance of an asset held in Vault and all strategies.
* @param _asset Address of asset
* @return uint256 Balance of asset in decimals of asset
*/
function checkBalance(address _asset) external view returns (uint256) {
return _checkBalance(_asset);
}
/**
* @notice Get the balance of an asset held in Vault and all strategies.
* @param _asset Address of asset
* @return uint256 Balance of asset in decimals of asset
*/
function _checkBalance(address _asset)
internal
view
returns (uint256 balance)
{
IERC20 asset = IERC20(_asset);
balance = asset.balanceOf(address(this));
for (uint256 i = 0; i < allStrategies.length; i++) {
IStrategy strategy = IStrategy(allStrategies[i]);
if (strategy.supportsAsset(_asset)) {
balance += strategy.checkBalance(_asset);
}
}
}
/**
* @notice Get the balance of all assets held in Vault and all strategies.
* @return uint256 Balance of all assets (1e18)
*/
function _checkBalance() internal view returns (uint256 balance) {
balance = 0;
for (uint256 i = 0; i < allAssets.length; i++) {
uint256 assetDecimals = Helpers.getDecimals(allAssets[i]);
balance += _checkBalance(allAssets[i]).scaleBy(
int8(18 - assetDecimals)
);
}
}
/**
* @notice Calculate the outputs for a redeem function, i.e. the mix of
* coins that will be returned
*/
function calculateRedeemOutputs(uint256 _amount)
external
returns (uint256[] memory)
{
return _calculateRedeemOutputs(_amount);
}
/**
* @notice Calculate the outputs for a redeem function, i.e. the mix of
* coins that will be returned.
* @return Array of amounts respective to the supported assets
*/
function _calculateRedeemOutputs(uint256 _amount)
internal
returns (uint256[] memory outputs)
{
uint256[] memory assetPrices = _getAssetPrices(true);
uint256 totalBalance = _checkBalance();
uint256 totalOutputValue = 0; // Running total of USD value of assets
uint256 assetCount = getAssetCount();
// Initialise arrays
// Price of each asset in USD in 1e18
outputs = new uint256[](assetCount);
for (uint256 i = 0; i < allAssets.length; i++) {
uint256 assetDecimals = Helpers.getDecimals(allAssets[i]);
// Get the proportional amount of this token for the redeem in 1e18
uint256 proportionalAmount = _checkBalance(allAssets[i])
.scaleBy(int8(18 - assetDecimals))
.mul(_amount)
.div(totalBalance);
if (proportionalAmount > 0) {
// Running USD total of all coins in the redeem outputs in 1e18
totalOutputValue += proportionalAmount.mulTruncate(
assetPrices[i]
);
// Save the output amount in the decimals of the asset
outputs[i] = proportionalAmount.scaleBy(
int8(assetDecimals - 18)
);
}
}
// USD difference in amount of coins calculated due to variations in
// price in 1e18
int256 outputValueDiff = int256(_amount - totalOutputValue);
// Make up the difference by adding/removing an equal proportion of
// each coin according to its USD value
for (uint256 i = 0; i < outputs.length; i++) {
if (outputs[i] == 0) continue;
if (outputValueDiff < 0) {
outputs[i] -= uint256(-outputValueDiff).mul(outputs[i]).div(
totalOutputValue
);
} else if (outputValueDiff > 0) {
outputs[i] += uint256(outputValueDiff).mul(outputs[i]).div(
totalOutputValue
);
}
}
}
/**
* @notice Get an array of the supported asset prices in USD.
* @return uint256[] Array of asset prices in USD (1e18)
*/
function _getAssetPrices(bool useMax)
internal
returns (uint256[] memory assetPrices)
{
assetPrices = new uint256[](getAssetCount());
IMinMaxOracle oracle = IMinMaxOracle(priceProvider);
// Price from Oracle is returned with 8 decimals
// _amount is in assetDecimals
for (uint256 i = 0; i < allAssets.length; i++) {
string memory symbol = Helpers.getSymbol(allAssets[i]);
// Get all the USD prices of the asset in 1e18
if (useMax) {
assetPrices[i] = oracle.priceMax(symbol).scaleBy(int8(18 - 8));
} else {
assetPrices[i] = oracle.priceMin(symbol).scaleBy(int8(18 - 8));
}
}
}
/***************************************
Pause
****************************************/
/**
* @dev Set the deposit paused flag to true to prevent rebasing.
*/
function pauseRebase() external onlyGovernor {
rebasePaused = true;
}
/**
* @dev Set the deposit paused flag to true to allow rebasing.
*/
function unpauseRebase() external onlyGovernor {
rebasePaused = false;
}
/**
* @dev Set the deposit paused flag to true to prevent deposits.
*/
function pauseDeposits() external onlyGovernor {
depositPaused = true;
emit DepositsPaused();
}
/**
* @dev Set the deposit paused flag to false to enable deposits.
*/
function unpauseDeposits() external onlyGovernor {
depositPaused = false;
emit DepositsUnpaused();
}
/***************************************
Utils
****************************************/
/**
* @dev Return the number of assets suppported by the Vault.
*/
function getAssetCount() public view returns (uint256) {
return allAssets.length;
}
/**
* @dev Return all asset addresses in order
*/
function getAllAssets() external view returns (address[] memory) {
return allAssets;
}
/**
* @dev Return the number of strategies active on the Vault.
*/
function getStrategyCount() public view returns (uint256) {
return allStrategies.length;
}
/**
* @dev Get the total APR of the Vault and all Strategies.
*/
function getAPR() external returns (uint256) {
if (getStrategyCount() == 0) return 0;
uint256[] memory assetPrices = _getAssetPrices(true);
uint256 totalAPR = 0;
// Get the value from strategies
for (uint256 i = 0; i < allStrategies.length; i++) {
IStrategy strategy = IStrategy(allStrategies[i]);
if (strategy.getAPR() > 0) {
totalAPR += _totalValueInStrategy(allStrategies[i], assetPrices)
.divPrecisely(_totalValue(assetPrices))
.mulTruncate(strategy.getAPR());
}
}
return totalAPR;
}
/**
* @dev Transfer token to governor. Intended for recovering tokens stuck in
* contract, i.e. mistaken sends.
* @param _asset Address for the asset
* @param _amount Amount of the asset to transfer
*/
function transferToken(address _asset, uint256 _amount)
external
onlyGovernor
{
IERC20(_asset).transfer(governor(), _amount);
}
/**
* @dev Collect reward tokens from all strategies.
*/
function collectRewardTokens() external onlyGovernor {
for (uint256 i = 0; i < allStrategies.length; i++) {
collectRewardTokens(allStrategies[i]);
}
}
/**
* @dev Collect reward tokens from a single strategy and transfer them to
Vault.
* @param _strategyAddr Address of the strategy to collect rewards from
*/
function collectRewardTokens(address _strategyAddr) public onlyGovernor {
IStrategy strategy = IStrategy(_strategyAddr);
strategy.collectRewardToken();
}
/**
* @dev Determines if an asset is supported by the vault.
* @param _asset Address of the asset
*/
function isSupportedAsset(address _asset) external view returns (bool) {
return assets[_asset].isSupported;
}
function _priceUSDMint(string memory symbol) internal returns (uint256) {
// Price from Oracle is returned with 8 decimals
// scale to 18 so 18-8=10
return IMinMaxOracle(priceProvider).priceMin(symbol).scaleBy(10);
}
/**
* @dev Returns the total price in 18 digit USD for a given asset.
* Using Min since min is what we use for mint pricing
* @param symbol String symbol of the asset
* @return uint256 USD price of 1 of the asset
*/
function priceUSDMint(string calldata symbol) external returns (uint256) {
return _priceUSDMint(symbol);
}
/**
* @dev Returns the total price in 18 digit USD for a given asset.
* Using Max since max is what we use for redeem pricing
* @param symbol String symbol of the asset
* @return uint256 USD price of 1 of the asset
*/
function _priceUSDRedeem(string memory symbol) internal returns (uint256) {
// Price from Oracle is returned with 8 decimals
// scale to 18 so 18-8=10
return IMinMaxOracle(priceProvider).priceMax(symbol).scaleBy(10);
}
/**
* @dev Returns the total price in 18 digit USD for a given asset.
* Using Max since max is what we use for redeem pricing
* @param symbol String symbol of the asset
* @return uint256 USD price of 1 of the asset
*/
function priceUSDRedeem(string calldata symbol) external returns (uint256) {
// Price from Oracle is returned with 8 decimals
// scale to 18 so 18-8=10
return _priceUSDRedeem(symbol);
}
} | _strategyAddr Address of the strategy to collect rewards from/ | function collectRewardTokens(address _strategyAddr) public onlyGovernor {
IStrategy strategy = IStrategy(_strategyAddr);
strategy.collectRewardToken();
}
| 1,233,240 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.5;
contract FlightSuretyData {
// using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address payable private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
mapping (address => bool) authorizedUsers;
uint256 private totalFundedAirlines;
uint256 private totalFunds;
struct Flight {
string flight;
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
}
mapping(bytes32 => Flight) public flights;
bytes32[] public allFlights;
struct AirlineCompany {
bool isRegistered;
bool isFunded;
uint256 votes;
mapping(address => bool) voters;
}
mapping(address => AirlineCompany) public airlines;
struct Passenger {
uint256 amount;
bytes32 flightKey;
uint256 payout;
}
mapping(bytes32 => Passenger) passengers;
mapping(address => uint256) public insureePayouts;
event CreditInsurees(string, uint256);
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor()
{
contractOwner = payable(msg.sender);
totalFundedAirlines = 0;
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/**
* @dev Modifier that requires the "an authorized" account to be the function caller
*/
modifier requireAuthorizedUser()
{
if(authorizedUsers[msg.sender] != true) {
revert("Caller is not authorized");
}
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
external
view
returns(bool)
{
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus( bool mode )
external
requireContractOwner
{
operational = mode;
}
/**
* @dev Get registration status of an airline
*
* @param airline address of the airline
*
* @return A bool that is the current airline registration status
*/
function isAirline(address airline)
external
view
returns(bool)
{
return airlines[airline].isRegistered;
}
/**
* @dev Get funded status of an airline
*
* @param airline address of the airline
*
* @return A bool that is the current airline registration status
*/
function isAirlineFunded(address airline)
external
view
returns(bool)
{
return airlines[airline].isFunded;
}
/**
* @dev increase the total number of funded airlines by one
*
* @return A number that is the new total number of airlines
*/
function incrementFundedAirlineCount()
external
returns(uint256)
{
return totalFundedAirlines += 1;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline( address airline, address airlineRegistrar )
external
returns(bool success, uint votes)
{
uint256 two = 2;
uint256 userConsensusActivationLevel = 4;
AirlineCompany storage airlineCompany = airlines[airline];
airlineCompany.isFunded = false;
if(totalFundedAirlines < userConsensusActivationLevel) {
airlineCompany.isRegistered = true;
airlineCompany.votes = 0;
return (true, airlines[airline].votes);
}
require(airlineCompany.voters[airlineRegistrar] == false, "You have voted this airline.");
airlineCompany.votes += 1;
airlineCompany.isRegistered = false;
airlineCompany.voters[airlineRegistrar] = true;
if((totalFundedAirlines / airlineCompany.votes) <= two) {
airlineCompany.isRegistered = true;
}
return (true, airlineCompany.votes);
}
/**
* @dev funds airline
*
* Funds an airline when called
*/
function fundsAirline(address airline, uint256 funds)
external
returns(bool)
{
airlines[airline].isFunded = true;
totalFunds += funds;
return airlines[airline].isFunded;
}
/**
* @dev Register a future flight for insuring.
*
*/
function registerFlight(
string calldata flight, address airlineAddress, uint8 statusCode, uint256 timestamp
)
external
returns (bytes32)
{
bytes32 key = keccak256(
abi.encodePacked(airlineAddress, flight, timestamp)
);
flights[key] = Flight(flight, true, statusCode, timestamp, airlineAddress);
allFlights.push(key);
return key;
}
/**
* @dev Confirms a registered flight.
*
*/
function isFlight( bytes32 key )
external
view
returns (bool)
{
return flights[key].isRegistered;
}
/**
* @dev Buy insurance for a flight
*
*/
function buy(uint256 amount, address passenger, bytes32 flightKey, uint256 payout)
external
{
bytes32 passengerAddress = keccak256(abi.encodePacked(passenger, flightKey));
totalFunds += amount;
passengers[passengerAddress] = Passenger(amount, flightKey, payout);
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees(address passenger, bytes32 flightKey)
external
{
bytes32 passengerAddress = keccak256(abi.encodePacked(passenger, flightKey));
uint256 payout = passengers[passengerAddress].payout;
insureePayouts[passenger] += payout;
emit CreditInsurees('Account creditted with ', payout);
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay(address passenger)
external
returns(uint256 passengerPay)
{
passengerPay = insureePayouts[passenger];
insureePayouts[passenger] = 0;
payable(passenger).transfer(passengerPay);
return passengerPay;
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund()
public
payable
{
contractOwner.transfer(msg.value);
}
function getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev authorizes the an address to call this contract
*/
function authorizeCaller(address callerAddress) external requireContractOwner
{
authorizedUsers[callerAddress] = true;
}
/**
* @dev Fallback function for funding smart contract.
*
*/
receive()
external
payable
{
fund();
}
}
| Get funded status of an airline airline address of the airline return A bool that is the current airline registration status/ | function isAirlineFunded(address airline)
external
view
returns(bool)
{
return airlines[airline].isFunded;
}
| 6,442,413 |
pragma solidity ^0.4.0;
/**
* The contract is a Smart ID, and all derived 'Smart IDs' should match the bytecode
* of a known 'good SmartIdentity' version. See the 'SmartIdentityRegistry' contract
* for a mechanism for verifying valid SmartIdentities.
*/
contract SmartIdentity {
address private owner;
address private override;
uint private blocklock;
string public encryptionPublicKey;
string public signingPublicKey;
uint constant BLOCK_HEIGHT = 20;
uint constant ERROR_EVENT = 1;
uint constant WARNING_EVENT = 2;
uint constant SIG_CHANGE_EVENT = 3;
uint constant INFO_EVENT = 4;
uint constant DEBUG_EVENT = 5;
mapping(bytes32 => Attribute) public attributes;
/**
* Constructor of the Smart Identity
*/
function SmartIdentity() {
owner = msg.sender;
override = owner;
blocklock = block.number - BLOCK_HEIGHT;
}
/**
* Modifier to place a constraint on the user calling a function
*/
modifier onlyBy(address _account) {
if (msg.sender != _account) {
throw;
}
_;
}
/**
* Modifier to prevent change if the block height is too low.
* This has been set at 20 for testing purposes, and should
* be made longer to better protect the contract from significant
* ownership changes.
*/
modifier checkBlockLock() {
if (blocklock + BLOCK_HEIGHT > block.number) {
throw;
}
_;
}
/**
* Modifier to set the blocklock.
*/
modifier blockLock() {
blocklock = block.number;
_;
}
/**
* The attribute structure: every attribute is composed of:
* - Attribute hash
* - Endorsements
*/
struct Attribute {
bytes32 hash;
mapping(bytes32 => Endorsement) endorsements;
}
/**
* The endorsement structure: every endorsement is composed of:
* - Endorser address
* - Endorsement hash
* - Accepted Status - true if the user has accepted the endorsement
*/
struct Endorsement {
address endorser;
bytes32 hash;
bool accepted;
}
/**
* This event is used for standard change notification messages and outputs the following:
* - owner of the contract
* - event status level
* - event message body
*/
event ChangeNotification(address indexed sender, uint status, bytes32 notificationMsg);
/**
* This function is used to send events.
* Status Level Scale:
* 1 Error: error conditions
* 2 Warning: warning conditions
* 3 Significant Change: Significant change to condition
* 4 Informational: informational messages
* 5 Verbose: debug-level messages
*/
function sendEvent(uint _status, bytes32 _notification) internal returns(bool) {
ChangeNotification(owner, _status, _notification);
return true;
}
/**
* This function gives the override address the ability to change owner.
* This could allow the identity to be moved to a multi-sig contract.
* See https://github.com/ethereum/dapp-bin/blob/master/wallet/wallet.sol
* for a multi-sig wallet example.
*/
function setOwner(address _newowner) onlyBy(override) checkBlockLock() blockLock() returns(bool) {
owner = _newowner;
sendEvent(SIG_CHANGE_EVENT, "Owner has been changed");
return true;
}
/**
* Cosmetic function for the override account holder to check that their
* permissions on the contract have been set correctly.
*/
function getOwner() onlyBy(override) returns(address) {
return owner;
}
/**
* The override address is another ethereum address that can reset the owner.
* In practice this could either be another multi-sig account, or another
* smart contract that this control could be delegated to.
*/
function setOverride(address _override) onlyBy(owner) checkBlockLock() blockLock() returns(bool) {
override = _override;
sendEvent(SIG_CHANGE_EVENT, "Override has been changed");
return true;
}
/**
* This function removes the override by the owner - if trust between the identity
* holder and the new account ends.
*/
function removeOverride() onlyBy(owner) checkBlockLock() blockLock() returns(bool) {
override = owner;
sendEvent(SIG_CHANGE_EVENT, "Override has been removed");
return true;
}
/**
* Adds an attribute, with an empty list of endorsements.
*/
function addAttribute(bytes32 _hash) onlyBy(owner) checkBlockLock() returns(bool) {
var attribute = attributes[_hash];
if (attribute.hash == _hash) {
sendEvent(SIG_CHANGE_EVENT, "A hash exists for the attribute");
throw;
}
attribute.hash = _hash;
sendEvent(INFO_EVENT, "Attribute has been added");
return true;
}
/**
* This updates an attribute by removing the old one first, and then
* adding the new one. The event log should hold the record of the
* transaction so at a future date it should be possible to traverse
* the history of an attribute against the blockchain.
*/
function updateAttribute(bytes32 _oldhash, bytes32 _newhash) onlyBy(owner) checkBlockLock() returns(bool) {
sendEvent(DEBUG_EVENT, "Attempting to update attribute");
removeAttribute(_oldhash);
addAttribute(_newhash);
sendEvent(SIG_CHANGE_EVENT, "Attribute has been updated");
return true;
}
/**
* Removes an attribute from a contract.
*/
function removeAttribute(bytes32 _hash) onlyBy(owner) checkBlockLock() returns(bool) {
var attribute = attributes[_hash];
if (attribute.hash != _hash) {
sendEvent(WARNING_EVENT, "Hash not found for attribute");
throw;
}
delete attributes[_hash];
sendEvent(SIG_CHANGE_EVENT, "Attribute has been removed");
return true;
}
/**
* Adds an endorsement to an attribute; must provide a valid attributeHash.
* See the docs for off-chain transfer of the encrypted endorsement information.
*/
function addEndorsement(bytes32 _attributeHash, bytes32 _endorsementHash) returns(bool) {
var attribute = attributes[_attributeHash];
if (attribute.hash != _attributeHash) {
sendEvent(ERROR_EVENT, "Attribute doesn't exist");
throw;
}
var endorsement = attribute.endorsements[_endorsementHash];
if (endorsement.hash == _endorsementHash) {
sendEvent(ERROR_EVENT, "Endorsement already exists");
throw;
}
endorsement.hash = _endorsementHash;
endorsement.endorser = msg.sender;
endorsement.accepted = false;
sendEvent(INFO_EVENT, "Endorsement has been added");
return true;
}
/**
* Owner can mark an endorsement as accepted.
*/
function acceptEndorsement(bytes32 _attributeHash, bytes32 _endorsementHash) onlyBy(owner) returns(bool) {
var attribute = attributes[_attributeHash];
var endorsement = attribute.endorsements[_endorsementHash];
endorsement.accepted = true;
sendEvent(SIG_CHANGE_EVENT, "Endorsement has been accepted");
}
/**
* Checks that an endorsement _endorsementHash exists for the attribute _attributeHash.
*/
function checkEndorsementExists(bytes32 _attributeHash, bytes32 _endorsementHash) returns(bool) {
var attribute = attributes[_attributeHash];
if (attribute.hash != _attributeHash) {
sendEvent(ERROR_EVENT, "Attribute doesn't exist");
return false;
}
var endorsement = attribute.endorsements[_endorsementHash];
if (endorsement.hash != _endorsementHash) {
sendEvent(ERROR_EVENT, "Endorsement doesn't exist");
return false;
}
if (endorsement.accepted == true) {
sendEvent(INFO_EVENT, "Endorsement exists for attribute");
return true;
} else {
sendEvent(ERROR_EVENT, "Endorsement hasn't been accepted");
return false;
}
}
/**
* Allows only the person who gave the endorsement the ability to remove it.
*/
function removeEndorsement(bytes32 _attributeHash, bytes32 _endorsementHash) returns(bool) {
var attribute = attributes[_attributeHash];
var endorsement = attribute.endorsements[_endorsementHash];
if (msg.sender == endorsement.endorser) {
delete attribute.endorsements[_endorsementHash];
sendEvent(SIG_CHANGE_EVENT, "Endorsement removed");
return true;
}
if (msg.sender == owner && endorsement.accepted == false) {
delete attribute.endorsements[_endorsementHash];
sendEvent(SIG_CHANGE_EVENT, "Endorsement denied");
return true;
}
sendEvent(SIG_CHANGE_EVENT, "Endorsement removal failed");
throw;
}
/**
* Allows only the account owner to create or update encryptionPublicKey.
* Only 1 encryptionPublicKey is allowed per account, therefore use same set
* method for both create and update.
*/
function setEncryptionPublicKey(string _myEncryptionPublicKey) onlyBy(owner) checkBlockLock() returns(bool) {
encryptionPublicKey = _myEncryptionPublicKey;
sendEvent(SIG_CHANGE_EVENT, "Encryption key added");
return true;
}
/**
* Allows only the account owner to create or update signingPublicKey.
* Only 1 signingPublicKey allowed per account, therefore use same set method
* for both create and update.
*/
function setSigningPublicKey(string _mySigningPublicKey) onlyBy(owner) checkBlockLock() returns(bool) {
signingPublicKey = _mySigningPublicKey;
sendEvent(SIG_CHANGE_EVENT, "Signing key added");
return true;
}
/**
* Kills the contract and prevents further actions on it.
*/
function kill() onlyBy(owner) returns(uint) {
suicide(owner);
sendEvent(WARNING_EVENT, "Contract killed");
}
}
| The override address is another ethereum address that can reset the owner. In practice this could either be another multi-sig account, or another smart contract that this control could be delegated to./ | function setOverride(address _override) onlyBy(owner) checkBlockLock() blockLock() returns(bool) {
override = _override;
sendEvent(SIG_CHANGE_EVENT, "Override has been changed");
return true;
}
| 6,455,295 |
./full_match/5/0x1A0d58a79fB4e74f6a7d45bFD91C0EF3DEEfcF86/sources/contracts/libs/MathUtils.sol | Compute percentage of a value with the percentage represented by a fraction _amount Amount to take the percentage of _fracNum Numerator of fraction representing the percentage _fracDenom Denominator of fraction representing the percentage/ | function percOf(
uint256 _amount,
uint256 _fracNum,
uint256 _fracDenom
) internal pure returns (uint256) {
return (_amount * percPoints(_fracNum, _fracDenom)) / PERC_DIVISOR;
}
| 1,887,359 |
./full_match/42/0xAfCd2405298C2FABB2F7fCcEB919B4505A6bdDFC/sources/browser/MerkleDistributor.sol | Check claimed proof against merkle window at given index. Check the account has not yet claimed for this window. Proof is correct and claim has not occurred yet; check that claim window has begun. | function _markClaimed(Claim memory claim) private {
require(_verifyClaim(claim), "Incorrect merkle proof");
require(!claimed[claim.windowIndex][claim.account], "Account has already claimed for this window");
require(getCurrentTime() >= merkleWindows[claim.windowIndex].start, "Claim window has not begun");
claimed[claim.windowIndex][claim.account] = true;
emit Claimed(
msg.sender,
claim.windowIndex,
claim.account,
claim.amount,
address(merkleWindows[claim.windowIndex].rewardToken)
);
}
| 16,243,984 |
./full_match/5/0xA13E43d299dd822677f3Cc62d3E77b84DC3665c3/sources/project_/contracts/base/MetawinMinterProxy.sol | Private function to calculate the purchase price./ | function _getPrice(uint256 amount) private view returns (uint256 price) {
price = _currentAuctionPrice() * amount;
}
| 1,942,884 |
// Sources flattened with hardhat v2.6.1 https://hardhat.org
// File @openzeppelin/contracts/utils/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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 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) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
// MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
// MIT
pragma solidity ^0.8.0;
/**
* @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 contracts/MVM/iMVM_DiscountOracle.sol
// MIT
pragma solidity ^0.8.9;
interface iMVM_DiscountOracle{
function setDiscount(
uint256 _discount
) external;
function setMinL2Gas(
uint256 _minL2Gas
) external;
function setWhitelistedXDomainSender(
address _sender,
bool _isWhitelisted
) external;
function isXDomainSenderAllowed(
address _sender
) view external returns(bool);
function setAllowAllXDomainSenders(
bool _allowAllXDomainSenders
) external;
function getMinL2Gas() view external returns(uint256);
function getDiscount() view external returns(uint256);
function processL2SeqGas(address sender, uint256 _chainId) external payable;
}
// File contracts/libraries/resolver/Lib_AddressManager.sol
// MIT
pragma solidity ^0.8.9;
/* External Imports */
/**
* @title Lib_AddressManager
*/
contract Lib_AddressManager is Ownable {
/**********
* Events *
**********/
event AddressSet(string indexed _name, address _newAddress, address _oldAddress);
/*************
* Variables *
*************/
mapping(bytes32 => address) private addresses;
/********************
* Public Functions *
********************/
/**
* Changes the address associated with a particular name.
* @param _name String name to associate an address with.
* @param _address Address to associate with the name.
*/
function setAddress(string memory _name, address _address) external onlyOwner {
bytes32 nameHash = _getNameHash(_name);
address oldAddress = addresses[nameHash];
addresses[nameHash] = _address;
emit AddressSet(_name, _address, oldAddress);
}
/**
* Retrieves the address associated with a given name.
* @param _name Name to retrieve an address for.
* @return Address associated with the given name.
*/
function getAddress(string memory _name) external view returns (address) {
return addresses[_getNameHash(_name)];
}
/**********************
* Internal Functions *
**********************/
/**
* Computes the hash of a name.
* @param _name Name to compute a hash for.
* @return Hash of the given name.
*/
function _getNameHash(string memory _name) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_name));
}
}
// File contracts/libraries/resolver/Lib_AddressResolver.sol
// MIT
pragma solidity ^0.8.9;
/* Library Imports */
/**
* @title Lib_AddressResolver
*/
abstract contract Lib_AddressResolver {
/*************
* Variables *
*************/
Lib_AddressManager public libAddressManager;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Lib_AddressManager.
*/
constructor(address _libAddressManager) {
libAddressManager = Lib_AddressManager(_libAddressManager);
}
/********************
* Public Functions *
********************/
/**
* Resolves the address associated with a given name.
* @param _name Name to resolve an address for.
* @return Address associated with the given name.
*/
function resolve(string memory _name) public view returns (address) {
return libAddressManager.getAddress(_name);
}
}
// File contracts/libraries/rlp/Lib_RLPReader.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_RLPReader
* @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]).
*/
library Lib_RLPReader {
/*************
* Constants *
*************/
uint256 internal constant MAX_LIST_LENGTH = 32;
/*********
* Enums *
*********/
enum RLPItemType {
DATA_ITEM,
LIST_ITEM
}
/***********
* Structs *
***********/
struct RLPItem {
uint256 length;
uint256 ptr;
}
/**********************
* Internal Functions *
**********************/
/**
* Converts bytes to a reference to memory position and length.
* @param _in Input bytes to convert.
* @return Output memory reference.
*/
function toRLPItem(bytes memory _in) internal pure returns (RLPItem memory) {
uint256 ptr;
assembly {
ptr := add(_in, 32)
}
return RLPItem({ length: _in.length, ptr: ptr });
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(RLPItem memory _in) internal pure returns (RLPItem[] memory) {
(uint256 listOffset, , RLPItemType itemType) = _decodeLength(_in);
require(itemType == RLPItemType.LIST_ITEM, "Invalid RLP list value.");
// Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by
// writing to the length. Since we can't know the number of RLP items without looping over
// the entire input, we'd have to loop twice to accurately size this array. It's easier to
// simply set a reasonable maximum list length and decrease the size before we finish.
RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH);
uint256 itemCount = 0;
uint256 offset = listOffset;
while (offset < _in.length) {
require(itemCount < MAX_LIST_LENGTH, "Provided RLP list exceeds max list length.");
(uint256 itemOffset, uint256 itemLength, ) = _decodeLength(
RLPItem({ length: _in.length - offset, ptr: _in.ptr + offset })
);
out[itemCount] = RLPItem({ length: itemLength + itemOffset, ptr: _in.ptr + offset });
itemCount += 1;
offset += itemOffset + itemLength;
}
// Decrease the array size to match the actual item count.
assembly {
mstore(out, itemCount)
}
return out;
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(bytes memory _in) internal pure returns (RLPItem[] memory) {
return readList(toRLPItem(_in));
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(RLPItem memory _in) internal pure returns (bytes memory) {
(uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in);
require(itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes value.");
return _copy(_in.ptr, itemOffset, itemLength);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(bytes memory _in) internal pure returns (bytes memory) {
return readBytes(toRLPItem(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(RLPItem memory _in) internal pure returns (string memory) {
return string(readBytes(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(bytes memory _in) internal pure returns (string memory) {
return readString(toRLPItem(_in));
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(RLPItem memory _in) internal pure returns (bytes32) {
require(_in.length <= 33, "Invalid RLP bytes32 value.");
(uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in);
require(itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes32 value.");
uint256 ptr = _in.ptr + itemOffset;
bytes32 out;
assembly {
out := mload(ptr)
// Shift the bytes over to match the item size.
if lt(itemLength, 32) {
out := div(out, exp(256, sub(32, itemLength)))
}
}
return out;
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(bytes memory _in) internal pure returns (bytes32) {
return readBytes32(toRLPItem(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(RLPItem memory _in) internal pure returns (uint256) {
return uint256(readBytes32(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(bytes memory _in) internal pure returns (uint256) {
return readUint256(toRLPItem(_in));
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(RLPItem memory _in) internal pure returns (bool) {
require(_in.length == 1, "Invalid RLP boolean value.");
uint256 ptr = _in.ptr;
uint256 out;
assembly {
out := byte(0, mload(ptr))
}
require(out == 0 || out == 1, "Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1");
return out != 0;
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(bytes memory _in) internal pure returns (bool) {
return readBool(toRLPItem(_in));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(RLPItem memory _in) internal pure returns (address) {
if (_in.length == 1) {
return address(0);
}
require(_in.length == 21, "Invalid RLP address value.");
return address(uint160(readUint256(_in)));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(bytes memory _in) internal pure returns (address) {
return readAddress(toRLPItem(_in));
}
/**
* Reads the raw bytes of an RLP item.
* @param _in RLP item to read.
* @return Raw RLP bytes.
*/
function readRawBytes(RLPItem memory _in) internal pure returns (bytes memory) {
return _copy(_in);
}
/*********************
* Private Functions *
*********************/
/**
* Decodes the length of an RLP item.
* @param _in RLP item to decode.
* @return Offset of the encoded data.
* @return Length of the encoded data.
* @return RLP item type (LIST_ITEM or DATA_ITEM).
*/
function _decodeLength(RLPItem memory _in)
private
pure
returns (
uint256,
uint256,
RLPItemType
)
{
require(_in.length > 0, "RLP item cannot be null.");
uint256 ptr = _in.ptr;
uint256 prefix;
assembly {
prefix := byte(0, mload(ptr))
}
if (prefix <= 0x7f) {
// Single byte.
return (0, 1, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xb7) {
// Short string.
uint256 strLen = prefix - 0x80;
require(_in.length > strLen, "Invalid RLP short string.");
return (1, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xbf) {
// Long string.
uint256 lenOfStrLen = prefix - 0xb7;
require(_in.length > lenOfStrLen, "Invalid RLP long string length.");
uint256 strLen;
assembly {
// Pick out the string length.
strLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfStrLen)))
}
require(_in.length > lenOfStrLen + strLen, "Invalid RLP long string.");
return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xf7) {
// Short list.
uint256 listLen = prefix - 0xc0;
require(_in.length > listLen, "Invalid RLP short list.");
return (1, listLen, RLPItemType.LIST_ITEM);
} else {
// Long list.
uint256 lenOfListLen = prefix - 0xf7;
require(_in.length > lenOfListLen, "Invalid RLP long list length.");
uint256 listLen;
assembly {
// Pick out the list length.
listLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfListLen)))
}
require(_in.length > lenOfListLen + listLen, "Invalid RLP long list.");
return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM);
}
}
/**
* Copies the bytes from a memory location.
* @param _src Pointer to the location to read from.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Copied bytes.
*/
function _copy(
uint256 _src,
uint256 _offset,
uint256 _length
) private pure returns (bytes memory) {
bytes memory out = new bytes(_length);
if (out.length == 0) {
return out;
}
uint256 src = _src + _offset;
uint256 dest;
assembly {
dest := add(out, 32)
}
// Copy over as many complete words as we can.
for (uint256 i = 0; i < _length / 32; i++) {
assembly {
mstore(dest, mload(src))
}
src += 32;
dest += 32;
}
// Pick out the remaining bytes.
uint256 mask;
unchecked {
mask = 256**(32 - (_length % 32)) - 1;
}
assembly {
mstore(dest, or(and(mload(src), not(mask)), and(mload(dest), mask)))
}
return out;
}
/**
* Copies an RLP item into bytes.
* @param _in RLP item to copy.
* @return Copied bytes.
*/
function _copy(RLPItem memory _in) private pure returns (bytes memory) {
return _copy(_in.ptr, 0, _in.length);
}
}
// File contracts/libraries/rlp/Lib_RLPWriter.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_RLPWriter
* @author Bakaoh (with modifications)
*/
library Lib_RLPWriter {
/**********************
* Internal Functions *
**********************/
/**
* RLP encodes a byte string.
* @param _in The byte string to encode.
* @return The RLP encoded string in bytes.
*/
function writeBytes(bytes memory _in) internal pure returns (bytes memory) {
bytes memory encoded;
if (_in.length == 1 && uint8(_in[0]) < 128) {
encoded = _in;
} else {
encoded = abi.encodePacked(_writeLength(_in.length, 128), _in);
}
return encoded;
}
/**
* RLP encodes a list of RLP encoded byte byte strings.
* @param _in The list of RLP encoded byte strings.
* @return The RLP encoded list of items in bytes.
*/
function writeList(bytes[] memory _in) internal pure returns (bytes memory) {
bytes memory list = _flatten(_in);
return abi.encodePacked(_writeLength(list.length, 192), list);
}
/**
* RLP encodes a string.
* @param _in The string to encode.
* @return The RLP encoded string in bytes.
*/
function writeString(string memory _in) internal pure returns (bytes memory) {
return writeBytes(bytes(_in));
}
/**
* RLP encodes an address.
* @param _in The address to encode.
* @return The RLP encoded address in bytes.
*/
function writeAddress(address _in) internal pure returns (bytes memory) {
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a uint.
* @param _in The uint256 to encode.
* @return The RLP encoded uint256 in bytes.
*/
function writeUint(uint256 _in) internal pure returns (bytes memory) {
return writeBytes(_toBinary(_in));
}
/**
* RLP encodes a bool.
* @param _in The bool to encode.
* @return The RLP encoded bool in bytes.
*/
function writeBool(bool _in) internal pure returns (bytes memory) {
bytes memory encoded = new bytes(1);
encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80));
return encoded;
}
/*********************
* Private Functions *
*********************/
/**
* Encode the first byte, followed by the `len` in binary form if `length` is more than 55.
* @param _len The length of the string or the payload.
* @param _offset 128 if item is string, 192 if item is list.
* @return RLP encoded bytes.
*/
function _writeLength(uint256 _len, uint256 _offset) private pure returns (bytes memory) {
bytes memory encoded;
if (_len < 56) {
encoded = new bytes(1);
encoded[0] = bytes1(uint8(_len) + uint8(_offset));
} else {
uint256 lenLen;
uint256 i = 1;
while (_len / i != 0) {
lenLen++;
i *= 256;
}
encoded = new bytes(lenLen + 1);
encoded[0] = bytes1(uint8(lenLen) + uint8(_offset) + 55);
for (i = 1; i <= lenLen; i++) {
encoded[i] = bytes1(uint8((_len / (256**(lenLen - i))) % 256));
}
}
return encoded;
}
/**
* Encode integer in big endian binary form with no leading zeroes.
* @notice TODO: This should be optimized with assembly to save gas costs.
* @param _x The integer to encode.
* @return RLP encoded bytes.
*/
function _toBinary(uint256 _x) private pure returns (bytes memory) {
bytes memory b = abi.encodePacked(_x);
uint256 i = 0;
for (; i < 32; i++) {
if (b[i] != 0) {
break;
}
}
bytes memory res = new bytes(32 - i);
for (uint256 j = 0; j < res.length; j++) {
res[j] = b[i++];
}
return res;
}
/**
* Copies a piece of memory to another location.
* @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol.
* @param _dest Destination location.
* @param _src Source location.
* @param _len Length of memory to copy.
*/
function _memcpy(
uint256 _dest,
uint256 _src,
uint256 _len
) private pure {
uint256 dest = _dest;
uint256 src = _src;
uint256 len = _len;
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint256 mask;
unchecked {
mask = 256**(32 - len) - 1;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/**
* Flattens a list of byte strings into one byte string.
* @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol.
* @param _list List of byte strings to flatten.
* @return The flattened byte string.
*/
function _flatten(bytes[] memory _list) private pure returns (bytes memory) {
if (_list.length == 0) {
return new bytes(0);
}
uint256 len;
uint256 i = 0;
for (; i < _list.length; i++) {
len += _list[i].length;
}
bytes memory flattened = new bytes(len);
uint256 flattenedPtr;
assembly {
flattenedPtr := add(flattened, 0x20)
}
for (i = 0; i < _list.length; i++) {
bytes memory item = _list[i];
uint256 listPtr;
assembly {
listPtr := add(item, 0x20)
}
_memcpy(flattenedPtr, listPtr, item.length);
flattenedPtr += _list[i].length;
}
return flattened;
}
}
// File contracts/libraries/utils/Lib_BytesUtils.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_BytesUtils
*/
library Lib_BytesUtils {
/**********************
* Internal Functions *
**********************/
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_length + 31 >= _length, "slice_overflow");
require(_start + _length >= _start, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function slice(bytes memory _bytes, uint256 _start) internal pure returns (bytes memory) {
if (_start >= _bytes.length) {
return bytes("");
}
return slice(_bytes, _start, _bytes.length - _start);
}
function toBytes32(bytes memory _bytes) internal pure returns (bytes32) {
if (_bytes.length < 32) {
bytes32 ret;
assembly {
ret := mload(add(_bytes, 32))
}
return ret;
}
return abi.decode(_bytes, (bytes32)); // will truncate if input length > 32 bytes
}
function toUint256(bytes memory _bytes) internal pure returns (uint256) {
return uint256(toBytes32(_bytes));
}
function toNibbles(bytes memory _bytes) internal pure returns (bytes memory) {
bytes memory nibbles = new bytes(_bytes.length * 2);
for (uint256 i = 0; i < _bytes.length; i++) {
nibbles[i * 2] = _bytes[i] >> 4;
nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16);
}
return nibbles;
}
function fromNibbles(bytes memory _bytes) internal pure returns (bytes memory) {
bytes memory ret = new bytes(_bytes.length / 2);
for (uint256 i = 0; i < ret.length; i++) {
ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]);
}
return ret;
}
function equal(bytes memory _bytes, bytes memory _other) internal pure returns (bool) {
return keccak256(_bytes) == keccak256(_other);
}
}
// File contracts/libraries/utils/Lib_Bytes32Utils.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_Byte32Utils
*/
library Lib_Bytes32Utils {
/**********************
* Internal Functions *
**********************/
/**
* Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true."
* @param _in Input bytes32 value.
* @return Bytes32 as a boolean.
*/
function toBool(bytes32 _in) internal pure returns (bool) {
return _in != 0;
}
/**
* Converts a boolean to a bytes32 value.
* @param _in Input boolean value.
* @return Boolean as a bytes32.
*/
function fromBool(bool _in) internal pure returns (bytes32) {
return bytes32(uint256(_in ? 1 : 0));
}
/**
* Converts a bytes32 value to an address. Takes the *last* 20 bytes.
* @param _in Input bytes32 value.
* @return Bytes32 as an address.
*/
function toAddress(bytes32 _in) internal pure returns (address) {
return address(uint160(uint256(_in)));
}
/**
* Converts an address to a bytes32.
* @param _in Input address value.
* @return Address as a bytes32.
*/
function fromAddress(address _in) internal pure returns (bytes32) {
return bytes32(uint256(uint160(_in)));
}
}
// File contracts/libraries/codec/Lib_OVMCodec.sol
// MIT
pragma solidity ^0.8.9;
/* Library Imports */
/**
* @title Lib_OVMCodec
*/
library Lib_OVMCodec {
/*********
* Enums *
*********/
enum QueueOrigin {
SEQUENCER_QUEUE,
L1TOL2_QUEUE
}
/***********
* Structs *
***********/
struct EVMAccount {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
}
struct ChainBatchHeader {
uint256 batchIndex;
bytes32 batchRoot;
uint256 batchSize;
uint256 prevTotalElements;
bytes extraData;
}
struct ChainInclusionProof {
uint256 index;
bytes32[] siblings;
}
struct Transaction {
uint256 timestamp;
uint256 blockNumber;
QueueOrigin l1QueueOrigin;
address l1TxOrigin;
address entrypoint;
uint256 gasLimit;
bytes data;
}
struct TransactionChainElement {
bool isSequenced;
uint256 queueIndex; // QUEUED TX ONLY
uint256 timestamp; // SEQUENCER TX ONLY
uint256 blockNumber; // SEQUENCER TX ONLY
bytes txData; // SEQUENCER TX ONLY
}
struct QueueElement {
bytes32 transactionHash;
uint40 timestamp;
uint40 blockNumber;
}
/**********************
* Internal Functions *
**********************/
/**
* Encodes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Encoded transaction bytes.
*/
function encodeTransaction(Transaction memory _transaction)
internal
pure
returns (bytes memory)
{
return
abi.encodePacked(
_transaction.timestamp,
_transaction.blockNumber,
_transaction.l1QueueOrigin,
_transaction.l1TxOrigin,
_transaction.entrypoint,
_transaction.gasLimit,
_transaction.data
);
}
/**
* Hashes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Hashed transaction
*/
function hashTransaction(Transaction memory _transaction) internal pure returns (bytes32) {
return keccak256(encodeTransaction(_transaction));
}
/**
* @notice Decodes an RLP-encoded account state into a useful struct.
* @param _encoded RLP-encoded account state.
* @return Account state struct.
*/
function decodeEVMAccount(bytes memory _encoded) internal pure returns (EVMAccount memory) {
Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded);
return
EVMAccount({
nonce: Lib_RLPReader.readUint256(accountState[0]),
balance: Lib_RLPReader.readUint256(accountState[1]),
storageRoot: Lib_RLPReader.readBytes32(accountState[2]),
codeHash: Lib_RLPReader.readBytes32(accountState[3])
});
}
/**
* Calculates a hash for a given batch header.
* @param _batchHeader Header to hash.
* @return Hash of the header.
*/
function hashBatchHeader(Lib_OVMCodec.ChainBatchHeader memory _batchHeader)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
_batchHeader.batchRoot,
_batchHeader.batchSize,
_batchHeader.prevTotalElements,
_batchHeader.extraData
)
);
}
}
// File contracts/libraries/utils/Lib_MerkleTree.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_MerkleTree
* @author River Keefer
*/
library Lib_MerkleTree {
/**********************
* Internal Functions *
**********************/
/**
* Calculates a merkle root for a list of 32-byte leaf hashes. WARNING: If the number
* of leaves passed in is not a power of two, it pads out the tree with zero hashes.
* If you do not know the original length of elements for the tree you are verifying, then
* this may allow empty leaves past _elements.length to pass a verification check down the line.
* Note that the _elements argument is modified, therefore it must not be used again afterwards
* @param _elements Array of hashes from which to generate a merkle root.
* @return Merkle root of the leaves, with zero hashes for non-powers-of-two (see above).
*/
function getMerkleRoot(bytes32[] memory _elements) internal pure returns (bytes32) {
require(_elements.length > 0, "Lib_MerkleTree: Must provide at least one leaf hash.");
if (_elements.length == 1) {
return _elements[0];
}
uint256[16] memory defaults = [
0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563,
0x633dc4d7da7256660a892f8f1604a44b5432649cc8ec5cb3ced4c4e6ac94dd1d,
0x890740a8eb06ce9be422cb8da5cdafc2b58c0a5e24036c578de2a433c828ff7d,
0x3b8ec09e026fdc305365dfc94e189a81b38c7597b3d941c279f042e8206e0bd8,
0xecd50eee38e386bd62be9bedb990706951b65fe053bd9d8a521af753d139e2da,
0xdefff6d330bb5403f63b14f33b578274160de3a50df4efecf0e0db73bcdd3da5,
0x617bdd11f7c0a11f49db22f629387a12da7596f9d1704d7465177c63d88ec7d7,
0x292c23a9aa1d8bea7e2435e555a4a60e379a5a35f3f452bae60121073fb6eead,
0xe1cea92ed99acdcb045a6726b2f87107e8a61620a232cf4d7d5b5766b3952e10,
0x7ad66c0a68c72cb89e4fb4303841966e4062a76ab97451e3b9fb526a5ceb7f82,
0xe026cc5a4aed3c22a58cbd3d2ac754c9352c5436f638042dca99034e83636516,
0x3d04cffd8b46a874edf5cfae63077de85f849a660426697b06a829c70dd1409c,
0xad676aa337a485e4728a0b240d92b3ef7b3c372d06d189322bfd5f61f1e7203e,
0xa2fca4a49658f9fab7aa63289c91b7c7b6c832a6d0e69334ff5b0a3483d09dab,
0x4ebfd9cd7bca2505f7bef59cc1c12ecc708fff26ae4af19abe852afe9e20c862,
0x2def10d13dd169f550f578bda343d9717a138562e0093b380a1120789d53cf10
];
// Reserve memory space for our hashes.
bytes memory buf = new bytes(64);
// We'll need to keep track of left and right siblings.
bytes32 leftSibling;
bytes32 rightSibling;
// Number of non-empty nodes at the current depth.
uint256 rowSize = _elements.length;
// Current depth, counting from 0 at the leaves
uint256 depth = 0;
// Common sub-expressions
uint256 halfRowSize; // rowSize / 2
bool rowSizeIsOdd; // rowSize % 2 == 1
while (rowSize > 1) {
halfRowSize = rowSize / 2;
rowSizeIsOdd = rowSize % 2 == 1;
for (uint256 i = 0; i < halfRowSize; i++) {
leftSibling = _elements[(2 * i)];
rightSibling = _elements[(2 * i) + 1];
assembly {
mstore(add(buf, 32), leftSibling)
mstore(add(buf, 64), rightSibling)
}
_elements[i] = keccak256(buf);
}
if (rowSizeIsOdd) {
leftSibling = _elements[rowSize - 1];
rightSibling = bytes32(defaults[depth]);
assembly {
mstore(add(buf, 32), leftSibling)
mstore(add(buf, 64), rightSibling)
}
_elements[halfRowSize] = keccak256(buf);
}
rowSize = halfRowSize + (rowSizeIsOdd ? 1 : 0);
depth++;
}
return _elements[0];
}
/**
* Verifies a merkle branch for the given leaf hash. Assumes the original length
* of leaves generated is a known, correct input, and does not return true for indices
* extending past that index (even if _siblings would be otherwise valid.)
* @param _root The Merkle root to verify against.
* @param _leaf The leaf hash to verify inclusion of.
* @param _index The index in the tree of this leaf.
* @param _siblings Array of sibline nodes in the inclusion proof, starting from depth 0
* (bottom of the tree).
* @param _totalLeaves The total number of leaves originally passed into.
* @return Whether or not the merkle branch and leaf passes verification.
*/
function verify(
bytes32 _root,
bytes32 _leaf,
uint256 _index,
bytes32[] memory _siblings,
uint256 _totalLeaves
) internal pure returns (bool) {
require(_totalLeaves > 0, "Lib_MerkleTree: Total leaves must be greater than zero.");
require(_index < _totalLeaves, "Lib_MerkleTree: Index out of bounds.");
require(
_siblings.length == _ceilLog2(_totalLeaves),
"Lib_MerkleTree: Total siblings does not correctly correspond to total leaves."
);
bytes32 computedRoot = _leaf;
for (uint256 i = 0; i < _siblings.length; i++) {
if ((_index & 1) == 1) {
computedRoot = keccak256(abi.encodePacked(_siblings[i], computedRoot));
} else {
computedRoot = keccak256(abi.encodePacked(computedRoot, _siblings[i]));
}
_index >>= 1;
}
return _root == computedRoot;
}
/*********************
* Private Functions *
*********************/
/**
* Calculates the integer ceiling of the log base 2 of an input.
* @param _in Unsigned input to calculate the log.
* @return ceil(log_base_2(_in))
*/
function _ceilLog2(uint256 _in) private pure returns (uint256) {
require(_in > 0, "Lib_MerkleTree: Cannot compute ceil(log_2) of 0.");
if (_in == 1) {
return 0;
}
// Find the highest set bit (will be floor(log_2)).
// Borrowed with <3 from https://github.com/ethereum/solidity-examples
uint256 val = _in;
uint256 highest = 0;
for (uint256 i = 128; i >= 1; i >>= 1) {
if (val & (((uint256(1) << i) - 1) << i) != 0) {
highest += i;
val >>= i;
}
}
// Increment by one if this is not a perfect logarithm.
if ((uint256(1) << highest) != _in) {
highest += 1;
}
return highest;
}
}
// File contracts/L1/rollup/IChainStorageContainer.sol
// MIT
pragma solidity >0.5.0 <0.9.0;
/**
* @title IChainStorageContainer
*/
interface IChainStorageContainer {
/********************
* Public Functions *
********************/
/**
* Sets the container's global metadata field. We're using `bytes27` here because we use five
* bytes to maintain the length of the underlying data structure, meaning we have an extra
* 27 bytes to store arbitrary data.
* @param _globalMetadata New global metadata to set.
*/
function setGlobalMetadata(bytes27 _globalMetadata) external;
/**
* Retrieves the container's global metadata field.
* @return Container global metadata field.
*/
function getGlobalMetadata() external view returns (bytes27);
/**
* Retrieves the number of objects stored in the container.
* @return Number of objects in the container.
*/
function length() external view returns (uint256);
/**
* Pushes an object into the container.
* @param _object A 32 byte value to insert into the container.
*/
function push(bytes32 _object) external;
/**
* Pushes an object into the container. Function allows setting the global metadata since
* we'll need to touch the "length" storage slot anyway, which also contains the global
* metadata (it's an optimization).
* @param _object A 32 byte value to insert into the container.
* @param _globalMetadata New global metadata for the container.
*/
function push(bytes32 _object, bytes27 _globalMetadata) external;
/**
* Set an object into the container. Function allows setting the global metadata since
* we'll need to touch the "length" storage slot anyway, which also contains the global
* metadata (it's an optimization).
* @param _index position.
* @param _object A 32 byte value to insert into the container.
*/
function setByChainId(
uint256 _chainId,
uint256 _index,
bytes32 _object
)
external;
/**
* Retrieves an object from the container.
* @param _index Index of the particular object to access.
* @return 32 byte object value.
*/
function get(uint256 _index) external view returns (bytes32);
/**
* Removes all objects after and including a given index.
* @param _index Object index to delete from.
*/
function deleteElementsAfterInclusive(uint256 _index) external;
/**
* Removes all objects after and including a given index. Also allows setting the global
* metadata field.
* @param _index Object index to delete from.
* @param _globalMetadata New global metadata for the container.
*/
function deleteElementsAfterInclusive(uint256 _index, bytes27 _globalMetadata) external;
/**
* Sets the container's global metadata field. We're using `bytes27` here because we use five
* bytes to maintain the length of the underlying data structure, meaning we have an extra
* 27 bytes to store arbitrary data.
* @param _chainId identity for the l2 chain.
* @param _globalMetadata New global metadata to set.
*/
function setGlobalMetadataByChainId(
uint256 _chainId,
bytes27 _globalMetadata
)
external;
/**
* Retrieves the container's global metadata field.
* @param _chainId identity for the l2 chain.
* @return Container global metadata field.
*/
function getGlobalMetadataByChainId(
uint256 _chainId
)
external
view
returns (
bytes27
);
/**
* Retrieves the number of objects stored in the container.
* @param _chainId identity for the l2 chain.
* @return Number of objects in the container.
*/
function lengthByChainId(
uint256 _chainId
)
external
view
returns (
uint256
);
/**
* Pushes an object into the container.
* @param _chainId identity for the l2 chain.
* @param _object A 32 byte value to insert into the container.
*/
function pushByChainId(
uint256 _chainId,
bytes32 _object
)
external;
/**
* Pushes an object into the container. Function allows setting the global metadata since
* we'll need to touch the "length" storage slot anyway, which also contains the global
* metadata (it's an optimization).
* @param _chainId identity for the l2 chain.
* @param _object A 32 byte value to insert into the container.
* @param _globalMetadata New global metadata for the container.
*/
function pushByChainId(
uint256 _chainId,
bytes32 _object,
bytes27 _globalMetadata
)
external;
/**
* Retrieves an object from the container.
* @param _chainId identity for the l2 chain.
* @param _index Index of the particular object to access.
* @return 32 byte object value.
*/
function getByChainId(
uint256 _chainId,
uint256 _index
)
external
view
returns (
bytes32
);
/**
* Removes all objects after and including a given index.
* @param _chainId identity for the l2 chain.
* @param _index Object index to delete from.
*/
function deleteElementsAfterInclusiveByChainId(
uint256 _chainId,
uint256 _index
)
external;
/**
* Removes all objects after and including a given index. Also allows setting the global
* metadata field.
* @param _chainId identity for the l2 chain.
* @param _index Object index to delete from.
* @param _globalMetadata New global metadata for the container.
*/
function deleteElementsAfterInclusiveByChainId(
uint256 _chainId,
uint256 _index,
bytes27 _globalMetadata
)
external;
}
// File contracts/L1/rollup/IStateCommitmentChain.sol
// MIT
pragma solidity >0.5.0 <0.9.0;
/* Library Imports */
/**
* @title IStateCommitmentChain
*/
interface IStateCommitmentChain {
/**********
* Events *
**********/
event StateBatchAppended(
uint256 _chainId,
uint256 indexed _batchIndex,
bytes32 _batchRoot,
uint256 _batchSize,
uint256 _prevTotalElements,
bytes _extraData
);
event StateBatchDeleted(
uint256 _chainId,
uint256 indexed _batchIndex,
bytes32 _batchRoot
);
/********************
* Public Functions *
********************/
function batches() external view returns (IChainStorageContainer);
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElements() external view returns (uint256 _totalElements);
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatches() external view returns (uint256 _totalBatches);
/**
* Retrieves the timestamp of the last batch submitted by the sequencer.
* @return _lastSequencerTimestamp Last sequencer batch timestamp.
*/
function getLastSequencerTimestamp() external view returns (uint256 _lastSequencerTimestamp);
/**
* Appends a batch of state roots to the chain.
* @param _batch Batch of state roots.
* @param _shouldStartAtElement Index of the element at which this batch should start.
*/
function appendStateBatch(bytes32[] calldata _batch, uint256 _shouldStartAtElement) external;
/**
* Deletes all state roots after (and including) a given batch.
* @param _batchHeader Header of the batch to start deleting from.
*/
function deleteStateBatch(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) external;
/**
* Verifies a batch inclusion proof.
* @param _element Hash of the element to verify a proof for.
* @param _batchHeader Header of the batch in which the element was included.
* @param _proof Merkle inclusion proof for the element.
*/
function verifyStateCommitment(
bytes32 _element,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _proof
) external view returns (bool _verified);
/**
* Checks whether a given batch is still inside its fraud proof window.
* @param _batchHeader Header of the batch to check.
* @return _inside Whether or not the batch is inside the fraud proof window.
*/
function insideFraudProofWindow(Lib_OVMCodec.ChainBatchHeader memory _batchHeader)
external
view
returns (
bool _inside
);
/********************
* chain id added func *
********************/
/**
* Retrieves the total number of elements submitted.
* @param _chainId identity for the l2 chain.
* @return _totalElements Total submitted elements.
*/
function getTotalElementsByChainId(uint256 _chainId)
external
view
returns (
uint256 _totalElements
);
/**
* Retrieves the total number of batches submitted.
* @param _chainId identity for the l2 chain.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatchesByChainId(uint256 _chainId)
external
view
returns (
uint256 _totalBatches
);
/**
* Retrieves the timestamp of the last batch submitted by the sequencer.
* @param _chainId identity for the l2 chain.
* @return _lastSequencerTimestamp Last sequencer batch timestamp.
*/
function getLastSequencerTimestampByChainId(uint256 _chainId)
external
view
returns (
uint256 _lastSequencerTimestamp
);
/**
* Appends a batch of state roots to the chain.
* @param _chainId identity for the l2 chain.
* @param _batch Batch of state roots.
* @param _shouldStartAtElement Index of the element at which this batch should start.
*/
function appendStateBatchByChainId(
uint256 _chainId,
bytes32[] calldata _batch,
uint256 _shouldStartAtElement,
string calldata proposer
)
external;
/**
* Deletes all state roots after (and including) a given batch.
* @param _chainId identity for the l2 chain.
* @param _batchHeader Header of the batch to start deleting from.
*/
function deleteStateBatchByChainId(
uint256 _chainId,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
external;
/**
* Verifies a batch inclusion proof.
* @param _chainId identity for the l2 chain.
* @param _element Hash of the element to verify a proof for.
* @param _batchHeader Header of the batch in which the element was included.
* @param _proof Merkle inclusion proof for the element.
*/
function verifyStateCommitmentByChainId(
uint256 _chainId,
bytes32 _element,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _proof
)
external
view
returns (
bool _verified
);
/**
* Checks whether a given batch is still inside its fraud proof window.
* @param _chainId identity for the l2 chain.
* @param _batchHeader Header of the batch to check.
* @return _inside Whether or not the batch is inside the fraud proof window.
*/
function insideFraudProofWindowByChainId(
uint256 _chainId,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
external
view
returns (
bool _inside
);
}
// File contracts/MVM/MVM_Verifier.sol
// MIT
pragma solidity ^0.8.9;
/* Contract Imports */
/* External Imports */
contract MVM_Verifier is Lib_AddressResolver{
// second slot
address public metis;
enum SETTLEMENT {NOT_ENOUGH_VERIFIER, SAME_ROOT, AGREE, DISAGREE, PASS}
event NewChallenge(uint256 cIndex, uint256 chainID, Lib_OVMCodec.ChainBatchHeader header, uint256 timestamp);
event Verify1(uint256 cIndex, address verifier);
event Verify2(uint256 cIndex, address verifier);
event Finalize(uint256 cIndex, address sender, SETTLEMENT result);
event Penalize(address sender, uint256 stakeLost);
event Reward(address target, uint256 amount);
event Claim(address sender, uint256 amount);
event Withdraw(address sender, uint256 amount);
event Stake(address verifier, uint256 amount);
event SlashSequencer(uint256 chainID, address seq);
/*************
* Constants *
*************/
string constant public CONFIG_OWNER_KEY = "METIS_MANAGER";
//challenge info
struct Challenge {
address challenger;
uint256 chainID;
uint256 index;
Lib_OVMCodec.ChainBatchHeader header;
uint256 timestamp;
uint256 numQualifiedVerifiers;
uint256 numVerifiers;
address[] verifiers;
bool done;
}
mapping (address => uint256) public verifier_stakes;
mapping (uint256 => mapping (address=>bytes)) private challenge_keys;
mapping (uint256 => mapping (address=>bytes)) private challenge_key_hashes;
mapping (uint256 => mapping (address=>bytes)) private challenge_hashes;
mapping (address => uint256) public rewards;
mapping (address => uint8) public absence_strikes;
mapping (address => uint8) public consensus_strikes;
// only one active challenge for each chain chainid=>cIndex
mapping (uint256 => uint256) public chain_under_challenge;
// white list
mapping (address => bool) public whitelist;
bool useWhiteList;
address[] public verifiers;
Challenge[] public challenges;
uint public verifyWindow = 3600 * 24; // 24 hours of window to complete the each verify phase
uint public activeChallenges;
uint256 public minStake;
uint256 public seqStake;
uint256 public numQualifiedVerifiers;
uint FAIL_THRESHOLD = 2; // 1 time grace
uint ABSENCE_THRESHOLD = 4; // 2 times grace
modifier onlyManager {
require(
msg.sender == resolve(CONFIG_OWNER_KEY),
"MVM_Verifier: Function can only be called by the METIS_MANAGER."
);
_;
}
modifier onlyWhitelisted {
require(isWhiteListed(msg.sender), "only whitelisted verifiers can call");
_;
}
modifier onlyStaked {
require(isSufficientlyStaked(msg.sender), "insufficient stake");
_;
}
constructor(
)
Lib_AddressResolver(address(0))
{
}
// add stake as a verifier
function verifierStake(uint256 stake) public onlyWhitelisted{
require(activeChallenges == 0, "stake is currently prohibited"); //ongoing challenge
require(stake > 0, "zero stake not allowed");
require(IERC20(metis).transferFrom(msg.sender, address(this), stake), "transfer metis failed");
uint256 previousBalance = verifier_stakes[msg.sender];
verifier_stakes[msg.sender] += stake;
require(isSufficientlyStaked(msg.sender), "insufficient stake to qualify as a verifier");
if (previousBalance == 0) {
numQualifiedVerifiers++;
verifiers.push(msg.sender);
}
emit Stake(msg.sender, stake);
}
// start a new challenge
// @param chainID chainid
// @param header chainbatch header
// @param proposedHash encrypted hash of the correct state
// @param keyhash hash of the decryption key
//
// @dev why do we ask for key and keyhash? because we want verifiers compute the state instead
// of just copying from other verifiers.
function newChallenge(uint256 chainID, Lib_OVMCodec.ChainBatchHeader calldata header, bytes calldata proposedHash, bytes calldata keyhash)
public onlyWhitelisted onlyStaked {
uint tempIndex = chain_under_challenge[chainID] - 1;
require(tempIndex == 0 || block.timestamp - challenges[tempIndex].timestamp > verifyWindow * 2, "there is an ongoing challenge");
if (tempIndex > 0) {
finalize(tempIndex);
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
// while the root is encrypted, the timestamp is available in the extradata field of the header
require(stateChain.insideFraudProofWindow(header), "the batch is outside of the fraud proof window");
Challenge memory c;
c.chainID = chainID;
c.challenger = msg.sender;
c.timestamp = block.timestamp;
c.header = header;
challenges.push(c);
uint cIndex = challenges.length - 1;
// house keeping
challenge_hashes[cIndex][msg.sender] = proposedHash;
challenge_key_hashes[cIndex][msg.sender] = keyhash;
challenges[cIndex].numVerifiers++; // the challenger
// this will prevent stake change
activeChallenges++;
chain_under_challenge[chainID] = cIndex + 1; // +1 because 0 means no in-progress challenge
emit NewChallenge(cIndex, chainID, header, block.timestamp);
}
// phase 1 of the verify, provide an encrypted hash and the hash of the decryption key
// @param cIndex index of the challenge
// @param hash encrypted hash of the correct state (for the index referred in the challenge)
// @param keyhash hash of the decryption key
function verify1(uint256 cIndex, bytes calldata hash, bytes calldata keyhash) public onlyWhitelisted onlyStaked{
require(challenge_hashes[cIndex][msg.sender].length == 0, "verify1 already completed for the sender");
challenge_hashes[cIndex][msg.sender] = hash;
challenge_key_hashes[cIndex][msg.sender] = keyhash;
challenges[cIndex].numVerifiers++;
emit Verify1(cIndex, msg.sender);
}
// phase 2 of the verify, provide the actual key to decrypt the hash
// @param cIndex index of the challenge
// @param key the decryption key
function verify2(uint256 cIndex, bytes calldata key) public onlyStaked onlyWhitelisted{
require(challenges[cIndex].numVerifiers == numQualifiedVerifiers
|| block.timestamp - challenges[cIndex].timestamp > verifyWindow, "phase 2 not ready");
require(challenge_hashes[cIndex][msg.sender].length > 0, "you didn't participate in phase 1");
if (challenge_keys[cIndex][msg.sender].length > 0) {
finalize(cIndex);
return;
}
//verify whether the key matches the keyhash initially provided.
require(sha256(key) == bytes32(challenge_key_hashes[cIndex][msg.sender]), "key and keyhash don't match");
if (msg.sender == challenges[cIndex].challenger) {
//decode the root in the header too
challenges[cIndex].header.batchRoot = bytes32(decrypt(abi.encodePacked(challenges[cIndex].header.batchRoot), key));
}
challenge_keys[cIndex][msg.sender] = key;
challenge_hashes[cIndex][msg.sender] = decrypt(challenge_hashes[cIndex][msg.sender], key);
challenges[cIndex].verifiers.push(msg.sender);
emit Verify2(cIndex, msg.sender);
finalize(cIndex);
}
function finalize(uint256 cIndex) internal {
Challenge storage challenge = challenges[cIndex];
require(challenge.done == false, "challenge is closed");
if (challenge.verifiers.length != challenge.numVerifiers
&& block.timestamp - challenge.timestamp < verifyWindow * 2) {
// not ready to finalize. do nothing
return;
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]);
uint reward = 0;
address[] memory agrees = new address[](challenge.verifiers.length);
uint numAgrees = 0;
address[] memory disagrees = new address[](challenge.verifiers.length);
uint numDisagrees = 0;
for (uint256 i = 0; i < verifiers.length; i++) {
if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) {
// not qualified as a verifier
continue;
}
//record the agreement
if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) {
//agree with the challenger
if (absence_strikes[verifiers[i]] > 0) {
absence_strikes[verifiers[i]] -= 1; // slowly clear the strike
}
agrees[numAgrees] = verifiers[i];
numAgrees++;
} else if (challenge_keys[cIndex][verifiers[i]].length == 0) {
//absent
absence_strikes[verifiers[i]] += 2;
if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) {
reward += penalize(verifiers[i]);
}
} else {
//disagree with the challenger
if (absence_strikes[verifiers[i]] > 0) {
absence_strikes[verifiers[i]] -= 1; // slowly clear the strike
}
disagrees[numDisagrees] = verifiers[i];
numDisagrees++;
}
}
if (Lib_OVMCodec.hashBatchHeader(challenge.header) !=
stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) {
// wrong header, penalize the challenger
reward += penalize(challenge.challenger);
// reward the disagrees. but no penalty on agrees because the input
// is garbage.
distributeReward(reward, disagrees, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
} else if (challenge.verifiers.length < numQualifiedVerifiers * 75 / 100) {
// the absent verifiers get a absense strike. no other penalties. already done
emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER);
}
else if (proposedHash != challenge.header.batchRoot) {
if (numAgrees <= numDisagrees) {
// no consensus, challenge failed.
for (uint i = 0; i < numAgrees; i++) {
consensus_strikes[agrees[i]] += 2;
if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) {
reward += penalize(agrees[i]);
}
}
distributeReward(reward, disagrees, disagrees.length);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
} else {
// reached agreement. delete the batch root and slash the sequencer if the header is still valid
if(stateChain.insideFraudProofWindow(challenge.header)) {
// this header needs to be within the window
stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header);
// temporary for the p1 of the decentralization roadmap
if (seqStake > 0) {
reward += seqStake;
for (uint i = 0; i < numDisagrees; i++) {
consensus_strikes[disagrees[i]] += 2;
if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) {
reward += penalize(disagrees[i]);
}
}
distributeReward(reward, agrees, agrees.length);
}
emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE);
} else {
//not in the window anymore. let it pass... no penalty
emit Finalize(cIndex, msg.sender, SETTLEMENT.PASS);
}
}
} else {
//wasteful challenge, add consensus_strikes to the challenger
consensus_strikes[challenge.challenger] += 2;
if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) {
reward += penalize(challenge.challenger);
}
distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT);
}
challenge.done = true;
activeChallenges--;
chain_under_challenge[challenge.chainID] = 0;
}
function depositSeqStake(uint256 amount) public onlyManager {
require(IERC20(metis).transferFrom(msg.sender, address(this), amount), "transfer metis failed");
seqStake += amount;
emit Stake(msg.sender, amount);
}
function withdrawSeqStake(address to) public onlyManager {
require(seqStake > 0, "no stake");
emit Withdraw(msg.sender, seqStake);
uint256 amount = seqStake;
seqStake = 0;
require(IERC20(metis).transfer(to, amount), "transfer metis failed");
}
function claim() public {
require(rewards[msg.sender] > 0, "no reward to claim");
uint256 amount = rewards[msg.sender];
rewards[msg.sender] = 0;
require(IERC20(metis).transfer(msg.sender, amount), "token transfer failed");
emit Claim(msg.sender, amount);
}
function withdraw(uint256 amount) public {
require(activeChallenges == 0, "withdraw is currently prohibited"); //ongoing challenge
uint256 balance = verifier_stakes[msg.sender];
require(balance >= amount, "insufficient stake to withdraw");
if (balance - amount < minStake && balance >= minStake) {
numQualifiedVerifiers--;
deleteVerifier(msg.sender);
}
verifier_stakes[msg.sender] -= amount;
require(IERC20(metis).transfer(msg.sender, amount), "token transfer failed");
}
function setMinStake(
uint256 _minStake
)
public
onlyManager
{
minStake = _minStake;
uint num = 0;
if (verifiers.length > 0) {
address[] memory arr = new address[](verifiers.length);
for (uint i = 0; i < verifiers.length; ++i) {
if (verifier_stakes[verifiers[i]] >= minStake) {
arr[num] = verifiers[i];
num++;
}
}
if (num < verifiers.length) {
delete verifiers;
for (uint i = 0; i < num; i++) {
verifiers.push(arr[i]);
}
}
}
numQualifiedVerifiers = num;
}
// helper
function isWhiteListed(address verifier) view public returns(bool){
return !useWhiteList || whitelist[verifier];
}
function isSufficientlyStaked (address target) view public returns(bool) {
return (verifier_stakes[target] >= minStake);
}
// set the length of the time windows for each verification phase
function setVerifyWindow (uint256 window) onlyManager public {
verifyWindow = window;
}
// add the verifier to the whitelist
function setWhiteList(address verifier, bool allowed) public onlyManager {
whitelist[verifier] = allowed;
useWhiteList = true;
}
// allow everyone to be the verifier
function disableWhiteList() public onlyManager {
useWhiteList = false;
}
function setThreshold(uint absence_threshold, uint fail_threshold) public onlyManager {
ABSENCE_THRESHOLD = absence_threshold;
FAIL_THRESHOLD = fail_threshold;
}
function getMerkleRoot(bytes32[] calldata elements) pure public returns (bytes32) {
return Lib_MerkleTree.getMerkleRoot(elements);
}
//helper fucntion to encrypt data
function encrypt(bytes calldata data, bytes calldata key) pure public returns (bytes memory) {
bytes memory encryptedData = data;
uint j = 0;
for (uint i = 0; i < encryptedData.length; i++) {
if (j == key.length) {
j = 0;
}
encryptedData[i] = encryptByte(encryptedData[i], uint8(key[j]));
j++;
}
return encryptedData;
}
function encryptByte(bytes1 b, uint8 k) pure internal returns (bytes1) {
uint16 temp16 = uint16(uint8(b));
temp16 += k;
if (temp16 > 255) {
temp16 -= 256;
}
return bytes1(uint8(temp16));
}
// helper fucntion to decrypt the data
function decrypt(bytes memory data, bytes memory key) pure public returns (bytes memory) {
bytes memory decryptedData = data;
uint j = 0;
for (uint i = 0; i < decryptedData.length; i++) {
if (j == key.length) {
j = 0;
}
decryptedData[i] = decryptByte(decryptedData[i], uint8(key[j]));
j++;
}
return decryptedData;
}
function decryptByte(bytes1 b, uint8 k) pure internal returns (bytes1) {
uint16 temp16 = uint16(uint8(b));
if (temp16 > k) {
temp16 -= k;
} else {
temp16 = 256 - k;
}
return bytes1(uint8(temp16));
}
// calculate the rewards
function distributeReward(uint256 amount, address[] memory list, uint num) internal {
uint reward = amount / num;
if (reward == 0) {
return;
}
uint total = 0;
for (uint i; i < list.length; i++) {
if (isSufficientlyStaked(list[i])) {
rewards[list[i]] += reward;
total += reward;
emit Reward(list[i], reward);
}
}
if (total < amount) {
if (isSufficientlyStaked(list[0])) {
rewards[list[0]] += total - amount;
emit Reward(list[0], total - amount);
} else {
rewards[list[1]] += total - amount;
emit Reward(list[1], total - amount);
}
}
}
// slash the verifier stake
function penalize(address target) internal returns(uint256) {
uint256 stake = verifier_stakes[target];
verifier_stakes[target] = 0;
numQualifiedVerifiers--;
deleteVerifier(target);
emit Penalize(target, stake);
return stake;
}
function deleteVerifier(address target) internal {
bool hasVerifier = false;
uint pos = 0;
for (uint i = 0; i < verifiers.length; i++){
if (verifiers[i] == target) {
hasVerifier = true;
pos = i;
break;
}
}
if (hasVerifier) {
for (uint i = pos; i < verifiers.length-1; i++) {
verifiers[i] = verifiers[i+1];
}
verifiers.pop();
}
}
} | Copies a piece of memory to another location. _dest Destination location. _src Source location. _len Length of memory to copy./ | function _memcpy(
uint256 _dest,
uint256 _src,
uint256 _len
) private pure {
uint256 dest = _dest;
uint256 src = _src;
uint256 len = _len;
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint256 mask;
unchecked {
mask = 256**(32 - len) - 1;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
| 366,129 |
./partial_match/8453/0xD65Abd7014B638e4b9b8657063389Eb1abB9689a/sources/contracts/enforcer/HolographRoyalties.sol | Gets the default royalty base points(percentage) from storage slot. return bp Royalty base points(percentage) for royalty payouts./ | function _getDefaultBp() private view returns (uint256 bp) {
assembly {
bp := sload(_defaultBpSlot)
}
}
| 16,799,295 |
pragma solidity ^0.5.9;
// Files Validator
contract Validator{
mapping(string => bytes32) public files_hashes;
// add file to the validator
function add_file_hash(string calldata _file_name, bytes32 _file_hash) external {
files_hashes[_file_name] = _file_hash;
}
// a casting function
function bytes32array_to_bytes(bytes32[] memory bytes32array) pure internal returns(bytes memory) {
uint nonzero_bytes = uint8(bytes32array[0][0]);
bytes memory _bytes = new bytes((bytes32array.length - 2) * 32 + nonzero_bytes);
uint ind = 0;
for (uint i = 0; i < bytes32array.length - 2; i++) {
for(uint j = 0; j < 32; j++) {
_bytes[ind] = bytes32array[i+1][j];
ind = ind + 1;
}
}
for (uint j = 0; j < nonzero_bytes; j++) {
_bytes[ind] = bytes32array[bytes32array.length-1][j];
ind = ind + 1;
}
return _bytes;
}
// check if a question is valid
function is_valid_question(bytes32[] calldata _question) view external returns(bool){
bytes memory question = bytes32array_to_bytes(_question);
string memory file_name = string(question);
// does the validator has the files' info?
if (files_hashes[file_name] != bytes32(0)) {
return true;
}
return false;
}
// check if the answer is valid (assuming the question is valid)
function is_answer_correct(bytes32[] calldata _question, bytes32[] calldata _answer) view external returns(bool){
bytes memory question = bytes32array_to_bytes(_question);
bytes memory answer = bytes32array_to_bytes(_answer);
string memory file_name = string(question);
// does the files' hash correct?
if (keccak256(answer) == files_hashes[file_name]) {
return true;
}
return false;
}
} | check if a question is valid does the validator has the files' info? | function is_valid_question(bytes32[] calldata _question) view external returns(bool){
bytes memory question = bytes32array_to_bytes(_question);
string memory file_name = string(question);
if (files_hashes[file_name] != bytes32(0)) {
return true;
}
return false;
}
| 1,048,278 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.10 <0.8.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "../utils/SafeDecimalMath.sol";
import "../utils/CoreUtility.sol";
import "../interfaces/IPrimaryMarket.sol";
import "../interfaces/IFund.sol";
import "../interfaces/ITwapOracle.sol";
import "../interfaces/IAprOracle.sol";
import "../interfaces/IBallot.sol";
import "../interfaces/IVotingEscrow.sol";
import "../interfaces/ITrancheIndex.sol";
import "./FundRoles.sol";
contract Fund is IFund, Ownable, ReentrancyGuard, FundRoles, CoreUtility, ITrancheIndex {
using Math for uint256;
using SafeMath for uint256;
using SafeDecimalMath for uint256;
using SafeERC20 for IERC20;
uint256 private constant UNIT = 1e18;
uint256 private constant MAX_INTEREST_RATE = 0.2e18; // 20% daily
uint256 private constant MAX_DAILY_PROTOCOL_FEE_RATE = 0.05e18; // 5% daily rate
uint256 private constant WEIGHT_A = 1;
uint256 private constant WEIGHT_B = 1;
uint256 private constant WEIGHT_M = WEIGHT_A + WEIGHT_B;
/// @notice Upper bound of `NAV_B / NAV_A` to trigger a rebalance.
uint256 public immutable upperRebalanceThreshold;
/// @notice Lower bound of `NAV_B / NAV_A` to trigger a rebalance.
uint256 public immutable lowerRebalanceThreshold;
/// @notice Address of the underlying token.
address public immutable override tokenUnderlying;
/// @notice A multipler that normalizes an underlying balance to 18 decimal places.
uint256 public immutable override underlyingDecimalMultiplier;
/// @notice Daily protocol fee rate.
uint256 public dailyProtocolFeeRate;
/// @notice TwapOracle address for the underlying asset.
ITwapOracle public override twapOracle;
/// @notice AprOracle address.
IAprOracle public aprOracle;
/// @notice Address of the interest rate ballot.
IBallot public ballot;
/// @notice Fee Collector address.
address public override feeCollector;
/// @notice Address of Token M.
address public override tokenM;
/// @notice Address of Token A.
address public override tokenA;
/// @notice Address of Token B.
address public override tokenB;
/// @notice End timestamp of the current trading day.
/// A trading day starts at UTC time `SETTLEMENT_TIME` of a day (inclusive)
/// and ends at the same time of the next day (exclusive).
uint256 public override currentDay;
/// @notice Start timestamp of the current primary market activity window.
uint256 public override fundActivityStartTime;
/// @notice Start timestamp of the current exchange activity window.
uint256 public override exchangeActivityStartTime;
uint256 public activityDelayTimeAfterRebalance;
/// @dev Historical rebalances. Rebalances are often accessed in loops with bounds checking.
/// So we store them in a fixed-length array, in order to make compiler-generated
/// bounds checking on every access cheaper. The actual length of this array is stored in
/// `_rebalanceSize` and should be explicitly checked when necessary.
Rebalance[65535] private _rebalances;
/// @dev Historical rebalance count.
uint256 private _rebalanceSize;
/// @dev Total share supply of the three tranches. They are always rebalanced to the latest
/// version.
uint256[TRANCHE_COUNT] private _totalSupplies;
/// @dev Mapping of account => share balance of the three tranches.
/// Rebalance versions are stored in a separate mapping `_balanceVersions`.
mapping(address => uint256[TRANCHE_COUNT]) private _balances;
/// @dev Rebalance version mapping for `_balances`.
mapping(address => uint256) private _balanceVersions;
/// @dev Mapping of owner => spender => share allowance of the three tranches.
/// Rebalance versions are stored in a separate mapping `_allowanceVersions`.
mapping(address => mapping(address => uint256[TRANCHE_COUNT])) private _allowances;
/// @dev Rebalance version mapping for `_allowances`.
mapping(address => mapping(address => uint256)) private _allowanceVersions;
/// @dev Mapping of trading day => NAV tuple.
mapping(uint256 => uint256[TRANCHE_COUNT]) private _historicalNavs;
/// @notice Mapping of trading day => total fund shares.
///
/// Key is the end timestamp of a trading day. Value is the total fund shares after
/// settlement of that trading day, as if all Token A and B are merged.
mapping(uint256 => uint256) public override historicalTotalShares;
/// @notice Mapping of trading day => underlying assets in the fund.
///
/// Key is the end timestamp of a trading day. Value is the underlying assets in
/// the fund after settlement of that trading day.
mapping(uint256 => uint256) public historicalUnderlying;
/// @notice Mapping of trading week => interest rate of Token A.
///
/// Key is the end timestamp of a trading week. Value is the interest rate captured
/// after settlement of the last day of the previous trading week.
mapping(uint256 => uint256) public historicalInterestRate;
address[] private obsoletePrimaryMarkets;
address[] private newPrimaryMarkets;
constructor(
address tokenUnderlying_,
uint256 underlyingDecimals_,
uint256 dailyProtocolFeeRate_,
uint256 upperRebalanceThreshold_,
uint256 lowerRebalanceThreshold_,
address twapOracle_,
address aprOracle_,
address ballot_,
address feeCollector_
) public Ownable() FundRoles() {
tokenUnderlying = tokenUnderlying_;
require(underlyingDecimals_ <= 18, "Underlying decimals larger than 18");
underlyingDecimalMultiplier = 10**(18 - underlyingDecimals_);
require(
dailyProtocolFeeRate_ <= MAX_DAILY_PROTOCOL_FEE_RATE,
"Exceed max protocol fee rate"
);
dailyProtocolFeeRate = dailyProtocolFeeRate_;
upperRebalanceThreshold = upperRebalanceThreshold_;
lowerRebalanceThreshold = lowerRebalanceThreshold_;
twapOracle = ITwapOracle(twapOracle_);
aprOracle = IAprOracle(aprOracle_);
ballot = IBallot(ballot_);
feeCollector = feeCollector_;
currentDay = endOfDay(block.timestamp);
uint256 lastDay = currentDay - 1 days;
uint256 currentPrice = twapOracle.getTwap(lastDay);
require(currentPrice != 0, "Price not available");
_historicalNavs[lastDay][TRANCHE_M] = UNIT;
_historicalNavs[lastDay][TRANCHE_A] = UNIT;
_historicalNavs[lastDay][TRANCHE_B] = UNIT;
historicalInterestRate[_endOfWeek(lastDay)] = MAX_INTEREST_RATE.min(aprOracle.capture());
fundActivityStartTime = lastDay;
exchangeActivityStartTime = lastDay + 30 minutes;
activityDelayTimeAfterRebalance = 12 hours;
}
function initialize(
address tokenM_,
address tokenA_,
address tokenB_,
address primaryMarket_
) external onlyOwner {
require(tokenM == address(0) && tokenM_ != address(0), "Already initialized");
tokenM = tokenM_;
tokenA = tokenA_;
tokenB = tokenB_;
_initializeRoles(tokenM_, tokenA_, tokenB_, primaryMarket_);
}
/// @notice Return weights of Token A and B when splitting Token M.
/// @return weightA Weight of Token A
/// @return weightB Weight of Token B
function trancheWeights() external pure override returns (uint256 weightA, uint256 weightB) {
return (WEIGHT_A, WEIGHT_B);
}
/// @notice UTC time of a day when the fund settles.
function settlementTime() external pure returns (uint256) {
return SETTLEMENT_TIME;
}
/// @notice Return end timestamp of the trading day containing a given timestamp.
///
/// A trading day starts at UTC time `SETTLEMENT_TIME` of a day (inclusive)
/// and ends at the same time of the next day (exclusive).
/// @param timestamp The given timestamp
/// @return End timestamp of the trading day.
function endOfDay(uint256 timestamp) public pure override returns (uint256) {
return ((timestamp.add(1 days) - SETTLEMENT_TIME) / 1 days) * 1 days + SETTLEMENT_TIME;
}
/// @notice Return end timestamp of the trading week containing a given timestamp.
///
/// A trading week starts at UTC time `SETTLEMENT_TIME` on a Thursday (inclusive)
/// and ends at the same time of the next Thursday (exclusive).
/// @param timestamp The given timestamp
/// @return End timestamp of the trading week.
function endOfWeek(uint256 timestamp) external pure returns (uint256) {
return _endOfWeek(timestamp);
}
/// @notice Return the status of the fund contract.
/// @param timestamp Timestamp to assess
/// @return True if the fund contract is active
function isFundActive(uint256 timestamp) public view override returns (bool) {
return timestamp >= fundActivityStartTime;
}
/// @notice Return the status of a given primary market contract.
/// @param primaryMarket The primary market contract address
/// @param timestamp Timestamp to assess
/// @return True if the primary market contract is active
function isPrimaryMarketActive(address primaryMarket, uint256 timestamp)
public
view
override
returns (bool)
{
return
isPrimaryMarket(primaryMarket) &&
timestamp >= fundActivityStartTime &&
timestamp < currentDay;
}
/// @notice Return the status of the exchange. Unlike the primary market, exchange is
/// anonymous to fund
/// @param timestamp Timestamp to assess
/// @return True if the exchange contract is active
function isExchangeActive(uint256 timestamp) public view override returns (bool) {
return (timestamp >= exchangeActivityStartTime && timestamp < (currentDay - 60 minutes));
}
/// @notice Total shares of the fund, as if all Token A and B are merged.
function getTotalShares() public view override returns (uint256) {
return
_totalSupplies[TRANCHE_M].add(_totalSupplies[TRANCHE_A]).add(_totalSupplies[TRANCHE_B]);
}
/// @notice Return the rebalance matrix at a given index. A zero struct is returned
/// if `index` is out of bound.
/// @param index Rebalance index
/// @return A rebalance matrix
function getRebalance(uint256 index) external view override returns (Rebalance memory) {
return _rebalances[index];
}
/// @notice Return timestamp of the transaction triggering the rebalance at a given index.
/// Zero is returned if `index` is out of bound.
/// @param index Rebalance index
/// @return Timestamp of the rebalance
function getRebalanceTimestamp(uint256 index) external view override returns (uint256) {
return _rebalances[index].timestamp;
}
/// @notice Return the number of historical rebalances.
function getRebalanceSize() external view override returns (uint256) {
return _rebalanceSize;
}
/// @notice Return NAV of Token M, A and B of the given trading day.
/// @param day End timestamp of a trading day
/// @return NAV of Token M, A and B
function historicalNavs(uint256 day)
external
view
override
returns (
uint256,
uint256,
uint256
)
{
return (
_historicalNavs[day][TRANCHE_M],
_historicalNavs[day][TRANCHE_A],
_historicalNavs[day][TRANCHE_B]
);
}
/// @notice Estimate NAV of all tranches at a given timestamp, considering underlying price
/// change, accrued protocol fee and accrued interest since the previous settlement.
///
/// The extrapolation uses simple interest instead of daily compound interest in
/// calculating protocol fee and Token A's interest. There may be significant error
/// in the returned values when `timestamp` is far beyond the last settlement.
/// @param timestamp Timestamp to estimate
/// @param price Price of the underlying asset (18 decimal places)
/// @return Estimated NAV of all tranches
function extrapolateNav(uint256 timestamp, uint256 price)
external
view
override
returns (
uint256,
uint256,
uint256
)
{
// Find the last settled trading day before the given timestamp.
uint256 previousDay = currentDay - 1 days;
if (previousDay > timestamp) {
previousDay = endOfDay(timestamp) - 1 days;
}
uint256 previousShares = historicalTotalShares[previousDay];
uint256 navM = _extrapolateNavM(previousDay, previousShares, timestamp, price);
uint256 navA = _extrapolateNavA(previousDay, previousShares, timestamp);
uint256 navB = calculateNavB(navM, navA);
return (navM, navA, navB);
}
function _extrapolateNavM(
uint256 previousDay,
uint256 previousShares,
uint256 timestamp,
uint256 price
) private view returns (uint256) {
uint256 navM;
if (previousShares == 0) {
// The fund is empty. Just return the previous recorded NAV.
navM = _historicalNavs[previousDay][TRANCHE_M];
if (navM == 0) {
// No NAV is recorded because the given timestamp is before the fund launches.
return UNIT;
} else {
return navM;
}
}
uint256 totalValue =
price.mul(historicalUnderlying[previousDay].mul(underlyingDecimalMultiplier));
uint256 accruedFee =
totalValue.multiplyDecimal(dailyProtocolFeeRate).mul(timestamp - previousDay).div(
1 days
);
navM = (totalValue - accruedFee).div(previousShares);
return navM;
}
function _extrapolateNavA(
uint256 previousDay,
uint256 previousShares,
uint256 timestamp
) private view returns (uint256) {
uint256 navA = _historicalNavs[previousDay][TRANCHE_A];
if (previousShares == 0) {
// The fund is empty. Just return the previous recorded NAV.
if (navA == 0) {
// No NAV is recorded because the given timestamp is before the fund launches.
return UNIT;
} else {
return navA;
}
}
uint256 week = _endOfWeek(previousDay);
uint256 newNavA =
navA
.multiplyDecimal(
UNIT.sub(dailyProtocolFeeRate.mul(timestamp - previousDay).div(1 days))
)
.multiplyDecimal(
UNIT.add(historicalInterestRate[week].mul(timestamp - previousDay).div(1 days))
);
return newNavA > navA ? newNavA : navA;
}
function calculateNavB(uint256 navM, uint256 navA) public pure override returns (uint256) {
// Using unchecked multiplications because they are unlikely to overflow
if (navM * WEIGHT_M >= navA * WEIGHT_A) {
return (navM * WEIGHT_M - navA * WEIGHT_A) / WEIGHT_B;
} else {
return 0;
}
}
/// @notice Transform share amounts according to the rebalance at a given index.
/// This function performs no bounds checking on the given index. A non-existent
/// rebalance transforms anything to a zero vector.
/// @param amountM Amount of Token M before the rebalance
/// @param amountA Amount of Token A before the rebalance
/// @param amountB Amount of Token B before the rebalance
/// @param index Rebalance index
/// @return newAmountM Amount of Token M after the rebalance
/// @return newAmountA Amount of Token A after the rebalance
/// @return newAmountB Amount of Token B after the rebalance
function doRebalance(
uint256 amountM,
uint256 amountA,
uint256 amountB,
uint256 index
)
public
view
override
returns (
uint256 newAmountM,
uint256 newAmountA,
uint256 newAmountB
)
{
Rebalance storage rebalance = _rebalances[index];
newAmountM = amountM
.multiplyDecimal(rebalance.ratioM)
.add(amountA.multiplyDecimal(rebalance.ratioA2M))
.add(amountB.multiplyDecimal(rebalance.ratioB2M));
uint256 ratioAB = rebalance.ratioAB; // Gas saver
newAmountA = amountA.multiplyDecimal(ratioAB);
newAmountB = amountB.multiplyDecimal(ratioAB);
}
/// @notice Transform share amounts according to rebalances in a given index range,
/// This function performs no bounds checking on the given indices. The original amounts
/// are returned if `fromIndex` is no less than `toIndex`. A zero vector is returned
/// if `toIndex` is greater than the number of existing rebalances.
/// @param amountM Amount of Token M before the rebalance
/// @param amountA Amount of Token A before the rebalance
/// @param amountB Amount of Token B before the rebalance
/// @param fromIndex Starting of the rebalance index range, inclusive
/// @param toIndex End of the rebalance index range, exclusive
/// @return newAmountM Amount of Token M after the rebalance
/// @return newAmountA Amount of Token A after the rebalance
/// @return newAmountB Amount of Token B after the rebalance
function batchRebalance(
uint256 amountM,
uint256 amountA,
uint256 amountB,
uint256 fromIndex,
uint256 toIndex
)
external
view
override
returns (
uint256 newAmountM,
uint256 newAmountA,
uint256 newAmountB
)
{
for (uint256 i = fromIndex; i < toIndex; i++) {
(amountM, amountA, amountB) = doRebalance(amountM, amountA, amountB, i);
}
newAmountM = amountM;
newAmountA = amountA;
newAmountB = amountB;
}
/// @notice Transform share balance to a given rebalance version, or to the latest version
/// if `targetVersion` is zero.
/// @param account Account of the balance to rebalance
/// @param targetVersion The target rebalance version, or zero for the latest version
function refreshBalance(address account, uint256 targetVersion) external override {
if (targetVersion > 0) {
require(targetVersion <= _rebalanceSize, "Target version out of bound");
}
_refreshBalance(account, targetVersion);
}
/// @notice Transform allowance to a given rebalance version, or to the latest version
/// if `targetVersion` is zero.
/// @param owner Owner of the allowance to rebalance
/// @param spender Spender of the allowance to rebalance
/// @param targetVersion The target rebalance version, or zero for the latest version
function refreshAllowance(
address owner,
address spender,
uint256 targetVersion
) external override {
if (targetVersion > 0) {
require(targetVersion <= _rebalanceSize, "Target version out of bound");
}
_refreshAllowance(owner, spender, targetVersion);
}
function shareBalanceOf(uint256 tranche, address account)
external
view
override
returns (uint256)
{
uint256 amountM = _balances[account][TRANCHE_M];
uint256 amountA = _balances[account][TRANCHE_A];
uint256 amountB = _balances[account][TRANCHE_B];
if (tranche == TRANCHE_M) {
if (amountM == 0 && amountA == 0 && amountB == 0) return 0;
} else if (tranche == TRANCHE_A) {
if (amountA == 0) return 0;
} else {
if (amountB == 0) return 0;
}
uint256 size = _rebalanceSize; // Gas saver
for (uint256 i = _balanceVersions[account]; i < size; i++) {
(amountM, amountA, amountB) = doRebalance(amountM, amountA, amountB, i);
}
if (tranche == TRANCHE_M) {
return amountM;
} else if (tranche == TRANCHE_A) {
return amountA;
} else {
return amountB;
}
}
/// @notice Return all three share balances transformed to the latest rebalance version.
/// @param account Owner of the shares
function allShareBalanceOf(address account)
external
view
override
returns (
uint256,
uint256,
uint256
)
{
uint256 amountM = _balances[account][TRANCHE_M];
uint256 amountA = _balances[account][TRANCHE_A];
uint256 amountB = _balances[account][TRANCHE_B];
uint256 size = _rebalanceSize; // Gas saver
for (uint256 i = _balanceVersions[account]; i < size; i++) {
(amountM, amountA, amountB) = doRebalance(amountM, amountA, amountB, i);
}
return (amountM, amountA, amountB);
}
function shareBalanceVersion(address account) external view override returns (uint256) {
return _balanceVersions[account];
}
function shareAllowance(
uint256 tranche,
address owner,
address spender
) external view override returns (uint256) {
uint256 allowanceM = _allowances[owner][spender][TRANCHE_M];
uint256 allowanceA = _allowances[owner][spender][TRANCHE_A];
uint256 allowanceB = _allowances[owner][spender][TRANCHE_B];
if (tranche == TRANCHE_M) {
if (allowanceM == 0) return 0;
} else if (tranche == TRANCHE_A) {
if (allowanceA == 0) return 0;
} else {
if (allowanceB == 0) return 0;
}
uint256 size = _rebalanceSize; // Gas saver
for (uint256 i = _allowanceVersions[owner][spender]; i < size; i++) {
(allowanceM, allowanceA, allowanceB) = _rebalanceAllowance(
allowanceM,
allowanceA,
allowanceB,
i
);
}
if (tranche == TRANCHE_M) {
return allowanceM;
} else if (tranche == TRANCHE_A) {
return allowanceA;
} else {
return allowanceB;
}
}
function shareAllowanceVersion(address owner, address spender)
external
view
override
returns (uint256)
{
return _allowanceVersions[owner][spender];
}
function shareTotalSupply(uint256 tranche) external view override returns (uint256) {
return _totalSupplies[tranche];
}
function mint(
uint256 tranche,
address account,
uint256 amount
) external override onlyPrimaryMarket {
_refreshBalance(account, _rebalanceSize);
_mint(tranche, account, amount);
}
function burn(
uint256 tranche,
address account,
uint256 amount
) external override onlyPrimaryMarket {
_refreshBalance(account, _rebalanceSize);
_burn(tranche, account, amount);
}
function transfer(
uint256 tranche,
address sender,
address recipient,
uint256 amount
) public override onlyShare {
require(isFundActive(block.timestamp), "Transfer is inactive");
_refreshBalance(sender, _rebalanceSize);
_refreshBalance(recipient, _rebalanceSize);
_transfer(tranche, sender, recipient, amount);
}
function transferFrom(
uint256 tranche,
address spender,
address sender,
address recipient,
uint256 amount
) external override onlyShare returns (uint256 newAllowance) {
transfer(tranche, sender, recipient, amount);
_refreshAllowance(sender, spender, _rebalanceSize);
newAllowance = _allowances[sender][spender][tranche].sub(
amount,
"ERC20: transfer amount exceeds allowance"
);
_approve(tranche, sender, spender, newAllowance);
}
function approve(
uint256 tranche,
address owner,
address spender,
uint256 amount
) external override onlyShare {
_refreshAllowance(owner, spender, _rebalanceSize);
_approve(tranche, owner, spender, amount);
}
function increaseAllowance(
uint256 tranche,
address sender,
address spender,
uint256 addedValue
) external override onlyShare returns (uint256 newAllowance) {
_refreshAllowance(sender, spender, _rebalanceSize);
newAllowance = _allowances[sender][spender][tranche].add(addedValue);
_approve(tranche, sender, spender, newAllowance);
}
function decreaseAllowance(
uint256 tranche,
address sender,
address spender,
uint256 subtractedValue
) external override onlyShare returns (uint256 newAllowance) {
_refreshAllowance(sender, spender, _rebalanceSize);
newAllowance = _allowances[sender][spender][tranche].sub(subtractedValue);
_approve(tranche, sender, spender, newAllowance);
}
function _transfer(
uint256 tranche,
address sender,
address recipient,
uint256 amount
) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender][tranche] = _balances[sender][tranche].sub(
amount,
"ERC20: transfer amount exceeds balance"
);
_balances[recipient][tranche] = _balances[recipient][tranche].add(amount);
emit Transfer(tranche, sender, recipient, amount);
}
function _mint(
uint256 tranche,
address account,
uint256 amount
) private {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupplies[tranche] = _totalSupplies[tranche].add(amount);
_balances[account][tranche] = _balances[account][tranche].add(amount);
emit Transfer(tranche, address(0), account, amount);
}
function _burn(
uint256 tranche,
address account,
uint256 amount
) private {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account][tranche] = _balances[account][tranche].sub(
amount,
"ERC20: burn amount exceeds balance"
);
_totalSupplies[tranche] = _totalSupplies[tranche].sub(amount);
emit Transfer(tranche, account, address(0), amount);
}
function _approve(
uint256 tranche,
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender][tranche] = amount;
emit Approval(tranche, owner, spender, amount);
}
/// @notice Settle the current trading day. Settlement includes the following changes
/// to the fund.
///
/// 1. Transfer protocol fee of the day to the fee collector.
/// 2. Settle all pending creations and redemptions from all primary markets.
/// 3. Calculate NAV of the day and trigger rebalance if necessary.
/// 4. Capture new interest rate for Token A.
function settle() external nonReentrant {
uint256 day = currentDay;
uint256 currentWeek = _endOfWeek(day - 1 days);
require(block.timestamp >= day, "The current trading day does not end yet");
uint256 price = twapOracle.getTwap(day);
require(price != 0, "Underlying price for settlement is not ready yet");
_collectFee();
_settlePrimaryMarkets(day, price);
// Calculate NAV
uint256 totalShares = getTotalShares();
uint256 underlying = IERC20(tokenUnderlying).balanceOf(address(this));
uint256 navA = _historicalNavs[day - 1 days][TRANCHE_A];
uint256 navM;
if (totalShares > 0) {
navM = price.mul(underlying.mul(underlyingDecimalMultiplier)).div(totalShares);
if (historicalTotalShares[day - 1 days] > 0) {
// Update NAV of Token A only when the fund is non-empty both before and after
// this settlement
uint256 newNavA =
navA.multiplyDecimal(UNIT.sub(dailyProtocolFeeRate)).multiplyDecimal(
historicalInterestRate[currentWeek].add(UNIT)
);
if (navA < newNavA) {
navA = newNavA;
}
}
} else {
// If the fund is empty, use NAV of Token M in the last day
navM = _historicalNavs[day - 1 days][TRANCHE_M];
}
uint256 navB = calculateNavB(navM, navA);
if (_shouldTriggerRebalance(navA, navB)) {
_triggerRebalance(day, navM, navA, navB);
navM = UNIT;
navA = UNIT;
navB = UNIT;
totalShares = getTotalShares();
fundActivityStartTime = day + activityDelayTimeAfterRebalance;
exchangeActivityStartTime = day + activityDelayTimeAfterRebalance;
} else {
fundActivityStartTime = day;
exchangeActivityStartTime = day + 30 minutes;
}
if (currentDay == currentWeek) {
historicalInterestRate[currentWeek + 1 weeks] = _updateInterestRate(currentWeek);
}
historicalTotalShares[day] = totalShares;
historicalUnderlying[day] = underlying;
_historicalNavs[day][TRANCHE_M] = navM;
_historicalNavs[day][TRANCHE_A] = navA;
_historicalNavs[day][TRANCHE_B] = navB;
currentDay = day + 1 days;
if (obsoletePrimaryMarkets.length > 0) {
for (uint256 i = 0; i < obsoletePrimaryMarkets.length; i++) {
_removePrimaryMarket(obsoletePrimaryMarkets[i]);
}
delete obsoletePrimaryMarkets;
}
if (newPrimaryMarkets.length > 0) {
for (uint256 i = 0; i < newPrimaryMarkets.length; i++) {
_addPrimaryMarket(newPrimaryMarkets[i]);
}
delete newPrimaryMarkets;
}
emit Settled(day, navM, navA, navB);
}
function addObsoletePrimaryMarket(address obsoletePrimaryMarket) external onlyOwner {
require(isPrimaryMarket(obsoletePrimaryMarket), "The address is not a primary market");
obsoletePrimaryMarkets.push(obsoletePrimaryMarket);
}
function addNewPrimaryMarket(address newPrimaryMarket) external onlyOwner {
require(!isPrimaryMarket(newPrimaryMarket), "The address is already a primary market");
newPrimaryMarkets.push(newPrimaryMarket);
}
function updateDailyProtocolFeeRate(uint256 newDailyProtocolFeeRate) external onlyOwner {
require(
newDailyProtocolFeeRate <= MAX_DAILY_PROTOCOL_FEE_RATE,
"Exceed max protocol fee rate"
);
dailyProtocolFeeRate = newDailyProtocolFeeRate;
}
function updateTwapOracle(address newTwapOracle) external onlyOwner {
twapOracle = ITwapOracle(newTwapOracle);
}
function updateAprOracle(address newAprOracle) external onlyOwner {
aprOracle = IAprOracle(newAprOracle);
}
function updateBallot(address newBallot) external onlyOwner {
ballot = IBallot(newBallot);
}
function updateFeeCollector(address newFeeCollector) external onlyOwner {
feeCollector = newFeeCollector;
}
function updateActivityDelayTime(uint256 delayTime) external onlyOwner {
require(
delayTime >= 30 minutes && delayTime <= 12 hours,
"Exceed allowed delay time range"
);
activityDelayTimeAfterRebalance = delayTime;
}
/// @dev Transfer protocol fee of the current trading day to the fee collector.
/// This function should be called before creation and redemption on the same day
/// are settled.
function _collectFee() private {
uint256 currentUnderlying = IERC20(tokenUnderlying).balanceOf(address(this));
uint256 fee = currentUnderlying.multiplyDecimal(dailyProtocolFeeRate);
if (fee > 0) {
IERC20(tokenUnderlying).safeTransfer(address(feeCollector), fee);
}
}
/// @dev Settle primary market operations in every PrimaryMarket contract.
function _settlePrimaryMarkets(uint256 day, uint256 price) private {
uint256 totalShares = getTotalShares();
uint256 underlying = IERC20(tokenUnderlying).balanceOf(address(this));
uint256 prevNavM = _historicalNavs[day - 1 days][TRANCHE_M];
uint256 primaryMarketCount = getPrimaryMarketCount();
for (uint256 i = 0; i < primaryMarketCount; i++) {
uint256 price_ = price; // Fix the "stack too deep" error
IPrimaryMarket pm = IPrimaryMarket(getPrimaryMarketMember(i));
(
uint256 sharesToMint,
uint256 sharesToBurn,
uint256 creationUnderlying,
uint256 redemptionUnderlying,
uint256 fee
) = pm.settle(day, totalShares, underlying, price_, prevNavM);
if (sharesToMint > sharesToBurn) {
_mint(TRANCHE_M, address(pm), sharesToMint - sharesToBurn);
} else if (sharesToBurn > sharesToMint) {
_burn(TRANCHE_M, address(pm), sharesToBurn - sharesToMint);
}
if (creationUnderlying > redemptionUnderlying) {
IERC20(tokenUnderlying).safeTransferFrom(
address(pm),
address(this),
creationUnderlying - redemptionUnderlying
);
} else if (redemptionUnderlying > creationUnderlying) {
IERC20(tokenUnderlying).safeTransfer(
address(pm),
redemptionUnderlying - creationUnderlying
);
}
if (fee > 0) {
IERC20(tokenUnderlying).safeTransfer(address(feeCollector), fee);
}
}
}
/// @dev Check whether a new rebalance should be triggered. Rebalance is triggered if
/// NAV of Token B over NAV of Token A is greater than the upper threshold or
/// less than the lower threshold.
/// @param navA NAV of Token A before the rebalance
/// @param navBOrZero NAV of Token B before the rebalance or zero if the NAV is negative
/// @return Whether a new rebalance should be triggered
function _shouldTriggerRebalance(uint256 navA, uint256 navBOrZero) private view returns (bool) {
uint256 bOverA = navBOrZero.divideDecimal(navA);
return bOverA < lowerRebalanceThreshold || bOverA > upperRebalanceThreshold;
}
/// @dev Create a new rebalance that resets NAV of all tranches to 1. Total supplies are
/// rebalanced immediately.
/// @param day Trading day that triggers this rebalance
/// @param navM NAV of Token M before this rebalance
/// @param navA NAV of Token A before this rebalance
/// @param navBOrZero NAV of Token B before this rebalance or zero if the NAV is negative
function _triggerRebalance(
uint256 day,
uint256 navM,
uint256 navA,
uint256 navBOrZero
) private {
Rebalance memory rebalance = _calculateRebalance(navM, navA, navBOrZero);
uint256 oldSize = _rebalanceSize;
_rebalances[oldSize] = rebalance;
_rebalanceSize = oldSize + 1;
emit RebalanceTriggered(
oldSize,
day,
rebalance.ratioM,
rebalance.ratioA2M,
rebalance.ratioB2M,
rebalance.ratioAB
);
(
_totalSupplies[TRANCHE_M],
_totalSupplies[TRANCHE_A],
_totalSupplies[TRANCHE_B]
) = doRebalance(
_totalSupplies[TRANCHE_M],
_totalSupplies[TRANCHE_A],
_totalSupplies[TRANCHE_B],
oldSize
);
_refreshBalance(address(this), oldSize + 1);
}
/// @dev Create a new rebalance matrix that resets given NAVs to (1, 1, 1).
///
/// Note that NAV of Token B can be negative before the rebalance when the underlying price
/// drops dramatically in a single trading day, in which case zero should be passed to
/// this function instead of the negative NAV.
/// @param navM NAV of Token M before the rebalance
/// @param navA NAV of Token A before the rebalance
/// @param navBOrZero NAV of Token B before the rebalance or zero if the NAV is negative
/// @return The rebalance matrix
function _calculateRebalance(
uint256 navM,
uint256 navA,
uint256 navBOrZero
) private view returns (Rebalance memory) {
uint256 ratioAB;
uint256 ratioA2M;
uint256 ratioB2M;
if (navBOrZero <= navA) {
// Lower rebalance
ratioAB = navBOrZero;
ratioA2M = ((navM - navBOrZero) * WEIGHT_M) / WEIGHT_A;
ratioB2M = 0;
} else {
// Upper rebalance
ratioAB = UNIT;
ratioA2M = navA - UNIT;
ratioB2M = navBOrZero - UNIT;
}
return
Rebalance({
ratioM: navM,
ratioA2M: ratioA2M,
ratioB2M: ratioB2M,
ratioAB: ratioAB,
timestamp: block.timestamp
});
}
function _updateInterestRate(uint256 week) private returns (uint256) {
uint256 baseInterestRate = MAX_INTEREST_RATE.min(aprOracle.capture());
uint256 floatingInterestRate = ballot.count(week).div(365);
uint256 rate = baseInterestRate.add(floatingInterestRate);
emit InterestRateUpdated(baseInterestRate, floatingInterestRate);
return rate;
}
/// @dev Transform share balance to a given rebalance version, or to the latest version
/// if `targetVersion` is zero. This function does no bound check on `targetVersion`.
/// @param account Account of the balance to rebalance
/// @param targetVersion The target rebalance version, or zero for the latest version
function _refreshBalance(address account, uint256 targetVersion) private {
if (targetVersion == 0) {
targetVersion = _rebalanceSize;
}
uint256 oldVersion = _balanceVersions[account];
if (oldVersion >= targetVersion) {
return;
}
uint256[TRANCHE_COUNT] storage balanceTuple = _balances[account];
uint256 balanceM = balanceTuple[TRANCHE_M];
uint256 balanceA = balanceTuple[TRANCHE_A];
uint256 balanceB = balanceTuple[TRANCHE_B];
_balanceVersions[account] = targetVersion;
if (balanceM == 0 && balanceA == 0 && balanceB == 0) {
// Fast path for an empty account
return;
}
for (uint256 i = oldVersion; i < targetVersion; i++) {
(balanceM, balanceA, balanceB) = doRebalance(balanceM, balanceA, balanceB, i);
}
balanceTuple[TRANCHE_M] = balanceM;
balanceTuple[TRANCHE_A] = balanceA;
balanceTuple[TRANCHE_B] = balanceB;
emit BalancesRebalanced(account, targetVersion, balanceM, balanceA, balanceB);
}
/// @dev Transform allowance to a given rebalance version, or to the latest version
/// if `targetVersion` is zero. This function does no bound check on `targetVersion`.
/// @param owner Owner of the allowance to rebalance
/// @param spender Spender of the allowance to rebalance
/// @param targetVersion The target rebalance version, or zero for the latest version
function _refreshAllowance(
address owner,
address spender,
uint256 targetVersion
) private {
if (targetVersion == 0) {
targetVersion = _rebalanceSize;
}
uint256 oldVersion = _allowanceVersions[owner][spender];
if (oldVersion >= targetVersion) {
return;
}
uint256[TRANCHE_COUNT] storage allowanceTuple = _allowances[owner][spender];
uint256 allowanceM = allowanceTuple[TRANCHE_M];
uint256 allowanceA = allowanceTuple[TRANCHE_A];
uint256 allowanceB = allowanceTuple[TRANCHE_B];
_allowanceVersions[owner][spender] = targetVersion;
if (allowanceM == 0 && allowanceA == 0 && allowanceB == 0) {
// Fast path for an empty allowance
return;
}
for (uint256 i = oldVersion; i < targetVersion; i++) {
(allowanceM, allowanceA, allowanceB) = _rebalanceAllowance(
allowanceM,
allowanceA,
allowanceB,
i
);
}
allowanceTuple[TRANCHE_M] = allowanceM;
allowanceTuple[TRANCHE_A] = allowanceA;
allowanceTuple[TRANCHE_B] = allowanceB;
emit AllowancesRebalanced(
owner,
spender,
targetVersion,
allowanceM,
allowanceA,
allowanceB
);
}
function _rebalanceAllowance(
uint256 allowanceM,
uint256 allowanceA,
uint256 allowanceB,
uint256 index
)
private
view
returns (
uint256 newAllowanceM,
uint256 newAllowanceA,
uint256 newAllowanceB
)
{
Rebalance storage rebalance = _rebalances[index];
/// @dev using saturating arithmetic to avoid unconscious overflow revert
newAllowanceM = allowanceM.saturatingMultiplyDecimal(rebalance.ratioM);
newAllowanceA = allowanceA.saturatingMultiplyDecimal(rebalance.ratioAB);
newAllowanceB = allowanceB.saturatingMultiplyDecimal(rebalance.ratioAB);
}
}
| Total shares of the fund, as if all Token A and B are merged. | function getTotalShares() public view override returns (uint256) {
return
_totalSupplies[TRANCHE_M].add(_totalSupplies[TRANCHE_A]).add(_totalSupplies[TRANCHE_B]);
}
| 12,579,391 |
./partial_match/4/0x84F7d65E1D82cb8c839b21945c085eC794D93d5b/sources/TetherToken.sol | Forward ERC20 methods to upgraded contract if this one is deprecated | function approve(address _spender, uint256 _value)
public
virtual
override
onlyPayloadSize(2 * 32)
{
if (deprecated) {
return
UpgradedStandardToken(upgradedAddress).approveByLegacy(
msg.sender,
_spender,
_value
);
return super.approve(_spender, _value);
}
}
| 8,758,946 |
// SPDX-License-Identifier: Unlicense
pragma solidity >=0.6.2;
import './Utilities.sol';
/// @notice ERC-20 contract with support for EIP-2612 and other niceties.
contract HabitatToken is Utilities {
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _allowances;
mapping (address => uint256) _nonces;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
constructor () {
_balances[msg.sender] = totalSupply();
}
/// @notice Returns the name of token.
function name () public virtual view returns (string memory) {
return 'Habitat Token';
}
/// @notice Returns the symbol of the token.
function symbol () public virtual view returns (string memory) {
return 'HBT';
}
/// @notice Returns the number of decimals the token uses.
function decimals () public virtual view returns (uint8) {
return 10;
}
/// @notice Returns the DOMAIN_SEPARATOR. See EIP-2612.
function DOMAIN_SEPARATOR () public virtual view returns (bytes32 ret) {
assembly {
// load free memory ptr
let ptr := mload(64)
// keep a copy to calculate the length later
let start := ptr
// keccak256('EIP712Domain(string name,uint256 chainId,address verifyingContract)')
mstore(ptr, 0x8cad95687ba82c2ce50e74f7b754645e5117c3a5bec8151c0726d5857980a866)
ptr := add(ptr, 32)
// keccak256(bytes('Habitat Token'))
mstore(ptr, 0x825a5bd2b322b183692110889ab8fda39cd7c633901fc90cea3ce579a5694e95)
ptr := add(ptr, 32)
// store chainid
mstore(ptr, chainid())
ptr := add(ptr, 32)
// store address(this)
mstore(ptr, address())
ptr := add(ptr, 32)
// hash
ret := keccak256(start, sub(ptr, start))
}
}
/// @notice Returns the total supply of this token.
function totalSupply () public virtual view returns (uint256) {
return 1000000000000000000;
}
/// @notice Returns the balance of `account`.
function balanceOf (address account) public virtual view returns (uint256) {
return _balances[account];
}
/// @notice Returns the allowance for `spender` of `account`.
function allowance (address account, address spender) public virtual view returns (uint256) {
return _allowances[account][spender];
}
/// @notice Returns the nonce of `account`. Used in `permit`. See EIP-2612.
function nonces (address account) public virtual view returns (uint256) {
return _nonces[account];
}
/// @notice Approves `amount` from sender to be spend by `spender`.
/// @param spender Address of the party that can draw from msg.sender's account.
/// @param amount The maximum collective amount that `spender` can draw.
/// @return (bool) Returns True if approved.
function approve (address spender, uint256 amount) public virtual returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
/// @dev The concrete implementation of `approve`.
function _approve (address owner, address spender, uint256 value) internal virtual {
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
/// @dev The concrete implementation of `transfer` and `transferFrom`.
function _transferFrom (address from, address to, uint256 value) internal virtual returns (bool) {
uint256 balance = _balances[from];
require(balance >= value, 'BALANCE');
if (from != to) {
_balances[from] = balance - value;
balance = _balances[to];
uint256 newBalance = balance + value;
// overflow check, also reverts if `value` is zero
require(newBalance > balance, 'OVERFLOW');
_balances[to] = newBalance;
}
emit Transfer(from, to, value);
return true;
}
/// @notice Transfers `amount` tokens from `msg.sender` to `to`.
/// @param to The address to move the tokens.
/// @param amount of the tokens to move.
/// @return (bool) Returns True if succeeded.
function transfer (address to, uint256 amount) public virtual returns (bool) {
return _transferFrom(msg.sender, to, amount);
}
/// @notice Transfers `amount` tokens from `from` to `to`. Caller may need approval if `from` is not `msg.sender`.
/// @param from Address to draw tokens from.
/// @param to The address to move the tokens.
/// @param amount The token amount to move.
/// @return (bool) Returns True if succeeded.
function transferFrom (address from, address to, uint256 amount) public virtual returns (bool) {
uint256 _allowance = _allowances[from][msg.sender];
require(_allowance >= amount, 'ALLOWANCE');
if (_allowance != uint256(-1)) {
_allowances[from][msg.sender] = _allowance - amount;
}
return _transferFrom(from, to, amount);
}
/// @notice Approves `value` from `owner` to be spend by `spender`.
/// @param owner Address of the owner.
/// @param spender The address of the spender that gets approved to draw from `owner`.
/// @param value The maximum collective amount that `spender` can draw.
/// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds).
function permit (
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(owner != address(0), 'OWNER');
require(block.timestamp < deadline, 'EXPIRED');
uint256 nonce = _nonces[owner]++;
bytes32 domainSeparator = DOMAIN_SEPARATOR();
bytes32 digest;
assembly {
// ptr to free memory
let ptr := mload(64)
// keep a copy to calculate the length later
let start := ptr
// keccak256('Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)');
mstore(ptr, 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9)
ptr := add(ptr, 32)
// copy (owner, spender, value) from calldata in one go
calldatacopy(ptr, 4, 96)
ptr := add(ptr, 96)
// store nonce
mstore(ptr, nonce)
ptr := add(ptr, 32)
// store deadline
mstore(ptr, deadline)
ptr := add(ptr, 32)
// Permit struct hash
let permitStructHash := keccak256(start, sub(ptr, start))
// reset ptr
ptr := start
// add 30 bytes to align correctly (0x1901)
start := add(ptr, 30)
// preamble
mstore(ptr, 0x1901)
ptr := add(ptr, 32)
// DOMAIN_SEPARATOR
mstore(ptr, domainSeparator)
ptr := add(ptr, 32)
// from above
mstore(ptr, permitStructHash)
ptr := add(ptr, 32)
// hash it
digest := keccak256(start, sub(ptr, start))
}
require(ecrecover(digest, v, r, s) == owner, 'SIG');
_approve(owner, spender, value);
}
/// @dev Helper function for wrapping calls. Reverts on a call to 'self'.
function _callWrapper (address to, bytes calldata data) internal returns (bytes memory) {
require(to != address(this));
(bool success, bytes memory ret) = to.call(data);
require(success);
return ret;
}
/// @notice Transfers `amount` from `msg.sender` to `to` and calls `to` with `data` as input.
/// Reverts if not succesful. Otherwise returns any data from the call.
function transferAndCall (address to, uint256 amount, bytes calldata data) external returns (bytes memory) {
_transferFrom(msg.sender, to, amount);
return _callWrapper(to, data);
}
/// @notice Approves `amount` from `msg.sender` to be spend by `to` and calls `to` with `data` as input.
/// Reverts if not succesful. Otherwise returns any data from the call.
function approveAndCall (address to, uint256 amount, bytes calldata data) external returns (bytes memory) {
_approve(msg.sender, to, amount);
return _callWrapper(to, data);
}
/// @notice Redeems a permit for this contract (`permitData`) and calls `to` with `data` as input.
/// Reverts if not succesful. Otherwise returns any data from the call.
function redeemPermitAndCall (address to, bytes calldata permitData, bytes calldata data) external returns (bytes memory) {
Utilities._maybeRedeemPermit(address(this), permitData);
return _callWrapper(to, data);
}
/// @notice Allows to recover `token`.
/// Transfers `token` to `msg.sender`.
/// @param token The address of the ERC-20 token to recover.
function recoverLostTokens (address token) external {
Utilities._safeTransfer(token, msg.sender, Utilities._safeBalance(token, address(this)));
}
}
| Approves `amount` from sender to be spend by `spender`. spender Address of the party that can draw from msg.sender's account. amount The maximum collective amount that `spender` can draw. return (bool) Returns True if approved. | function approve (address spender, uint256 amount) public virtual returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
| 5,466,821 |
./full_match/40/0x41c98Ba90f8f5555C269d3Fb63f3B8E5033d75aA/sources/omnidex/omnidex-pools/CharmVaultV2.sol | Reinvests CHARM tokens into ZenMaster Only possible when contract not paused./ | function harvest(address _caller) external onlyAuthorized whenNotPaused {
IZenMaster(zenmaster).leaveStaking(0);
uint256 bal = available();
uint256 currentPerformanceFee = bal.mul(performanceFee).div(10000);
token.safeTransfer(treasury, currentPerformanceFee);
uint256 currentCallFee = bal.mul(callFee).div(10000);
token.safeTransfer(_caller, currentCallFee);
uint256 currentBurnFee = bal.mul(burnFee).div(10000);
token.safeTransfer(furnace, currentBurnFee);
_earn();
lastHarvestedTime = block.timestamp;
emit Harvest(_caller, currentPerformanceFee, currentCallFee);
}
| 9,550,184 |
pragma solidity ^0.4.20;
pragma experimental ABIEncoderV2;
import "github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol";
// Changed MAGic to Magic
// Changed ua to userAddress
contract MagicIDContract is usingOraclize{
address public contractOwner;
mapping (bytes32 => uint16) uin_version;
mapping (bytes32 => uint16) agency_version;
bytes32 public uin;
bytes32 public agencyID;
bytes32 public uinOraclizeID;
bytes32 public agencyIDOraclizeID;
/* mapping (address => uint) AccessAgencyMap; */
mapping (address => MagicIDStruct) address_MagicIDStruct;
mapping (address => AccessAgencyStruct) address_AccessAgencyStruct;
mapping (bytes32 => address[]) MagicIDUIN_AgencyAddress;
mapping (bytes32 => address) AccessAgencyID_AccessAgencyAddress;
mapping (bytes32 => address) uin_UserAddress;
/* mapping (address => IDInstance) userAddress_IDInstance; */
// Commented here
/* mapping (address => IDInstance) User_AgencyMap; */
/* mapping (bytes32 => MagicIDStruct) uin_MagicIDElement; */
mapping (bytes32 => mapping(bytes32 => IDInstance)) uin_AgencyID_IDInstance;
/* event IDAccessed(address from, MagicIDStruct whichID); */
// Changed IDInstance
struct IDInstance {
uint time_fence;
bytes32[] location_fence;
}
// Changed parentname to parentName, rightfinger to right_finger, leftfinger to left_finger
struct MagicIDStruct {
bytes32 uin;
MagicIDStruct1 magicIDStruct1;
MagicIDStruct2 magicIDStruct2;
MagicIDStruct3 magicIDStruct3;
MagicIDStruct4 magicIDStruct4;
}
struct MagicIDStruct1 {
bytes32 name;
bytes32 gender;
bytes32 dob;
bytes32 parentName;
bytes32 personalAddress;
bytes32 mobile;
bytes32 email;
}
struct MagicIDStruct2 {
bytes32 iris_left;
bytes32 iris_right;
bytes32 face;
}
struct MagicIDStruct3 {
bytes32 right_finger_1;
bytes32 right_finger_2;
bytes32 right_finger_3;
bytes32 right_finger_4;
bytes32 right_finger_5;
}
struct MagicIDStruct4 {
bytes32 left_finger_1;
bytes32 left_finger_2;
bytes32 left_finger_3;
bytes32 left_finger_4;
bytes32 left_finger_5;
}
string[] public uinArray;
//MODIFIERS
modifier isIDOwner(bytes32 uin) {
if (msg.sender != uin_UserAddress[uin]) {
throw;
}
_; // continue executing rest of method body
}
modifier isContractOwner() {
if(msg.sender != contractOwner){
throw;
}
_; // continue executing rest of method body
}
modifier isAccessAgency() {
/* if(AccessAgencyMap[msg.sender] > 0) { */
if(!address_AccessAgencyStruct[msg.sender].isActive) {
throw;
}
_; // continue to access the ID info of the user (citizen)
}
function MagicIDContract() {
contractOwner = msg.sender;
}
function createMagicID(bytes32 uin, bytes32[] _personal) returns (bool){
uin_UserAddress[uin] = msg.sender;
var magicID1 = createMagicID1(_personal);
var magicID2 = createMagicID2(_personal);
var magicID3 = createMagicID3(_personal);
var magicID4 = createMagicID4(_personal);
MagicIDStruct memory magicID = MagicIDStruct(uin, magicID1, magicID2, magicID3, magicID4);
address_MagicIDStruct[msg.sender] = magicID;
uinArray.push(bytes32ToString(uin));
return true;
}
function createMagicID1(bytes32[] _personal) internal returns (MagicIDStruct1) {
MagicIDStruct1 ID;
ID.name = _personal[0];
ID.gender = _personal[1];
ID.dob = _personal[2];
ID.parentName = _personal[3];
ID.personalAddress = _personal[4];
ID.mobile = _personal[5];
ID.email = _personal[6];
return ID;
}
function createMagicID2(bytes32[] _personal) internal returns (MagicIDStruct2) {
MagicIDStruct2 ID;
ID.iris_left = _personal[7];
ID.iris_right = _personal[8];
ID.face = _personal[9];
return ID;
}
function createMagicID3(bytes32[] _personal) internal returns (MagicIDStruct3) {
MagicIDStruct3 ID;
ID.right_finger_1 = _personal[10];
ID.right_finger_2 = _personal[11];
ID.right_finger_3 = _personal[12];
ID.right_finger_4 = _personal[13];
ID.right_finger_5 = _personal[14];
return ID;
}
function createMagicID4(
bytes32[] _personal
) internal returns (MagicIDStruct4) {
MagicIDStruct4 ID;
ID.left_finger_1 = _personal[15];
ID.left_finger_2 = _personal[16];
ID.left_finger_3 = _personal[17];
ID.left_finger_4 = _personal[18];
ID.left_finger_5 = _personal[19];
return ID;
}
// Removed keccak256 function here. Input _time_fence in s.
function authID(bytes32 agency_id, uint _time_fence, bytes32[] _location_fence) payable returns (bool authIDStatus) {
MagicIDStruct myMagicID = address_MagicIDStruct[msg.sender];
bytes32 my_uin = myMagicID.uin;
address agencyAddress = AccessAgencyID_AccessAgencyAddress[agency_id];
// Instead of a modifier this will make sure that only the IDOowner aunthenticates himself/herself and the agency is active.
require(msg.sender == uin_UserAddress[my_uin]);
require(address_AccessAgencyStruct[agencyAddress].isActive == true);
MagicIDUIN_AgencyAddress[my_uin].push(agencyAddress);
uin_AgencyID_IDInstance[my_uin][agency_id].time_fence = now + _time_fence;
uin_AgencyID_IDInstance[my_uin][agency_id].location_fence = _location_fence;
// This is to set the uin_AgencyID_IDInstance[my_uin][agency_id].time_fence = 0 after the time_fence.
uinOraclizeID = oraclize_query(_time_fence, "URL", strConcat("json(https://lottery-0610.herokuapp.com/revoke/", bytes32ToString(my_uin), "/", bytes32ToString(agency_id), ").uin"));
agencyIDOraclizeID = oraclize_query(_time_fence, "URL", strConcat("json(https://lottery-0610.herokuapp.com/revoke/", bytes32ToString(my_uin), "/", bytes32ToString(agency_id), ").agencyID"));
return true;
}
function getMagicIDFromUIN(bytes32 uin) constant internal returns (MagicIDStruct storage) {
address userAddress = uin_UserAddress[uin];
return address_MagicIDStruct[userAddress];
}
// Change return variables' names here
function getIDUIN(bytes32 uin) constant isAccessAgency returns (bool isRet, string ret_uin) {
AccessAgencyStruct queryingAgency = address_AccessAgencyStruct[msg.sender];
if(uin_AgencyID_IDInstance[uin][queryingAgency.agency_id].time_fence < now){
return (false, "");
}
MagicIDStruct storage magicID = getMagicIDFromUIN(uin);
return (true, bytes32ToString(magicID.uin));
}
// Change return variables' names here
function getIDName(bytes32 uin) constant isAccessAgency returns (bool isRet, string ret_name) {
AccessAgencyStruct queryingAgency = address_AccessAgencyStruct[msg.sender];
if(uin_AgencyID_IDInstance[uin][queryingAgency.agency_id].time_fence < now){
return (false, "");
}
require(queryingAgency.accessAgencyStruct2.isAllowedName);
MagicIDStruct storage magicID = getMagicIDFromUIN(uin);
return (true, bytes32ToString(magicID.magicIDStruct1.name));
}
// Change return variables' names here
function getIDGender(bytes32 uin) constant isAccessAgency returns (bool isRet, string ret_gender) {
AccessAgencyStruct queryingAgency = address_AccessAgencyStruct[msg.sender];
if(uin_AgencyID_IDInstance[uin][queryingAgency.agency_id].time_fence < now){
return (false, "");
}
require(queryingAgency.accessAgencyStruct2.isAllowedGender);
MagicIDStruct storage magicID = getMagicIDFromUIN(uin);
return (true, bytes32ToString(magicID.magicIDStruct1.gender));
}
// Change return variables' names here
function getIDdob(bytes32 uin) constant isAccessAgency returns (bool isRet, string ret_dob) {
AccessAgencyStruct queryingAgency = address_AccessAgencyStruct[msg.sender];
if(uin_AgencyID_IDInstance[uin][queryingAgency.agency_id].time_fence < now){
return (false, "");
}
require(queryingAgency.accessAgencyStruct2.isAllowedDOB);
MagicIDStruct storage magicID = getMagicIDFromUIN(uin);
return (true, bytes32ToString(magicID.magicIDStruct1.dob));
}
// Change return variables' names here
function getIDParentName(bytes32 uin) constant isAccessAgency returns (bool isRet, string ret_parentName) {
AccessAgencyStruct queryingAgency = address_AccessAgencyStruct[msg.sender];
if(uin_AgencyID_IDInstance[uin][queryingAgency.agency_id].time_fence < now){
return (false, "");
}
require(queryingAgency.accessAgencyStruct2.isAllowedParentName);
MagicIDStruct storage magicID = getMagicIDFromUIN(uin);
return (true, bytes32ToString(magicID.magicIDStruct1.parentName));
}
// Change return variables' names here
function getIDaddress(bytes32 uin) constant isAccessAgency returns (bool isRet, string ret_personalAddress) {
AccessAgencyStruct queryingAgency = address_AccessAgencyStruct[msg.sender];
if(uin_AgencyID_IDInstance[uin][queryingAgency.agency_id].time_fence < now){
return (false, "");
}
require(queryingAgency.accessAgencyStruct2.isAllowedAddress);
MagicIDStruct storage magicID = getMagicIDFromUIN(uin);
return (true, bytes32ToString(magicID.magicIDStruct1.personalAddress));
}
// Change return variables' names here
function getIDmobile(bytes32 uin) constant isAccessAgency returns (bool isRet, string ret_mobile) {
AccessAgencyStruct queryingAgency = address_AccessAgencyStruct[msg.sender];
if(uin_AgencyID_IDInstance[uin][queryingAgency.agency_id].time_fence < now){
return (false, "");
}
require(queryingAgency.accessAgencyStruct2.isAllowedMobile);
MagicIDStruct storage magicID = getMagicIDFromUIN(uin);
return (true, bytes32ToString(magicID.magicIDStruct1.mobile));
}
// Change return variables' names here
function getIDemail(bytes32 uin) constant isAccessAgency returns (bool isRet, string ret_email) {
AccessAgencyStruct queryingAgency = address_AccessAgencyStruct[msg.sender];
if(uin_AgencyID_IDInstance[uin][queryingAgency.agency_id].time_fence < now){
return (false, "");
}
require(queryingAgency.accessAgencyStruct3.isAllowedEmail);
MagicIDStruct storage magicID = getMagicIDFromUIN(uin);
return (true, bytes32ToString(magicID.magicIDStruct1.email));
}
// Change return variables' names here
/* function getIDCurrentLoc(bytes32 uin) isAccessAgency returns (bool isRet, bytes32 ret_current_loc) {
AccessAgencyStruct queryingAgency = address_AccessAgencyStruct[msg.sender];
if(uin_AgencyID_IDInstance[uin][queryingAgency.agency_id].time_fence < now){
return (false, "");
}
require(queryingAgency.isAllowedCurrentLoc);
MagicIDStruct storage magicID = getMagicIDFromUIN(uin);
return (true, magicID.current_loc);
} */
// Change return variables' names here
function getBioIRIS(bytes32 uin) constant isAccessAgency returns (bool isRet, string ret_iris_left, string ret_iris_right) {
AccessAgencyStruct queryingAgency = address_AccessAgencyStruct[msg.sender];
if(uin_AgencyID_IDInstance[uin][queryingAgency.agency_id].time_fence < now){
return (false, "", "");
}
require(queryingAgency.accessAgencyStruct3.isAllowedBioIRIS);
MagicIDStruct storage magicID = getMagicIDFromUIN(uin);
return (true, bytes32ToString(magicID.magicIDStruct2.iris_left), bytes32ToString(magicID.magicIDStruct2.iris_right));
}
// Change return variables' names here
function getBioFace(bytes32 uin) constant isAccessAgency returns (bool isRet, string ret_face) {
AccessAgencyStruct queryingAgency = address_AccessAgencyStruct[msg.sender];
if(uin_AgencyID_IDInstance[uin][queryingAgency.agency_id].time_fence < now){
return (false, "");
}
require(queryingAgency.accessAgencyStruct3.isAllowedBioFace);
MagicIDStruct storage magicID = getMagicIDFromUIN(uin);
return (true, bytes32ToString(magicID.magicIDStruct2.face));
}
// Change return variables' names here
function getBioRightFingers(bytes32 uin) constant isAccessAgency returns (bool isRet, string ret_right_finger_1, string ret_right_finger_2, string ret_right_finger_3, string ret_right_finger_4,string ret_right_finger_5) {
AccessAgencyStruct queryingAgency = address_AccessAgencyStruct[msg.sender];
if(uin_AgencyID_IDInstance[uin][queryingAgency.agency_id].time_fence < now){
return (false, "", "", "", "", "");
}
require(queryingAgency.accessAgencyStruct3.isAllowedBioRightFingers);
MagicIDStruct storage magicID = getMagicIDFromUIN(uin);
return (true, bytes32ToString(magicID.magicIDStruct3.right_finger_1), bytes32ToString(magicID.magicIDStruct3.right_finger_2), bytes32ToString(magicID.magicIDStruct3.right_finger_3), bytes32ToString(magicID.magicIDStruct3.right_finger_4), bytes32ToString(magicID.magicIDStruct3.right_finger_5));
}
// Change return variables' names here
function getBioLeftFingers(bytes32 uin) constant isAccessAgency returns (bool isRet, string ret_left_finger_1, string ret_left_finger_2, string ret_left_finger_3, string ret_left_finger_4, string ret_left_finger_5) {
AccessAgencyStruct queryingAgency = address_AccessAgencyStruct[msg.sender];
if(uin_AgencyID_IDInstance[uin][queryingAgency.agency_id].time_fence < now){
return (false, "", "", "", "", "");
}
require(queryingAgency.accessAgencyStruct3.isAllowedBioLeftFingers);
MagicIDStruct storage magicID = getMagicIDFromUIN(uin);
return (true, bytes32ToString(magicID.magicIDStruct4.left_finger_1), bytes32ToString(magicID.magicIDStruct4.left_finger_2), bytes32ToString(magicID.magicIDStruct4.left_finger_3), bytes32ToString(magicID.magicIDStruct4.left_finger_4), bytes32ToString(magicID.magicIDStruct4.left_finger_5));
}
// uin_AgencyID_IDInstance for _uin => time_fence = 0.
function revokeID(bytes32 _uin, bytes32 _agencyID) internal returns (bool revokeIDStatus) {
uin_AgencyID_IDInstance[_uin][_agencyID].time_fence = 0;
return true;
}
function __callback(bytes32 oraclizeID, string _result){
// if(msg.sender != oraclize_cbAddress() || msg.sender != uin_UserAddress[stringToBytes32(_result[0])]) throw;
if(msg.sender == oraclize_cbAddress() && oraclizeID == uinOraclizeID){
uin = stringToBytes32(_result);
uin_version[uin] += 1;
}
if(msg.sender == oraclize_cbAddress() && oraclizeID == agencyIDOraclizeID){
agencyID = stringToBytes32(_result);
agency_version[agencyID] += 1;
}
// If uinOraclizeID and agencyIDOraclizeID are both true for the same version
if(uin_version[uin] == agency_version[agencyID]){
revokeID(uin, agencyID);
}
}
// Check here. Returns the addresses of the agencies who accessed user's uin (or wherever the person entered). Modifier required.
function getIDAccessors(bytes32 uin) constant isIDOwner(uin) returns (address[] accessorsArray) {
accessorsArray = MagicIDUIN_AgencyAddress[uin];
}
// Returns name and domain of the agency when given agency's address. Can be called by user as well as other agencies.
function nameResolveAgency(address _agencyAddress) returns (string, string) {
AccessAgencyStruct agency = address_AccessAgencyStruct[_agencyAddress];
return (bytes32ToString(agency.agency_name), bytes32ToString(agency.agency_domain));
}
// Code here. Who can set isActive to false? contractOwner? Resorting with contractOwner for now.
function setAgencyAccess(bytes32 _agency_id, bool _isActive) returns (bool setAgencyAccessStatus) {
address accessAgency = AccessAgencyID_AccessAgencyAddress[_agency_id];
address_AccessAgencyStruct[accessAgency].isActive = _isActive;
return true;
}
struct AccessAgencyStruct {
bytes32 agency_id;
bytes32 agency_name;
bytes32 agency_domain;
bool isActive;
AccessAgencyStruct2 accessAgencyStruct2;
AccessAgencyStruct3 accessAgencyStruct3;
}
struct AccessAgencyStruct2 {
bool isAllowedName;
bool isAllowedGender;
bool isAllowedDOB;
bool isAllowedParentName;
bool isAllowedAddress;
bool isAllowedMobile;
}
struct AccessAgencyStruct3 {
bool isAllowedEmail;
bool isAllowedBioIRIS;
bool isAllowedBioFace;
bool isAllowedBioRightFingers;
bool isAllowedBioLeftFingers;
}
string[] public AccessAgencyArray;
function createAccessAgency(bytes32 agency_id, bytes32 _agency_name, bytes32 _agency_domain, bool[] _features) returns (bool){
AccessAgencyID_AccessAgencyAddress[agency_id] = msg.sender;
var accessAgency2 = createAccessAgency2(_features);
var accessAgency3 = createAccessAgency3(_features);
// Setting isActive of agency to false. Who can set it to true is still a mystery!
AccessAgencyStruct memory agency = AccessAgencyStruct(agency_id, _agency_name, _agency_domain, false, accessAgency2, accessAgency3);
address_AccessAgencyStruct[msg.sender] = agency;
AccessAgencyArray.push(bytes32ToString(agency_id));
return true;
}
function createAccessAgency2(
bool[] _features
) internal returns (AccessAgencyStruct2) {
AccessAgencyStruct2 agencyStruct;
agencyStruct.isAllowedName = _features[0];
agencyStruct.isAllowedGender = _features[1];
agencyStruct.isAllowedDOB = _features[2];
agencyStruct.isAllowedParentName = _features[3];
agencyStruct.isAllowedAddress = _features[4];
agencyStruct.isAllowedMobile = _features[5];
return agencyStruct;
}
function createAccessAgency3(
bool[] _features
) internal returns (AccessAgencyStruct3) {
AccessAgencyStruct3 agencyStruct;
agencyStruct.isAllowedEmail = _features[6];
agencyStruct.isAllowedBioIRIS = _features[7];
agencyStruct.isAllowedBioFace = _features[8];
agencyStruct.isAllowedBioRightFingers = _features[9];
agencyStruct.isAllowedBioLeftFingers = _features[10];
return agencyStruct;
}
function bytes32ToString(bytes32 x) constant returns (string) {
bytes memory bytesString = new bytes(32);
uint charCount = 0;
for (uint j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
return string(bytesStringTrimmed);
}
function stringToBytes32(string memory source) returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
function getAgencyCount() returns (uint){
return AccessAgencyArray.length;
}
function getMemberCount() returns (uint){
return uinArray.length;
}
}
| Change return variables' names here | function getIDGender(bytes32 uin) constant isAccessAgency returns (bool isRet, string ret_gender) {
AccessAgencyStruct queryingAgency = address_AccessAgencyStruct[msg.sender];
if(uin_AgencyID_IDInstance[uin][queryingAgency.agency_id].time_fence < now){
return (false, "");
}
require(queryingAgency.accessAgencyStruct2.isAllowedGender);
MagicIDStruct storage magicID = getMagicIDFromUIN(uin);
return (true, bytes32ToString(magicID.magicIDStruct1.gender));
}
| 12,686,918 |
pragma solidity ^0.5.8;
interface ierc2068 { //inject NONSTANDARD NAMING
function TOTALSUPPLY3() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF80(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER74(address recipient, uint256 amount)external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE0(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE81(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM66(address sender,address recipient,uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER48(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL56(address indexed owner,address indexed spender,uint256 value); //inject NONSTANDARD NAMING
}
contract context27 { //inject NONSTANDARD NAMING
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER71() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
}
contract erc205 is context27, ierc2068 { //inject NONSTANDARD NAMING
using safemath98 for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
function TOTALSUPPLY3() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF80(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER74(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER57(_MSGSENDER71(), recipient, amount);
return true;
}
function ALLOWANCE0(address owner, address spender) //inject NONSTANDARD NAMING
public
view
returns (uint256)
{
return _allowances[owner][spender];
}
function APPROVE81(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE12(_MSGSENDER71(), spender, amount);
return true;
}
function TRANSFERFROM66( //inject NONSTANDARD NAMING
address sender,
address recipient,
uint256 amount
) public returns (bool) {
_TRANSFER57(sender, recipient, amount);
_APPROVE12(
sender,
_MSGSENDER71(),
_allowances[sender][_MSGSENDER71()].SUB0(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function INCREASEALLOWANCE53(address spender, uint256 addedValue) //inject NONSTANDARD NAMING
public
returns (bool)
{
_APPROVE12(
_MSGSENDER71(),
spender,
_allowances[_MSGSENDER71()][spender].ADD95(addedValue)
);
return true;
}
function DECREASEALLOWANCE27(address spender, uint256 subtractedValue) //inject NONSTANDARD NAMING
public
returns (bool)
{
_APPROVE12(
_MSGSENDER71(),
spender,
_allowances[_MSGSENDER71()][spender].SUB0(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
function _TRANSFER57( //inject NONSTANDARD NAMING
address sender,
address recipient,
uint256 amount
) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB0(
amount,
"ERC20: transfer amount exceeds balance"
);
_balances[recipient] = _balances[recipient].ADD95(amount);
emit TRANSFER48(sender, recipient, amount);
}
function _MINT16(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD95(amount);
_balances[account] = _balances[account].ADD95(amount);
emit TRANSFER48(address(0), account, amount);
}
function _BURN5(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB0(
amount,
"ERC20: burn amount exceeds balance"
);
_totalSupply = _totalSupply.SUB0(amount);
emit TRANSFER48(account, address(0), amount);
}
function _APPROVE12( //inject NONSTANDARD NAMING
address owner,
address spender,
uint256 amount
) internal {
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 APPROVAL56(owner, spender, amount);
}
}
contract erc20detailed25 is ierc2068 { //inject NONSTANDARD NAMING
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(
string memory name,
string memory symbol,
uint8 decimals
) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function NAME49() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL36() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS29() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
library safemath98 { //inject NONSTANDARD NAMING
function ADD95(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB0(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB0(a, b, "SafeMath: subtraction overflow");
}
function SUB0( //inject NONSTANDARD NAMING
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL35(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV21(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV21(a, b, "SafeMath: division by zero");
}
function DIV21( //inject NONSTANDARD NAMING
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
}
library address60 { //inject NONSTANDARD NAMING
function ISCONTRACT31(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 codehash;
bytes32 accountHash
= 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != 0x0 && codehash != accountHash);
}
}
library safeerc2024 { //inject NONSTANDARD NAMING
using safemath98 for uint256;
using address60 for address;
function SAFETRANSFER69( //inject NONSTANDARD NAMING
ierc2068 token,
address to,
uint256 value
) internal {
CALLOPTIONALRETURN38(
token,
abi.encodeWithSelector(token.TRANSFER74.selector, to, value)
);
}
function SAFETRANSFERFROM69( //inject NONSTANDARD NAMING
ierc2068 token,
address from,
address to,
uint256 value
) internal {
CALLOPTIONALRETURN38(
token,
abi.encodeWithSelector(token.TRANSFERFROM66.selector, from, to, value)
);
}
function SAFEAPPROVE52( //inject NONSTANDARD NAMING
ierc2068 token,
address spender,
uint256 value
) internal {
require(
(value == 0) || (token.ALLOWANCE0(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN38(
token,
abi.encodeWithSelector(token.APPROVE81.selector, spender, value)
);
}
function CALLOPTIONALRETURN38(ierc2068 token, bytes memory data) private { //inject NONSTANDARD NAMING
require(address(token).ISCONTRACT31(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "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"
);
}
}
}
contract gnb86 is erc205, erc20detailed25 { //inject NONSTANDARD NAMING
using safeerc2024 for ierc2068;
using address60 for address;
using safemath98 for uint256;
constructor(address _winner) public erc20detailed25("Global Newmedia Bank", "GNB", 18) {
_MINT16(_winner, 100000000000 * 1e18);
}
} | inject NONSTANDARD NAMING | function BALANCEOF80(address account) public view returns (uint256) { | 12,763,989 |
./full_match/1/0xCc09F34Accdb36ee3ED98358A3B8a6AE5C29Ea07/sources/contracts/AnonWeb3Token.sol | Transfers tokens from one address to another with the sender's approval | function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")
);
return true;
}
| 8,346,011 |
./full_match/5/0xbc5E27602fB899964743b09381E3410cbb83E018/sources/contracts/Punkillaz.sol | Returns the unpacked `TokenOwnership` struct from `packed`./ | function _unpackedOwnership(uint256 packed)
private
pure
returns (TokenOwnership memory ownership)
{
ownership.addr = address(uint160(packed));
ownership.startTimestamp = uint64(packed >> BITPOS_START_TIMESTAMP);
ownership.burned = packed & BITMASK_BURNED != 0;
}
| 1,922,125 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
// Part: IBasicRewards
interface IBasicRewards {
function stakeFor(address, uint256) external returns (bool);
function balanceOf(address) external view returns (uint256);
function withdrawAll(bool) external;
function getReward() external returns (bool);
}
// Part: ICurveFactoryPool
interface ICurveFactoryPool {
function get_dy(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256);
function get_balances() external view returns (uint256[2] memory);
function add_liquidity(
uint256[2] memory _amounts,
uint256 _min_mint_amount,
address _receiver
) external returns (uint256);
function exchange(
int128 i,
int128 j,
uint256 _dx,
uint256 _min_dy,
address _receiver
) external returns (uint256);
}
// Part: ICurveV2Pool
interface ICurveV2Pool {
function get_dy(
uint256 i,
uint256 j,
uint256 dx
) external view returns (uint256);
function exchange_underlying(
uint256 i,
uint256 j,
uint256 dx,
uint256 min_dy
) external payable returns (uint256);
}
// Part: OpenZeppelin/[email protected]/Address
/**
* @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 on 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");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
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);
}
}
}
}
// Part: OpenZeppelin/[email protected]/IERC20
/**
* @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);
}
// Part: OpenZeppelin/[email protected]/MerkleProof
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// Part: OpenZeppelin/[email protected]/ReentrancyGuard
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// Part: OpenZeppelin/[email protected]/SafeERC20
/**
* @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 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) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_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");
}
}
}
// Part: UnionBase
// Common variables and functions
contract UnionBase {
address public constant CVXCRV_STAKING_CONTRACT =
0x3Fe65692bfCD0e6CF84cB1E7d24108E434A7587e;
address public constant CURVE_CRV_ETH_POOL =
0x8301AE4fc9c624d1D396cbDAa1ed877821D7C511;
address public constant CURVE_CVX_ETH_POOL =
0xB576491F1E6e5E62f1d8F26062Ee822B40B0E0d4;
address public constant CURVE_CVXCRV_CRV_POOL =
0x9D0464996170c6B9e75eED71c68B99dDEDf279e8;
address public constant CRV_TOKEN =
0xD533a949740bb3306d119CC777fa900bA034cd52;
address public constant CVXCRV_TOKEN =
0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7;
address public constant CVX_TOKEN =
0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B;
uint256 public constant CRVETH_ETH_INDEX = 0;
uint256 public constant CRVETH_CRV_INDEX = 1;
int128 public constant CVXCRV_CRV_INDEX = 0;
int128 public constant CVXCRV_CVXCRV_INDEX = 1;
uint256 public constant CVXETH_ETH_INDEX = 0;
uint256 public constant CVXETH_CVX_INDEX = 1;
IBasicRewards cvxCrvStaking = IBasicRewards(CVXCRV_STAKING_CONTRACT);
ICurveV2Pool cvxEthSwap = ICurveV2Pool(CURVE_CVX_ETH_POOL);
ICurveV2Pool crvEthSwap = ICurveV2Pool(CURVE_CRV_ETH_POOL);
ICurveFactoryPool crvCvxCrvSwap = ICurveFactoryPool(CURVE_CVXCRV_CRV_POOL);
/// @notice Swap CRV for cvxCRV on Curve
/// @param amount - amount to swap
/// @param recipient - where swapped tokens will be sent to
/// @return amount of CRV obtained after the swap
function _swapCrvToCvxCrv(uint256 amount, address recipient)
internal
returns (uint256)
{
return
crvCvxCrvSwap.exchange(
CVXCRV_CRV_INDEX,
CVXCRV_CVXCRV_INDEX,
amount,
0,
recipient
);
}
/// @notice Swap CRV for cvxCRV on Curve
/// @param amount - amount to swap
/// @param recipient - where swapped tokens will be sent to
/// @return amount of CRV obtained after the swap
function _swapCvxCrvToCrv(uint256 amount, address recipient)
internal
returns (uint256)
{
return
crvCvxCrvSwap.exchange(
CVXCRV_CVXCRV_INDEX,
CVXCRV_CRV_INDEX,
amount,
0,
recipient
);
}
/// @notice Swap CRV for native ETH on Curve
/// @param amount - amount to swap
/// @return amount of ETH obtained after the swap
function _swapCrvToEth(uint256 amount) internal returns (uint256) {
return
crvEthSwap.exchange_underlying{value: 0}(
CRVETH_CRV_INDEX,
CRVETH_ETH_INDEX,
amount,
0
);
}
/// @notice Swap native ETH for CRV on Curve
/// @param amount - amount to swap
/// @return amount of CRV obtained after the swap
function _swapEthToCrv(uint256 amount) internal returns (uint256) {
return
crvEthSwap.exchange_underlying{value: amount}(
CRVETH_ETH_INDEX,
CRVETH_CRV_INDEX,
amount,
0
);
}
/// @notice Swap native ETH for CVX on Curve
/// @param amount - amount to swap
/// @return amount of CRV obtained after the swap
function _swapEthToCvx(uint256 amount) internal returns (uint256) {
return
cvxEthSwap.exchange_underlying{value: amount}(
CVXETH_ETH_INDEX,
CVXETH_CVX_INDEX,
amount,
0
);
}
}
// File: MerkleDistributor.sol
// Allows anyone to claim a token if they exist in a merkle root.
contract MerkleDistributor is ReentrancyGuard, UnionBase {
using SafeERC20 for IERC20;
// Possible options when claiming
enum Option {
Claim,
ClaimAsETH,
ClaimAsCRV,
ClaimAsCVX,
ClaimAndStake
}
address public immutable token;
bytes32 public merkleRoot;
uint32 public week;
bool public frozen;
address public admin;
address public depositor;
// This is a packed array of booleans.
mapping(uint256 => mapping(uint256 => uint256)) private claimedBitMap;
// This event is triggered whenever a call to #claim succeeds.
event Claimed(
uint256 index,
uint256 indexed amount,
address indexed account,
uint256 week,
Option indexed option
);
// This event is triggered whenever the merkle root gets updated.
event MerkleRootUpdated(bytes32 indexed merkleRoot, uint32 indexed week);
// This event is triggered whenever the admin is updated.
event AdminUpdated(address indexed oldAdmin, address indexed newAdmin);
constructor(
address token_,
address depositor_,
bytes32 merkleRoot_
) {
token = token_;
admin = msg.sender;
depositor = depositor_;
merkleRoot = merkleRoot_;
week = 0;
frozen = true;
}
/// @notice Check if the index has been marked as claimed.
/// @param index - the index to check
/// @return true if index has been marked as claimed.
function isClaimed(uint256 index) public view returns (bool) {
uint256 claimedWordIndex = index / 256;
uint256 claimedBitIndex = index % 256;
uint256 claimedWord = claimedBitMap[week][claimedWordIndex];
uint256 mask = (1 << claimedBitIndex);
return claimedWord & mask == mask;
}
function _setClaimed(uint256 index) private {
uint256 claimedWordIndex = index / 256;
uint256 claimedBitIndex = index % 256;
claimedBitMap[week][claimedWordIndex] =
claimedBitMap[week][claimedWordIndex] |
(1 << claimedBitIndex);
}
/// @notice Set approvals for the tokens used when swapping
function setApprovals() external onlyAdmin {
IERC20(CRV_TOKEN).safeApprove(CURVE_CRV_ETH_POOL, 0);
IERC20(CRV_TOKEN).safeApprove(CURVE_CRV_ETH_POOL, 2**256 - 1);
IERC20(CVXCRV_TOKEN).safeApprove(CVXCRV_STAKING_CONTRACT, 0);
IERC20(CVXCRV_TOKEN).safeApprove(CVXCRV_STAKING_CONTRACT, 2**256 - 1);
IERC20(CVXCRV_TOKEN).safeApprove(CURVE_CVXCRV_CRV_POOL, 0);
IERC20(CVXCRV_TOKEN).safeApprove(CURVE_CVXCRV_CRV_POOL, 2**256 - 1);
}
/// @notice Transfers ownership of the contract
/// @param newAdmin - address of the new admin of the contract
function updateAdmin(address newAdmin) external onlyAdmin {
require(newAdmin != address(0));
address oldAdmin = admin;
admin = newAdmin;
emit AdminUpdated(oldAdmin, newAdmin);
}
/// @notice Claim the given amount of the token to the given address.
/// Reverts if the inputs are invalid.
/// @param index - claimer index
/// @param account - claimer account
/// @param amount - claim amount
/// @param merkleProof - merkle proof for the claim
/// @param option - claiming option
function claim(
uint256 index,
address account,
uint256 amount,
bytes32[] calldata merkleProof,
Option option
) external nonReentrant {
require(!frozen, "Claiming is frozen.");
require(!isClaimed(index), "Drop already claimed.");
// Verify the merkle proof.
bytes32 node = keccak256(abi.encodePacked(index, account, amount));
require(
MerkleProof.verify(merkleProof, merkleRoot, node),
"Invalid proof."
);
// Mark it claimed and send the token.
_setClaimed(index);
if (option == Option.ClaimAsCRV) {
_swapCvxCrvToCrv(amount, account);
} else if (option == Option.ClaimAsETH) {
uint256 _crvBalance = _swapCvxCrvToCrv(amount, address(this));
uint256 _ethAmount = _swapCrvToEth(_crvBalance);
(bool success, ) = account.call{value: _ethAmount}("");
require(success, "ETH transfer failed");
} else if (option == Option.ClaimAsCVX) {
uint256 _crvBalance = _swapCvxCrvToCrv(amount, address(this));
uint256 _ethAmount = _swapCrvToEth(_crvBalance);
uint256 _cvxAmount = _swapEthToCvx(_ethAmount);
IERC20(CVX_TOKEN).safeTransfer(account, _cvxAmount);
} else if (option == Option.ClaimAndStake) {
require(cvxCrvStaking.stakeFor(account, amount), "Staking failed");
} else {
IERC20(token).safeTransfer(account, amount);
}
emit Claimed(index, amount, account, week, option);
}
/// @notice Freezes the claim function to allow the merkleRoot to be changed
/// @dev Can be called by the owner or the depositor zap contract
function freeze() public {
require(
(msg.sender == admin) || (msg.sender == depositor),
"Admin or depositor only"
);
frozen = true;
}
/// @notice Unfreezes the claim function.
function unfreeze() public onlyAdmin {
frozen = false;
}
/// @notice Update the merkle root and increment the week.
/// @param _merkleRoot - the new root to push
function updateMerkleRoot(bytes32 _merkleRoot) public onlyAdmin {
require(frozen, "Contract not frozen.");
// Increment the week (simulates the clearing of the claimedBitMap)
week = week + 1;
// Set the new merkle root
merkleRoot = _merkleRoot;
emit MerkleRootUpdated(merkleRoot, week);
}
receive() external payable {}
modifier onlyAdmin() {
require(msg.sender == admin, "Admin only");
_;
}
}
| Check if the index has been marked as claimed. index - the index to check return true if index has been marked as claimed. | function isClaimed(uint256 index) public view returns (bool) {
uint256 claimedWordIndex = index / 256;
uint256 claimedBitIndex = index % 256;
uint256 claimedWord = claimedBitMap[week][claimedWordIndex];
uint256 mask = (1 << claimedBitIndex);
return claimedWord & mask == mask;
}
| 5,713,448 |
./full_match/80001/0xE369423ea9f02B201f179E64e2298B4E2F6937f0/sources/contracts/TicketManagement.sol | Adding the Tickets' Owner Details. Store the addEmployee transaction into the logs | function addTicketOwner(
address _owner,
uint256 _amount,
string memory _typeOfTicket,
string memory _imgUrl
) public payable returns (uint256) {
address newOwner = msg.sender;
bool success;
require(success, "Transfer failed.");
Transaction storage newTransaction = transactions[numberOfTickets];
newTransaction.to = concertManager;
newTransaction.from = newOwner;
newTransaction.amount = _amount;
newTransaction.timestamp = block.timestamp;
newTransaction.ticketType = _typeOfTicket;
numberOfTransactions++;
emit Payment(_owner, _amount);
Tickets storage newTicket = tickets[numberOfTickets];
newTicket.owner = _owner;
newTicket.amount = _amount;
newTicket.typeOfTicket = _typeOfTicket;
newTicket.time = block.timestamp;
newTicket.imgUrl = _imgUrl;
numberOfTickets++;
emit addTicket(_owner, _amount, _typeOfTicket);
return numberOfTickets - 1;
}
| 5,609,228 |
./full_match/42/0x492f2B3372425C7De48ac40B3B8B8B2fE66EFEDD/sources/browser/LeadToken.sol | Get current day from launch | function currentDay() external view returns (uint256){ return _currentDay();}
| 16,240,830 |
// SPDX-License-Identifier: MIT
// Soldity version 0.8.X
pragma solidity ^0.8.0;
// (๐ See brownie-config.yaml for dependencies)
// For Chainlink price feeds
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
// For contract ownership management
import "@openzeppelin/contracts/access/Ownable.sol";
// For verifiable random number generation
import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
// Inherit the functionailty
contract Lottery is VRFConsumerBase, Ownable {
// Define possible lottery states (values: 0, 1, 2)
enum LOTTERY_STATE {
OPEN,
CLOSED,
CALCULATING_WINNER
}
// Current lottery state
LOTTERY_STATE public lottery_state;
// Minimum entry fee, in USD
uint256 public usdEntryFee;
// Chainlink price feed interface (internal - not accessible from the outside)
AggregatorV3Interface internal ethUsdPriceFeed;
// Lottery entries (payable - can receive funds from this contract)
address payable[] public players;
// (Working with VRFConsumerBase)
// Public key against which randomness is generated
bytes32 public keyHash;
// VRF service fee, in LINK
uint256 public fee;
// The winner of last lottery
address payable public recentWinner;
// The randomness used in last lottery
uint256 public randomness;
// Define events
// (Similar to printing out to the console in the traditional programming
// Stored in log entries on the blockchain, not accessible by smart contracts)
// VRF service request ID
event RequestedRandomness(bytes32 requestId);
// Random number
event RandomnessReceived(uint256 _randomness);
// โน๏ธ Working with 18 decimals
// Add any inherited constructors before the body
constructor(
address _priceFeedAddress,
uint256 _fee,
bytes32 _keyHash,
// VRFCoordinator contract address
address _vrfCoordinator,
// LINK contract address
address _link
) VRFConsumerBase(_vrfCoordinator, _link) {
// 50 USD entry fee
usdEntryFee = 50e18;
// ETH/USD price feed contract
ethUsdPriceFeed = AggregatorV3Interface(_priceFeedAddress);
// Lottery state closed
lottery_state = LOTTERY_STATE.CLOSED;
fee = _fee;
keyHash = _keyHash;
}
// Starts the lottery (onlyOwner - proceeds only if called by the owner)
function startLottery() public onlyOwner {
// Can't start a new lottery if the current one has not ended
require(
lottery_state == LOTTERY_STATE.CLOSED,
"Can't start a new lottery yet!"
);
lottery_state = LOTTERY_STATE.OPEN;
}
// Returns the minimum entrance fee in wei (view - cannot change the state)
function getEntranceFee() public view returns (uint256) {
// Get the latest ETH/USD exchange rate
// (Returns a tuple; skip other values)
(, int256 answer, , , ) = ethUsdPriceFeed.latestRoundData();
// The answer has 8 decimals, add 10 more
uint256 adjustedPrice = uint256(answer) * 1e10;
// Calculate the fee (multiply before dividing!)
uint256 costToEnter = (usdEntryFee * 1e18) / adjustedPrice;
return costToEnter;
}
// Allows anyone to enter the lottery (payable - accepts ETH)
function enter() public payable {
// if it's open
require(lottery_state == LOTTERY_STATE.OPEN);
// and they pay the entry fee
require(msg.value >= getEntranceFee(), "Not enough ETH!");
// Store the entry
players.push(payable(msg.sender));
}
// Ends the lottery and requests randomness
function endLottery() public onlyOwner {
// Lock other functionality
lottery_state = LOTTERY_STATE.CALCULATING_WINNER;
// (Request and receive data cycle)
// Requesting data from VRFCoordinator
bytes32 requestId = requestRandomness(keyHash, fee);
// Emit an event for testing purposes
emit RequestedRandomness(requestId);
}
// Picks a winner
// (Request and receive data cycle)
// Receiving data from VRFCoordinator
function fulfillRandomness(bytes32 _requestId, uint256 _randomness)
internal
override
{
// Proceed if waiting for response
require(
lottery_state == LOTTERY_STATE.CALCULATING_WINNER,
"You aren't there yet"
);
// The random number shouldn't be 0
require(_randomness > 0, "random-not-found");
// Pick a winner
// (Let's say randomness is 11 and there are 4 entries
// 11 % 4 The reminder can't be >= 4)
uint256 indexOfWinner = _randomness % players.length;
// Store their address
recentWinner = players[indexOfWinner];
// Transfer the funds
recentWinner.transfer(address(this).balance);
// Store the randomeness
randomness = _randomness;
// Clear entries
players = new address payable[](0);
// Close the lottery
lottery_state = LOTTERY_STATE.CLOSED;
// Emit an event for testing purposes
emit RandomnessReceived(_randomness);
}
}
| Ends the lottery and requests randomness Lock other functionality (Request and receive data cycle) Requesting data from VRFCoordinator Emit an event for testing purposes | function endLottery() public onlyOwner {
lottery_state = LOTTERY_STATE.CALCULATING_WINNER;
bytes32 requestId = requestRandomness(keyHash, fee);
emit RequestedRandomness(requestId);
}
| 12,920,814 |
// SPDX-License-Identifier: BlueOak-1.0.0
pragma solidity 0.8.9;
import "contracts/libraries/Fixed.sol";
import "contracts/p0/RToken.sol";
import "contracts/p0/mixins/Component.sol";
import "contracts/p1/RToken.sol";
import "contracts/interfaces/IBackingManager.sol";
import "contracts/interfaces/IBasketHandler.sol";
import "contracts/plugins/mocks/ERC20Mock.sol";
import "contracts/fuzz/Mocks.sol";
import "contracts/fuzz/Utils.sol";
/* TODO: Here's a few of the many ways that this test could be improved:
- Decorate basically everything with events for clues about test failures
- Have the MockBasketHandler and MockBackingManager save an "event" log, representing the
state-change events that they've been issued, so that we can ensure the equivalence of the
function call sequence that each RToken emits
- Get these mocks to be more active, so they exercise more of the RToken space.
- In particular, make the referesher functions do more of what they're intended to do
- Have the mock contracts act wildly, possibly represented by more actions from the
RTokenDiffTest contract, to mock out changes that might effect the RToken (but that the
RToken probably doesn't model directly)
- Change the mock basket model from "token A" to "switches between token A and token B" or use
- Or something yet more ambitious? This could be practically anything we can drive from
random actions.
- It *might* be that these mocked-out component models are really useful for other fuzz tests too
*/
contract MockBackingManager is IBackingManager, ComponentMock {
function init(
IMain,
uint32,
uint192,
uint192,
uint192
) external {}
function grantRTokenAllowance(IERC20) external {}
function manageTokens(IERC20[] memory) external {}
/// Settle any auctions that can be settled
function settleTrade(IERC20) external virtual override {}
function claimAndSweepRewards() external virtual override {}
function trades(IERC20) external view virtual override returns (ITrade) {
return ITrade(address(0));
}
/// @return {%} The maximum trade slippage acceptable
function maxTradeSlippage() external view virtual override returns (uint192) {
return 1e16;
}
/// @return {UoA} The smallest amount of value worth trading
function dustAmount() external view virtual override returns (uint192) {
return 2e20;
}
}
contract MockBasketHandler is IBasketHandler, ComponentMock {
using FixLib for uint192;
/* The mock basket we're running with, here, is always either 100% A or 100% B.
* Each is always assumed to have a price of 1 UoA.
* We can (and maybe should) build something with wider behavior
*/
// Is the basket 100% A (instead of 100% B?)
bool public modeA = true;
IERC20 public tokenA;
IERC20 public tokenB;
uint256 public nonce = 0;
uint256 public timestamp;
constructor(IERC20 tokenA_, IERC20 tokenB_) {
tokenA = tokenA_;
tokenB = tokenB_;
timestamp = block.timestamp;
}
function init(IMain) external {}
function token() private view returns (IERC20) {
return modeA ? tokenA : tokenB;
}
/// Set the prime basket
function setPrimeBasket(IERC20[] memory, uint192[] memory) external {}
/// Set the backup configuration for a given target
function setBackupConfig(
bytes32,
uint256,
IERC20[] calldata
) external {}
/// Default the basket in order to schedule a basket refresh
function disableBasket() external {}
/// Governance-controlled setter to cause a basket switch explicitly
function refreshBasket() external {
// TODO: modeA = !modeA, and we do all the needed trades and handle capitalization
++nonce;
timestamp = block.timestamp;
}
/// @return If the BackingManager has sufficient collateral to redeem the entire RToken supply
function fullyCapitalized() external pure returns (bool) {
return true;
}
/// @return status The worst CollateralStatus of all collateral in the basket
function status() external pure returns (CollateralStatus) {
return CollateralStatus.SOUND;
}
/// @return {tok/BU} The whole token quantity of token in the reference basket
function quantity(IERC20 erc20) external view returns (uint192) {
return token() == erc20 ? FIX_ONE : FIX_ZERO;
}
/// @param amount {BU}
/// @return erc20s The addresses of the ERC20 tokens in the reference basket
/// @return quantities {qTok} The quantity of each ERC20 token to issue `amount` baskets
function quote(uint192 amount, RoundingMode rounding)
external
view
returns (address[] memory erc20s, uint256[] memory quantities)
{
erc20s = new address[](1);
erc20s[0] = modeA ? address(tokenA) : address(tokenB);
quantities = new uint256[](1);
quantities[0] = amount.shiftl(18).toUint(rounding);
}
/// @return baskets {BU} The quantity of complete baskets at an address. A balance for BUs
function basketsHeldBy(address acct) external view returns (uint192 baskets) {
int8 decimals = int8(IERC20Metadata(address(token())).decimals());
baskets = shiftl_toFix(token().balanceOf(acct), -decimals);
}
/// @return p {UoA/BU} The protocol's best guess at what a BU would be priced at in UoA
function price() external pure returns (uint192 p) {
return FIX_ONE;
}
/// @return nonce_ The basket nonce, a monotonically increasing unique identifier
/// @return timestamp_ The timestamp at which the basket was last set
function lastSet() external view returns (uint256 nonce_, uint256 timestamp_) {
nonce_ = nonce;
timestamp_ = timestamp;
}
}
contract RTokenTestSystem is MainMock {
using FixLib for uint192;
ERC20Mock public baseA;
ERC20Mock public baseB;
constructor(IRToken rToken_) {
DeploymentParams memory params = defaultParams();
Components memory components;
baseA = new ERC20Mock("Base Token A", "A$");
baseB = new ERC20Mock("Base Token B", "B$");
for (uint256 i = 0; i < USERS.length; i++) {
baseA.mint(USERS[i], 1e24);
baseB.mint(USERS[i], 1e24);
}
init(components, IERC20(address(0)), 0);
basketHandler = new MockBasketHandler(baseA, baseB);
basketHandler.init(this);
backingManager = new MockBackingManager();
backingManager.init(
this,
params.tradingDelay,
params.backingBuffer,
params.maxTradeSlippage,
params.dustAmount
);
rToken = rToken_;
rToken.init(this, "RToken", "RTK", "rtoken://1", params.issuanceRate);
}
}
contract RTokenP0Test is RTokenP0 {
function _msgSender() internal view virtual override returns (address) {
return MainMock(address(main)).sender();
}
}
contract RTokenP1Test is RTokenP1 {
function _msgSender() internal view virtual override returns (address) {
return MainMock(address(main)).sender();
}
}
contract RTokenDiffTest {
using FixLib for uint192;
address[] public USERS = [address(0x10000), address(0x20000), address(0x30000)];
RTokenTestSystem public p0;
RTokenTestSystem public p1;
modifier fromSender() {
p0.setSender(msg.sender);
p1.setSender(msg.sender);
_;
p0.setSender(address(0));
p1.setSender(address(0));
}
modifier fromBackingMgr() {
p0.setSender(address(p0.backingManager()));
p1.setSender(address(p1.backingManager()));
_;
p0.setSender(address(0));
p1.setSender(address(0));
}
constructor() {
p0 = new RTokenTestSystem(new RTokenP0Test());
p1 = new RTokenTestSystem(new RTokenP1Test());
}
// Actions and state modifiers
// ==== user actions, performed by 0x[123]0000. Melt
function issue(uint256 amount) external fromSender {
amount %= 1e36;
p0.rToken().issue(amount);
p1.rToken().issue(amount);
}
function cancel(uint256 endId, bool e) external fromSender {
p0.rToken().cancel(endId, e);
p1.rToken().cancel(endId, e);
}
function vest(address acct, uint256 endId) external fromSender {
p0.rToken().vest(acct, endId);
p1.rToken().vest(acct, endId);
}
// TODO: Add "cancel" and "vest" variations that are likely to succeed too
// i.e, ones that have valid endIDs
function redeem(uint256 amount) external fromSender {
amount %= 1e36;
p0.rToken().redeem(amount);
p1.rToken().redeem(amount);
}
function melt(uint256 amount) external fromSender {
amount %= 1e36;
p0.rToken().melt(amount);
p1.rToken().melt(amount);
}
function mint(address recipient, uint256 amount) external fromBackingMgr {
amount %= 1e36;
recipient = address((uint160(recipient) % 3) * 0x10000); // mint only to USERS
p0.rToken().mint(recipient, amount);
p1.rToken().mint(recipient, amount);
}
function setBasketsNeeded(uint192 basketsNeeded) external fromBackingMgr {
basketsNeeded %= 1e36;
p0.rToken().setBasketsNeeded(basketsNeeded);
p1.rToken().setBasketsNeeded(basketsNeeded);
}
// Auth on these is that the caller needs to be main.owner. That... should be this contract?
function setIssuanceRate(uint192 val) external {
val %= 1e24;
assert(p0.owner() == address(this)); // hope but verify
assert(p1.owner() == address(this));
RTokenP0(address(p0.rToken())).setIssuanceRate(val);
RTokenP1(address(p1.rToken())).setIssuanceRate(val);
}
// TODO: changes to MockERC20 balances
// Invariant: the observable rtoken prices are equal
function echidna_prices_equal() external view returns (bool) {
return p0.rToken().price() == p1.rToken().price();
}
function echidna_vesting_ids_equal() external view returns (bool) {
return
p0.rToken().endIdForVest(USERS[0]) == p1.rToken().endIdForVest(USERS[0]) &&
p0.rToken().endIdForVest(USERS[1]) == p1.rToken().endIdForVest(USERS[1]) &&
p0.rToken().endIdForVest(USERS[2]) == p1.rToken().endIdForVest(USERS[2]);
}
function echidna_baskets_needed_equal() external view returns (bool) {
return p0.rToken().basketsNeeded() == p1.rToken().basketsNeeded();
}
function all_balances_equal(address acct0, address acct1) internal view returns (bool) {
return
p0.baseA().balanceOf(acct0) == p1.baseA().balanceOf(acct1) &&
p0.baseB().balanceOf(acct0) == p1.baseB().balanceOf(acct1) &&
p0.rToken().balanceOf(acct0) == p1.rToken().balanceOf(acct1);
}
function echidna_user_balances_equal() external view returns (bool equal) {
equal =
all_balances_equal(address(p0.backingManager()), address(p1.backingManager())) &&
all_balances_equal(address(p0.basketHandler()), address(p1.basketHandler())) &&
all_balances_equal(address(p0), address(p1));
for (uint256 i = 0; i < USERS.length; i++) {
equal = equal && all_balances_equal(USERS[i], USERS[i]);
}
}
}
| amount {BU} return erc20s The addresses of the ERC20 tokens in the reference basket return quantities {qTok} The quantity of each ERC20 token to issue `amount` baskets | function quote(uint192 amount, RoundingMode rounding)
external
view
returns (address[] memory erc20s, uint256[] memory quantities)
{
erc20s = new address[](1);
erc20s[0] = modeA ? address(tokenA) : address(tokenB);
quantities = new uint256[](1);
quantities[0] = amount.shiftl(18).toUint(rounding);
}
| 1,833,298 |
pragma solidity ^0.7.5;
// ----------------------------------------------------------------------------
// BokkyPooBah's DateTime Library v1.01
//
// A gas-efficient Solidity date and time library
//
// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary
//
// Tested date range 1970/01/01 to 2345/12/31
//
// Conventions:
// Unit | Range | Notes
// :-------- |:-------------:|:-----
// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC
// year | 1970 ... 2345 |
// month | 1 ... 12 |
// day | 1 ... 31 |
// hour | 0 ... 23 |
// minute | 0 ... 59 |
// second | 0 ... 59 |
// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday
//
//
// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.
// ----------------------------------------------------------------------------
library BokkyPooBahsDateTimeLibrary {
uint constant SECONDS_PER_DAY = 24 * 60 * 60;
uint constant SECONDS_PER_HOUR = 60 * 60;
uint constant SECONDS_PER_MINUTE = 60;
int constant OFFSET19700101 = 2440588;
uint constant DOW_MON = 1;
uint constant DOW_TUE = 2;
uint constant DOW_WED = 3;
uint constant DOW_THU = 4;
uint constant DOW_FRI = 5;
uint constant DOW_SAT = 6;
uint constant DOW_SUN = 7;
// ------------------------------------------------------------------------
// Calculate the number of days from 1970/01/01 to year/month/day using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and subtracting the offset 2440588 so that 1970/01/01 is day 0
//
// days = day
// - 32075
// + 1461 * (year + 4800 + (month - 14) / 12) / 4
// + 367 * (month - 2 - (month - 14) / 12 * 12) / 12
// - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4
// - offset
// ------------------------------------------------------------------------
function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) {
require(year >= 1970);
int _year = int(year);
int _month = int(month);
int _day = int(day);
int __days = _day
- 32075
+ 1461 * (_year + 4800 + (_month - 14) / 12) / 4
+ 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12
- 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4
- OFFSET19700101;
_days = uint(__days);
}
// ------------------------------------------------------------------------
// Calculate year/month/day from the number of days since 1970/01/01 using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and adding the offset 2440588 so that 1970/01/01 is day 0
//
// int L = days + 68569 + offset
// int N = 4 * L / 146097
// L = L - (146097 * N + 3) / 4
// year = 4000 * (L + 1) / 1461001
// L = L - 1461 * year / 4 + 31
// month = 80 * L / 2447
// dd = L - 2447 * month / 80
// L = month / 11
// month = month + 2 - 12 * L
// year = 100 * (N - 49) + year + L
// ------------------------------------------------------------------------
function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) {
int __days = int(_days);
int L = __days + 68569 + OFFSET19700101;
int N = 4 * L / 146097;
L = L - (146097 * N + 3) / 4;
int _year = 4000 * (L + 1) / 1461001;
L = L - 1461 * _year / 4 + 31;
int _month = 80 * L / 2447;
int _day = L - 2447 * _month / 80;
L = _month / 11;
_month = _month + 2 - 12 * L;
_year = 100 * (N - 49) + _year + L;
year = uint(_year);
month = uint(_month);
day = uint(_day);
}
function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY;
}
function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second;
}
function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
secs = secs % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
second = secs % SECONDS_PER_MINUTE;
}
function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) {
if (year >= 1970 && month > 0 && month <= 12) {
uint daysInMonth = _getDaysInMonth(year, month);
if (day > 0 && day <= daysInMonth) {
valid = true;
}
}
}
function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) {
if (isValidDate(year, month, day)) {
if (hour < 24 && minute < 60 && second < 60) {
valid = true;
}
}
}
function isLeapYear(uint timestamp) internal pure returns (bool leapYear) {
(uint year,,) = _daysToDate(timestamp / SECONDS_PER_DAY);
leapYear = _isLeapYear(year);
}
function _isLeapYear(uint year) internal pure returns (bool leapYear) {
leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
function isWeekDay(uint timestamp) internal pure returns (bool weekDay) {
weekDay = getDayOfWeek(timestamp) <= DOW_FRI;
}
function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) {
weekEnd = getDayOfWeek(timestamp) >= DOW_SAT;
}
function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) {
(uint year, uint month,) = _daysToDate(timestamp / SECONDS_PER_DAY);
daysInMonth = _getDaysInMonth(year, month);
}
function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
daysInMonth = 31;
} else if (month != 2) {
daysInMonth = 30;
} else {
daysInMonth = _isLeapYear(year) ? 29 : 28;
}
}
// 1 = Monday, 7 = Sunday
function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) {
uint _days = timestamp / SECONDS_PER_DAY;
dayOfWeek = (_days + 3) % 7 + 1;
}
function getYear(uint timestamp) internal pure returns (uint year) {
(year,,) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getMonth(uint timestamp) internal pure returns (uint month) {
(,month,) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getDay(uint timestamp) internal pure returns (uint day) {
(,,day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getHour(uint timestamp) internal pure returns (uint hour) {
uint secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
}
function getMinute(uint timestamp) internal pure returns (uint minute) {
uint secs = timestamp % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
}
function getSecond(uint timestamp) internal pure returns (uint second) {
second = timestamp % SECONDS_PER_MINUTE;
}
function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) {
(uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year += _years;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) {
(uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY);
month += _months;
year += (month - 1) / 12;
month = (month - 1) % 12 + 1;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _days * SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _hours * SECONDS_PER_HOUR;
require(newTimestamp >= timestamp);
}
function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE;
require(newTimestamp >= timestamp);
}
function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _seconds;
require(newTimestamp >= timestamp);
}
function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) {
(uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year -= _years;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) {
(uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint yearMonth = year * 12 + (month - 1) - _months;
year = yearMonth / 12;
month = yearMonth % 12 + 1;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _days * SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _hours * SECONDS_PER_HOUR;
require(newTimestamp <= timestamp);
}
function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE;
require(newTimestamp <= timestamp);
}
function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _seconds;
require(newTimestamp <= timestamp);
}
function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) {
require(fromTimestamp <= toTimestamp);
(uint fromYear,,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(uint toYear,,) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_years = toYear - fromYear;
}
function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) {
require(fromTimestamp <= toTimestamp);
(uint fromYear, uint fromMonth,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(uint toYear, uint toMonth,) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;
}
function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) {
require(fromTimestamp <= toTimestamp);
_days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY;
}
function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) {
require(fromTimestamp <= toTimestamp);
_hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR;
}
function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) {
require(fromTimestamp <= toTimestamp);
_minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE;
}
function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) {
require(fromTimestamp <= toTimestamp);
_seconds = toTimestamp - fromTimestamp;
}
}
pragma solidity 0.7.6;
import "@openzeppelin/contracts/proxy/TransparentUpgradeableProxy.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "./vaults/StakingData.sol";
contract ITrustVaultFactory is Initializable {
address[] internal _VaultProxies;
mapping (address => bool) internal _AdminList;
mapping (address => bool) internal _TrustedSigners;
mapping(address => bool) internal _VaultStatus;
address internal _roundDataImplementationAddress;
address internal _stakeDataImplementationAddress;
address internal _stakingDataAddress;
address internal _burnAddress;
address internal _governanceDistributionAddress;
address internal _governanceTokenAddress;
address internal _stakingCalculationAddress;
function initialize(
address admin,
address trustedSigner,
address roundDataImplementationAddress,
address stakeDataImplementationAddress,
address governanceTokenAddress,
address stakingCalculationAddress
) initializer external {
require(admin != address(0));
_AdminList[admin] = true;
_AdminList[msg.sender] = true;
_TrustedSigners[trustedSigner] = true;
_roundDataImplementationAddress = roundDataImplementationAddress;
_stakeDataImplementationAddress = stakeDataImplementationAddress;
_governanceTokenAddress = governanceTokenAddress;
_stakingCalculationAddress = stakingCalculationAddress;
}
modifier onlyAdmin() {
require(_AdminList[msg.sender] == true, "Not Factory Admin");
_;
}
function createVault(
address contractAddress,
bytes memory data
) external onlyAdmin {
TransparentUpgradeableProxy proxy = new TransparentUpgradeableProxy(contractAddress, msg.sender, data );
require(address(proxy) != address(0));
_VaultProxies.push(address(proxy));
_VaultStatus[address(proxy)] = true;
StakingData stakingDataContract = StakingData(_stakingDataAddress);
stakingDataContract.addVault(address(proxy));
}
function getVaultaddresses() external view returns (address[] memory vaults, bool[] memory status) {
vaults = _VaultProxies;
status = new bool[](vaults.length);
for(uint i = 0; i < vaults.length; i++){
status[i] = _VaultStatus[vaults[i]];
}
return (vaults, status);
}
function pauseVault(address vaultAddress) external onlyAdmin {
_VaultStatus[vaultAddress] = false;
}
function unPauseVault(address vaultAddress) external onlyAdmin {
_VaultStatus[vaultAddress] = true;
}
function addAdminAddress(address newAddress) external onlyAdmin {
require(_AdminList[newAddress] == false, "Already Admin");
_AdminList[newAddress] = true;
}
/**
* @dev revoke admin
*/
function revokeAdminAddress(address newAddress) external onlyAdmin {
require(msg.sender != newAddress);
_AdminList[newAddress] = false;
}
function addTrustedSigner(address newAddress) external onlyAdmin{
require(_TrustedSigners[newAddress] == false);
_TrustedSigners[newAddress] = true;
}
function isTrustedSignerAddress(address account) external view returns (bool) {
return _TrustedSigners[account] == true;
}
function updateRoundDataImplementationAddress(address newAddress) external onlyAdmin {
_roundDataImplementationAddress = newAddress;
}
function getRoundDataImplementationAddress() external view returns(address){
return _roundDataImplementationAddress;
}
function updateStakeDataImplementationAddress(address newAddress) external onlyAdmin {
_stakeDataImplementationAddress = newAddress;
}
function getStakeDataImplementationAddress() external view returns(address){
return _stakeDataImplementationAddress;
}
function updateStakingDataAddress(address newAddress) external onlyAdmin {
_stakingDataAddress = newAddress;
}
function getStakingDataAddress() external view returns(address){
return _stakingDataAddress;
}
function isStakingDataAddress(address addressToCheck) external view returns (bool) {
return _stakingDataAddress == addressToCheck;
}
function updateBurnAddress(address newAddress) external onlyAdmin {
_burnAddress = newAddress;
}
function getBurnAddress() external view returns(address){
return _burnAddress;
}
function isBurnAddress(address addressToCheck) external view returns (bool) {
return _burnAddress == addressToCheck;
}
function updateGovernanceDistributionAddress(address newAddress) external onlyAdmin {
_governanceDistributionAddress = newAddress;
}
function getGovernanceDistributionAddress() external view returns(address){
return _governanceDistributionAddress;
}
function updateGovernanceTokenAddress(address newAddress) external onlyAdmin {
_governanceTokenAddress = newAddress;
}
function getGovernanceTokenAddress() external view returns(address){
return _governanceTokenAddress;
}
function updateStakingCalculationsAddress(address newAddress) external onlyAdmin {
_stakingCalculationAddress = newAddress;
}
function getStakingCalculationsAddress() external view returns(address){
return _stakingCalculationAddress;
}
/**
* @dev revoke admin
*/
function revokeTrustedSigner(address newAddress) external onlyAdmin {
require(msg.sender != newAddress);
_TrustedSigners[newAddress] = false;
}
function isAdmin() external view returns (bool) {
return isAddressAdmin(msg.sender);
}
function isAddressAdmin(address account) public view returns (bool) {
return _AdminList[account] == true;
}
function isActiveVault(address vaultAddress) external view returns (bool) {
return _VaultStatus[vaultAddress] == true;
}
}
pragma solidity 0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/math/SafeMath.sol";
library ITrustVaultLib {
using SafeMath for uint;
struct RewardTokenRoundData{
address tokenAddress;
uint amount;
uint commissionAmount;
uint tokenPerBlock;
uint totalSupply;
bool ignoreUnstakes;
}
struct RewardTokenRound{
mapping(address => RewardTokenRoundData) roundData;
uint startBlock;
uint endBlock;
}
struct AccountStaking {
uint32 startRound;
uint endDate;
uint total;
Staking[] stakes;
}
struct Staking {
uint startTime;
uint startBlock;
uint amount;
uint total;
}
struct UnStaking {
address account;
uint amount;
uint startDateTime;
uint startBlock;
uint endBlock;
}
struct ClaimedReward {
uint amount;
uint lastClaimedRound;
}
function divider(uint numerator, uint denominator, uint precision) internal pure returns(uint) {
return numerator*(uint(10)**uint(precision))/denominator;
}
function getUnstakingsForBlockRange(
UnStaking[] memory unStakes,
uint startBlock,
uint endBlock) internal pure returns (uint){
// If we have bad data, no supply data or it starts after the block we are looking for then we can return zero
if(endBlock < startBlock
|| unStakes.length == 0
|| unStakes[0].startBlock > endBlock)
{
return 0;
}
uint lastIndex = unStakes.length - 1;
uint diff = 0;
uint stakeEnd;
uint stakeStart;
uint total;
diff = 0;
stakeEnd = 0;
stakeStart = 0;
//last index should now be in our range so loop through until all block numbers are covered
while(lastIndex >= 0) {
if( (unStakes[lastIndex].endBlock != 0 && unStakes[lastIndex].endBlock < startBlock)
|| unStakes[lastIndex].startBlock > endBlock) {
if(lastIndex == 0){
break;
}
lastIndex = lastIndex.sub(1);
continue;
}
stakeEnd = unStakes[lastIndex].endBlock == 0
? endBlock : unStakes[lastIndex].endBlock;
stakeEnd = (stakeEnd >= endBlock ? endBlock : stakeEnd);
stakeStart = unStakes[lastIndex].startBlock < startBlock
? startBlock : unStakes[lastIndex].startBlock;
diff = (stakeEnd == stakeStart ? 1 : stakeEnd.sub(stakeStart));
total = total.add(unStakes[lastIndex].amount.mul(diff));
if(lastIndex == 0){
break;
}
lastIndex = lastIndex.sub(1);
}
return total;
}
function getHoldingsForBlockRange(
Staking[] memory stakes,
uint startBlock,
uint endBlock) internal pure returns (uint){
// If we have bad data, no supply data or it starts after the block we are looking for then we can return zero
if(endBlock < startBlock
|| stakes.length == 0
|| stakes[0].startBlock > endBlock){
return 0;
}
uint lastIndex = stakes.length - 1;
uint diff;
// If the last total supply is before the start we are looking for we can take the last value
if(stakes[lastIndex].startBlock <= startBlock){
diff = endBlock.sub(startBlock) == 0 ? 1 : endBlock.sub(startBlock);
return stakes[lastIndex].total.mul(diff);
}
// working our way back we need to get the first index that falls into our range
// This could be large so need to think of a better way to get here
while(lastIndex > 0 && stakes[lastIndex].startBlock > endBlock){
lastIndex = lastIndex.sub(1);
}
uint total;
diff = 0;
//last index should now be in our range so loop through until all block numbers are covered
while(stakes[lastIndex].startBlock >= startBlock ) {
diff = 1;
if(stakes[lastIndex].startBlock <= startBlock){
diff = endBlock.sub(startBlock) == 0 ? 1 : endBlock.sub(startBlock);
total = total.add(stakes[lastIndex].total.mul(diff));
break;
}
diff = endBlock.sub(stakes[lastIndex].startBlock) == 0
? 1
: endBlock.sub(stakes[lastIndex].startBlock);
total = total.add(stakes[lastIndex].total.mul(diff));
endBlock = stakes[lastIndex].startBlock;
if(lastIndex == 0){
break;
}
lastIndex = lastIndex.sub(1);
}
// If the last total supply is before the start we are looking for we can take the last value
if(stakes[lastIndex].startBlock <= startBlock && startBlock <= endBlock){
diff = endBlock.sub(startBlock) == 0 ? 1 : endBlock.sub(startBlock);
total = total.add(stakes[lastIndex].total.mul(diff));
}
return total;
}
function splitSignature(bytes memory sig)
internal
pure
returns (uint8, bytes32, bytes32)
{
require(sig.length == 65);
bytes32 r;
bytes32 s;
uint8 v;
assembly {
// first 32 bytes, after the length prefix
r := mload(add(sig, 32))
// second 32 bytes
s := mload(add(sig, 64))
// final byte (first byte of the next 32 bytes)
v := byte(0, mload(add(sig, 96)))
}
return (v, r, s);
}
function recoverSigner(bytes32 message, bytes memory sig)
internal
pure
returns (address)
{
uint8 v;
bytes32 r;
bytes32 s;
(v, r, s) = splitSignature(sig);
return ecrecover(message, v, r, s);
}
function prefixed(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
pragma solidity 0.7.6;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20CappedUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
contract iTrustGovernanceToken is ERC20CappedUpgradeable, OwnableUpgradeable, PausableUpgradeable {
using SafeMathUpgradeable for uint;
address internal _treasuryAddress;
uint internal _yearOneSupply;
uint internal _yearTwoSupply;
uint internal _yearThreeSupply;
uint internal _yearFourSupply;
uint internal _yearFiveSupply;
function initialize(
address payable treasuryAddress,
uint cap_,
uint yearOneSupply,
uint yearTwoSupply,
uint yearThreeSupply,
uint yearFourSupply,
uint yearFiveSupply) initializer public {
require(yearOneSupply.add(yearTwoSupply).add(yearThreeSupply).add(yearFourSupply).add(yearFiveSupply) == cap_);
__ERC20_init("iTrust Governance Token", "$ITG");
__ERC20Capped_init(cap_);
__Ownable_init();
__Pausable_init();
_treasuryAddress = treasuryAddress;
_yearOneSupply = yearOneSupply;
_yearTwoSupply = yearTwoSupply;
_yearThreeSupply = yearThreeSupply;
_yearFourSupply = yearFourSupply;
_yearFiveSupply = yearFiveSupply;
}
function mintYearOne() external onlyOwner {
require(totalSupply() == 0);
_mint(_treasuryAddress, _yearOneSupply);
}
function mintYearTwo() external onlyOwner {
require(totalSupply() == _yearOneSupply);
_mint(_treasuryAddress, _yearTwoSupply);
}
function mintYearThree() external onlyOwner {
require(totalSupply() == _yearOneSupply.add(_yearTwoSupply));
_mint(_treasuryAddress, _yearThreeSupply);
}
function mintYearFour() external onlyOwner {
require(totalSupply() == _yearOneSupply.add(_yearTwoSupply).add(_yearThreeSupply));
_mint(_treasuryAddress, _yearFourSupply);
}
function mintYearFive() external onlyOwner {
require(totalSupply() == _yearOneSupply.add(_yearTwoSupply).add(_yearThreeSupply).add(_yearFourSupply));
_mint(_treasuryAddress, _yearFiveSupply);
}
}
pragma solidity 0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import { ITrustVaultLib as VaultLib } from "./../libraries/ItrustVaultLib.sol";
abstract contract BaseContract is Initializable, ContextUpgradeable
{
uint8 internal constant FALSE = 0;
uint8 internal constant TRUE = 1;
uint8 internal _locked;
address internal _iTrustFactoryAddress;
mapping (address => uint32) internal _CurrentRoundNumbers;
mapping (address => uint) internal _TotalUnstakedWnxm;
mapping (address => uint[]) internal _TotalSupplyKeys;
mapping (address => uint[]) internal _TotalUnstakingKeys;
mapping (address => uint[]) internal _TotalSupplyForDayKeys;
mapping (address => address[]) public totalRewardTokenAddresses;
mapping (address => address[]) internal _UnstakingAddresses;
mapping (address => address[]) internal _AccountStakesAddresses;
mapping (address => VaultLib.UnStaking[]) internal _UnstakingRequests;
mapping (address => mapping (address => uint32)) internal _RewardStartingRounds;
mapping (address => mapping (address => VaultLib.AccountStaking)) internal _AccountStakes;
mapping (address => mapping (address => VaultLib.UnStaking[])) internal _AccountUnstakings;
mapping (address => mapping (address => uint8)) internal _RewardTokens;
mapping (address => mapping (address => uint)) internal _AccountUnstakingTotals;
mapping (address => mapping (address => uint)) internal _AccountUnstakedTotals;
mapping (address => mapping (uint => uint)) internal _TotalSupplyHistory;
mapping (address => mapping (address => mapping (address => VaultLib.ClaimedReward))) internal _AccountRewards;
mapping (address => mapping (uint => VaultLib.RewardTokenRound)) internal _Rounds;
mapping (address => mapping (uint => uint)) internal _TotalSupplyForDayHistory;
mapping (address => mapping (uint => VaultLib.UnStaking)) internal _TotalUnstakingHistory;
function _nonReentrant() internal view {
require(_locked == FALSE);
}
}
pragma solidity 0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "./../iTrustVaultFactory.sol";
import "./../tokens/iTrustGovernanceToken.sol";
import "./Vault.sol";
import {
BokkyPooBahsDateTimeLibrary as DateTimeLib
} from "./../3rdParty/BokkyPooBahsDateTimeLibrary.sol";
contract GovernanceDistribution is Initializable, ContextUpgradeable
{
using SafeMathUpgradeable for uint;
uint8 internal constant FALSE = 0;
uint8 internal constant TRUE = 1;
uint8 internal _locked;
uint internal _tokenPerHour;
address internal _iTrustFactoryAddress;
uint[] internal _totalSupplyKeys;
mapping (uint => uint) internal _totalSupplyHistory;
mapping (address => uint[]) internal _totalStakedKeys;
mapping (address => mapping (uint => uint)) internal _totalStakedHistory;
mapping (address => uint) internal _lastClaimedTimes;
mapping(address => mapping(string => bool)) _UsedNonces;
function initialize(
address iTrustFactoryAddress,
uint tokenPerDay
)
initializer
external
{
_iTrustFactoryAddress = iTrustFactoryAddress;
_tokenPerHour = tokenPerDay.div(24);
}
/**
* Public functions
*/
function totalStaked(address account) external view returns(uint) {
_onlyAdmin();
if(_totalStakedKeys[account].length == 0){
return 0;
}
return _totalStakedHistory[account][_totalStakedKeys[account][_totalStakedKeys[account].length.sub(1)]];
}
function totalSupply() external view returns(uint) {
_onlyAdmin();
if(_totalSupplyKeys.length == 0){
return 0;
}
return _totalSupplyHistory[_totalSupplyKeys[_totalSupplyKeys.length.sub(1)]];
}
function calculateRewards() external view returns(uint amount, uint claimedUntil) {
(amount, claimedUntil) = _calculateRewards(_msgSender());
return(amount, claimedUntil);
}
function calculateRewardsForAccount(address account) external view returns(uint amount, uint claimedUntil) {
_isTrustedSigner(_msgSender());
(amount, claimedUntil) = _calculateRewards(account);
return(amount, claimedUntil);
}
function removeStake(address account, uint value) external {
_validateStakingDataAddress();
require(_totalStakedKeys[account].length != 0);
uint currentTime = _getStartOfHourTimeStamp(block.timestamp);
uint lastStakedIndex = _totalStakedKeys[account][_totalStakedKeys[account].length.sub(1)];
if(lastStakedIndex > currentTime){
if(_totalStakedKeys[account].length == 1 || _totalStakedKeys[account][_totalStakedKeys[account].length.sub(2)] != currentTime){
_totalStakedKeys[account][_totalStakedKeys[account].length.sub(1)] = currentTime;
_totalStakedHistory[account][currentTime] = _totalStakedKeys[account].length == 1 ? 0 : _totalStakedHistory[account][_totalStakedKeys[account][_totalStakedKeys[account].length.sub(2)]];
_totalStakedKeys[account].push(lastStakedIndex);
}
_totalStakedHistory[account][lastStakedIndex] = _totalStakedHistory[account][lastStakedIndex].sub(value);
lastStakedIndex = _totalStakedKeys[account][_totalStakedKeys[account].length.sub(2)];
}
require(value <= _totalStakedHistory[account][lastStakedIndex]);
uint newValue = _totalStakedHistory[account][lastStakedIndex].sub(value);
if(lastStakedIndex != currentTime){
_totalStakedKeys[account].push(currentTime);
}
_totalStakedHistory[account][currentTime] = newValue;
require(_totalSupplyKeys.length != 0);
uint lastSupplyIndex = _totalSupplyKeys[_totalSupplyKeys.length.sub(1)];
if(lastSupplyIndex > currentTime){
if(_totalSupplyKeys.length == 1 || _totalSupplyKeys[_totalSupplyKeys.length.sub(2)] != currentTime){
_totalSupplyKeys[_totalSupplyKeys.length.sub(1)] = currentTime;
_totalSupplyHistory[currentTime] = _totalSupplyKeys.length == 1 ? 0 : _totalSupplyHistory[_totalSupplyKeys[_totalSupplyKeys.length.sub(2)]];
_totalSupplyKeys.push(lastSupplyIndex);
}
_totalSupplyHistory[lastSupplyIndex] = _totalSupplyHistory[lastSupplyIndex].sub(value);
lastSupplyIndex = _totalSupplyKeys[_totalSupplyKeys.length.sub(2)];
}
if(lastSupplyIndex != currentTime){
_totalSupplyKeys.push(currentTime);
}
_totalSupplyHistory[currentTime] = _totalSupplyHistory[lastSupplyIndex].sub(value);
}
function addStake(address account, uint value) external {
_validateStakingDataAddress();
uint currentTime = _getStartOfNextHourTimeStamp(block.timestamp);
if(_totalStakedKeys[account].length == 0){
_totalStakedKeys[account].push(currentTime);
_totalStakedHistory[account][currentTime] = value;
} else {
uint lastStakedIndex = _totalStakedKeys[account].length.sub(1);
uint lastTimestamp = _totalStakedKeys[account][lastStakedIndex];
if(lastTimestamp != currentTime){
_totalStakedKeys[account].push(currentTime);
}
_totalStakedHistory[account][currentTime] = _totalStakedHistory[account][lastTimestamp].add(value);
}
if(_totalSupplyKeys.length == 0){
_totalSupplyKeys.push(currentTime);
_totalSupplyHistory[currentTime] = value;
} else {
uint lastSupplyIndex = _totalSupplyKeys.length.sub(1);
uint lastSupplyTimestamp = _totalSupplyKeys[lastSupplyIndex];
if(lastSupplyTimestamp != currentTime){
_totalSupplyKeys.push(currentTime);
}
_totalSupplyHistory[currentTime] = _totalSupplyHistory[lastSupplyTimestamp].add(value);
}
}
function withdrawTokens(uint amount, uint claimedUntil, string memory nonce, bytes memory sig) external {
_nonReentrant();
require(amount != 0);
require(claimedUntil != 0);
require(!_UsedNonces[_msgSender()][nonce]);
_locked = TRUE;
bytes32 abiBytes = keccak256(abi.encodePacked(_msgSender(), amount, claimedUntil, nonce, address(this)));
bytes32 message = _prefixed(abiBytes);
address signer = _recoverSigner(message, sig);
_isTrustedSigner(signer);
_lastClaimedTimes[_msgSender()] = claimedUntil;
_UsedNonces[_msgSender()][nonce] = true;
_getiTrustGovernanceToken().transfer(_msgSender(), amount);
_locked = FALSE;
}
/**
* Internal functions
*/
function _calculateRewards(address account) internal view returns(uint, uint) {
if(_totalStakedKeys[account].length == 0 || _totalSupplyKeys.length == 0){
return (0, 0);
}
uint currentTime = _getStartOfHourTimeStamp(block.timestamp);
uint claimedUntil = _getStartOfHourTimeStamp(block.timestamp);
uint lastClaimedTimestamp = _lastClaimedTimes[account];
// if 0 they have never staked go back to the first stake
if(lastClaimedTimestamp == 0){
lastClaimedTimestamp = _totalStakedKeys[account][0];
}
uint totalRewards = 0;
uint stakedStartingIndex = _totalStakedKeys[account].length.sub(1);
uint supplyStartingIndex = _totalSupplyKeys.length.sub(1);
uint hourReward = 0;
while(currentTime > lastClaimedTimestamp) {
(hourReward, stakedStartingIndex, supplyStartingIndex) = _getTotalRewardHour(account, currentTime, stakedStartingIndex, supplyStartingIndex);
totalRewards = totalRewards.add(hourReward);
currentTime = DateTimeLib.subHours(currentTime, 1);
}
return (totalRewards, claimedUntil);
}
function _getTotalRewardHour(address account, uint hourTimestamp, uint stakedStartingIndex, uint supplyStartingIndex) internal view returns(uint, uint, uint) {
(uint totalStakedForHour, uint returnedStakedStartingIndex) = _getTotalStakedForHour(account, hourTimestamp, stakedStartingIndex);
(uint totalSupplyForHour, uint returnedSupplyStartingIndex) = _getTotalSupplyForHour(hourTimestamp, supplyStartingIndex);
uint reward = 0;
if(totalSupplyForHour > 0 && totalStakedForHour > 0){
uint govTokenPerTokenPerHour = _divider(_tokenPerHour, totalSupplyForHour, 18); // _tokenPerHour.div(totalSupplyForHour);
reward = reward.add(totalStakedForHour.mul(govTokenPerTokenPerHour).div(1e18));
}
return (reward, returnedStakedStartingIndex, returnedSupplyStartingIndex);
}
function _getTotalStakedForHour(address account, uint hourTimestamp, uint startingIndex) internal view returns(uint, uint) {
while(startingIndex != 0 && hourTimestamp <= _totalStakedKeys[account][startingIndex]) {
startingIndex = startingIndex.sub(1);
}
// We never got far enough back before hitting 0, meaning we staked after the hour we are looking up
if(hourTimestamp < _totalStakedKeys[account][startingIndex]){
return (0, startingIndex);
}
return (_totalStakedHistory[account][_totalStakedKeys[account][startingIndex]], startingIndex);
}
function _getTotalSupplyForHour(uint hourTimestamp, uint startingIndex) internal view returns(uint, uint) {
while(startingIndex != 0 && hourTimestamp <= _totalSupplyKeys[startingIndex]) {
startingIndex = startingIndex.sub(1);
}
// We never got far enough back before hitting 0, meaning we staked after the hour we are looking up
if(hourTimestamp < _totalSupplyKeys[startingIndex]){
return (0, startingIndex);
}
return (_totalSupplyHistory[_totalSupplyKeys[startingIndex]], startingIndex);
}
function _getStartOfHourTimeStamp(uint nowDateTime) internal pure returns (uint) {
(uint year, uint month, uint day, uint hour, ,) = DateTimeLib.timestampToDateTime(nowDateTime);
return DateTimeLib.timestampFromDateTime(year, month, day, hour, 0, 0);
}
function _getStartOfNextHourTimeStamp(uint nowDateTime) internal pure returns (uint) {
(uint year, uint month, uint day, uint hour, ,) = DateTimeLib.timestampToDateTime(nowDateTime);
return DateTimeLib.timestampFromDateTime(year, month, day, hour.add(1), 0, 0);
}
function _getITrustVaultFactory() internal view returns(ITrustVaultFactory) {
return ITrustVaultFactory(_iTrustFactoryAddress);
}
function _governanceTokenAddress() internal view returns(address) {
ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress);
return vaultFactory.getGovernanceTokenAddress();
}
function _getiTrustGovernanceToken() internal view returns(iTrustGovernanceToken) {
return iTrustGovernanceToken(_governanceTokenAddress());
}
function _divider(uint numerator, uint denominator, uint precision) internal pure returns(uint) {
return numerator*(uint(10)**uint(precision))/denominator;
}
/**
* Validate functions
*/
function _nonReentrant() internal view {
require(_locked == FALSE);
}
function _onlyAdmin() internal view {
require(
_getITrustVaultFactory().isAddressAdmin(_msgSender()),
"Not admin"
);
}
function _isTrustedSigner(address signer) internal view {
require(
_getITrustVaultFactory().isTrustedSignerAddress(signer),
"Not trusted signer"
);
}
function _validateStakingDataAddress() internal view {
_validateStakingDataAddress(_msgSender());
}
function _validateStakingDataAddress(address contractAddress) internal view {
ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress);
require(vaultFactory.isStakingDataAddress(contractAddress));
}
function _splitSignature(bytes memory sig)
internal
pure
returns (uint8, bytes32, bytes32)
{
require(sig.length == 65);
bytes32 r;
bytes32 s;
uint8 v;
assembly {
// first 32 bytes, after the length prefix
r := mload(add(sig, 32))
// second 32 bytes
s := mload(add(sig, 64))
// final byte (first byte of the next 32 bytes)
v := byte(0, mload(add(sig, 96)))
}
return (v, r, s);
}
function _recoverSigner(bytes32 message, bytes memory sig)
internal
pure
returns (address)
{
uint8 v;
bytes32 r;
bytes32 s;
(v, r, s) = _splitSignature(sig);
return ecrecover(message, v, r, s);
}
function _prefixed(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
pragma solidity 0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./../iTrustVaultFactory.sol";
import "./BaseContract.sol";
import "./StakingDataController/StakeData.sol";
import { ITrustVaultLib as VaultLib } from "./../libraries/ItrustVaultLib.sol";
contract StakingCalculation
{
using SafeMath for uint;
// function getRoundDataForAccount(
// VaultLib.Staking[] memory stakes,
// VaultLib.UnStaking[] memory unstakes,
// uint startBlock,
// uint endBlock) external pure
// returns (uint totalHoldings, uint[] memory stakeBlocks, uint[] memory stakeAmounts, uint[] memory unstakeStartBlocks, uint[] memory unstakeEndBlocks, uint[] memory unstakeAmounts)
// {
// totalHoldings = VaultLib.getHoldingsForBlockRange(stakes, startBlock, endBlock);
// (stakeBlocks, stakeAmounts) = VaultLib.getRoundDataStakesForAccount(stakes, startBlock, endBlock);
// (unstakeStartBlocks, unstakeEndBlocks, unstakeAmounts) = VaultLib.getRoundDataUnstakesForAccount(unstakes, startBlock, endBlock);
// return (totalHoldings, stakeBlocks, stakeAmounts, unstakeStartBlocks, unstakeEndBlocks, unstakeAmounts);
// }
function getUnstakingsForBlockRange(
VaultLib.UnStaking[] memory unStakes,
uint startBlock,
uint endBlock) external pure returns (uint){
return VaultLib.getUnstakingsForBlockRange(
unStakes,
startBlock,
endBlock
);
}
function getHoldingsForBlockRange(
VaultLib.Staking[] memory stakes,
uint startBlock,
uint endBlock) external pure returns (uint){
return VaultLib.getHoldingsForBlockRange(
stakes,
startBlock,
endBlock);
}
}
pragma solidity 0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "./../iTrustVaultFactory.sol";
import "./BaseContract.sol";
import "./StakingDataController/StakeData.sol";
import "./StakingCalculation.sol";
import "./StakingDataController/RoundData.sol";
contract StakingData is BaseContract
{
using SafeMathUpgradeable for uint;
function initialize(
address iTrustFactoryAddress
)
initializer
external
{
_iTrustFactoryAddress = iTrustFactoryAddress;
_locked = FALSE;
}
/**
* Public functions
*/
function _getTotalSupplyForBlockRange(address vaultAddress, uint endBlock, uint startBlock) internal returns(uint) {
(bool success, bytes memory result) =
_stakeDataImplementationAddress()
.delegatecall(
abi.encodeWithSelector(
StakeData.getTotalSupplyForBlockRange.selector,
vaultAddress,
endBlock,
startBlock
)
);
require(success);
return abi.decode(result, (uint256));
}
function _getTotalUnstakingsForBlockRange(address vaultAddress, uint endBlock, uint startBlock) internal returns(uint) {
(bool success, bytes memory result) =
_stakeDataImplementationAddress()
.delegatecall(
abi.encodeWithSelector(
StakeData.getTotalUnstakingsForBlockRange.selector,
vaultAddress,
endBlock,
startBlock
)
);
require(success);
return abi.decode(result, (uint256));
}
function addVault(address vaultAddress) external {
_validateFactory();
_CurrentRoundNumbers[vaultAddress] = 1;
_Rounds[vaultAddress][_CurrentRoundNumbers[vaultAddress]].startBlock = block.number;
_updateTotalSupplyForBlock(0);
}
function endRound(address[] calldata tokens, uint[] calldata tokenAmounts, bool[] calldata ignoreUnstakes, uint commission) external returns(bool) {
_validateVault();
address vaultAddress = _vaultAddress();
uint startBlock = _Rounds[vaultAddress][_CurrentRoundNumbers[vaultAddress]].startBlock;
(bool result, ) = _roundDataImplementationAddress()
.delegatecall(
abi.encodeWithSelector(
RoundData.endRound.selector,
vaultAddress,
tokens,
tokenAmounts,
ignoreUnstakes,
_getTotalSupplyForBlockRange(
vaultAddress,
block.number,
startBlock
),
_getTotalUnstakingsForBlockRange(
vaultAddress,
block.number,
startBlock
),
commission)
);
require(result);
return true;
}
function getCurrentRoundData() external view returns(uint, uint, uint) {
_validateVault();
return _getRoundDataForAddress(_vaultAddress(), _CurrentRoundNumbers[_vaultAddress()]);
}
function getRoundData(uint roundNumberIn) external view returns(uint, uint, uint) {
_validateVault();
return _getRoundDataForAddress(_vaultAddress(), roundNumberIn);
}
function getRoundRewards(uint roundNumber) external view
returns(
address[] memory rewardTokens,
uint[] memory rewardAmounts,
uint[] memory commisionAmounts,
uint[] memory tokenPerBlock,
uint[] memory totalSupply
) {
_validateVault();
return _getRoundRewardsForAddress(_vaultAddress(), roundNumber);
}
function startUnstake(address account, uint256 value) external returns(bool) {
_validateVault();
(bool result, ) = _stakeDataImplementationAddress()
.delegatecall(abi.encodeWithSelector(StakeData.startUnstakeForAddress.selector, _vaultAddress(), account, value));
return result;
}
function getAccountStakes(address account) external view
returns(
uint stakingTotal,
uint unStakingTotal,
uint[] memory unStakingAmounts,
uint[] memory unStakingStarts
) {
_validateVault();
return _getAccountStakesForAddress(_vaultAddress(), account);
}
function getAccountStakingTotal(address account) external view returns (uint) {
_validateVault();
return _AccountStakes[_vaultAddress()][account].total.sub(_AccountUnstakingTotals[_vaultAddress()][account]);
}
function getAllAcountUnstakes() external view returns (address[] memory accounts, uint[] memory startTimes, uint[] memory values) {
_validateVault();
return _getAllAcountUnstakesForAddress(_vaultAddress());
}
function getAccountUnstakedTotal(address account) external view returns (uint) {
_validateVault();
return _AccountUnstakedTotals[_vaultAddress()][account];
}
function authoriseUnstakes(address[] memory account, uint[] memory timestamp) external returns(bool) {
_validateVault();
require(account.length <= 10);
for(uint8 i = 0; i < account.length; i++) {
_authoriseUnstake(_vaultAddress(), account[i], timestamp[i]);
}
return true;
}
function withdrawUnstakedToken(address account, uint amount) external returns(bool) {
_validateVault();
_nonReentrant();
_locked = TRUE;
address vaultAddress = _vaultAddress();
require(_AccountUnstakedTotals[vaultAddress][account] > 0);
require(amount <= _AccountUnstakedTotals[vaultAddress][account]);
_AccountUnstakedTotals[vaultAddress][account] = _AccountUnstakedTotals[vaultAddress][account].sub(amount);
_TotalUnstakedWnxm[vaultAddress] = _TotalUnstakedWnxm[vaultAddress].sub(amount);
_locked = FALSE;
return true;
}
function createStake(uint amount, address account) external returns(bool) {
_validateVault();
(bool result, ) = _stakeDataImplementationAddress()
.delegatecall(abi.encodeWithSelector(StakeData.createStake.selector,_vaultAddress(),amount,account));
return result;
}
function removeStake(uint amount, address account) external returns(bool) {
_validateVault();
(bool result, ) = _stakeDataImplementationAddress()
.delegatecall(abi.encodeWithSelector(StakeData.removeStake.selector, _vaultAddress(), amount, account));
return result;
}
function calculateRewards(address account) external view returns (address[] memory rewardTokens, uint[] memory rewards) {
_validateVault();
return _calculateRewards(account);
}
function withdrawRewards(address account, address[] memory rewardTokens, uint[] memory rewards) external returns(bool) {
_validateVault();
_nonReentrant();
_locked = TRUE;
_withdrawRewards(_vaultAddress(), rewardTokens, rewards, account);
_locked = FALSE;
return true;
}
function updateTotalSupplyForDayAndBlock(uint totalSupply) external returns(bool) {
_validateVault();
_updateTotalSupplyForBlock(totalSupply);
return true;
}
function getTotalSupplyForAccountBlock(address vaultAddress, uint date) external view returns(uint) {
_validateBurnContract();
return _getTotalSupplyForAccountBlock(vaultAddress, date);
}
function getHoldingsForIndexAndBlockForVault(address vaultAddress, uint index, uint blockNumber) external view returns(address indexAddress, uint addressHoldings) {
_validateBurnContract();
return _getHoldingsForIndexAndBlock(vaultAddress, index, blockNumber);
}
function getNumberOfStakingAddressesForVault(address vaultAddress) external view returns(uint) {
_validateBurnContract();
return _AccountStakesAddresses[vaultAddress].length;
}
/**
* Internal functions
*/
function _getHoldingsForIndexAndBlock(address vaultAddress, uint index, uint blockNumber) internal view returns(address indexAddress, uint addressHoldings) {
require(_AccountStakesAddresses[vaultAddress].length - 1 >= index);
indexAddress = _AccountStakesAddresses[vaultAddress][index];
bytes memory data = abi.encodeWithSelector(StakingCalculation.getHoldingsForBlockRange.selector, _AccountStakes[vaultAddress][indexAddress].stakes, blockNumber, blockNumber);
(, bytes memory resultData) = _stakingCalculationsAddress().staticcall(data);
addressHoldings = abi.decode(resultData, (uint256));
return(indexAddress, addressHoldings);
}
function _getTotalSupplyForAccountBlock(address vaultAddress, uint blockNumber) internal view returns(uint) {
uint index = _getIndexForBlock(vaultAddress, blockNumber, 0);
return _TotalSupplyHistory[vaultAddress][_TotalSupplyKeys[vaultAddress][index]];
}
function _authoriseUnstake(address vaultAddress, address account, uint timestamp) internal {
(bool result, ) = _stakeDataImplementationAddress()
.delegatecall(abi.encodeWithSelector(StakeData.authoriseUnstake.selector, vaultAddress, account, timestamp));
require(result);
}
function _updateTotalSupplyForBlock(uint totalSupply) public returns(bool) {
if(_TotalSupplyHistory[_vaultAddress()][block.number] == 0){ // Assumes there will never be 0, could use the array itself to check will look at this again
_TotalSupplyKeys[_vaultAddress()].push(block.number);
}
_TotalSupplyHistory[_vaultAddress()][block.number] = totalSupply;
return true;
}
function _getRoundDataForAddress(address vaultAddress, uint roundNumberIn) internal view returns(uint roundNumber, uint startBlock, uint endBlock) {
roundNumber = roundNumberIn;
startBlock = _Rounds[vaultAddress][roundNumber].startBlock;
endBlock = _Rounds[vaultAddress][roundNumber].endBlock;
return(
roundNumber,
startBlock,
endBlock
);
}
function _getRoundRewardsForAddress(address vaultAddress, uint roundNumber) internal view
returns(
address[] memory rewardTokens,
uint[] memory rewardAmounts,
uint[] memory commissionAmounts,
uint[] memory tokenPerBlock,
uint[] memory totalSupply
) {
rewardTokens = new address[](totalRewardTokenAddresses[vaultAddress].length);
rewardAmounts = new uint[](totalRewardTokenAddresses[vaultAddress].length);
commissionAmounts = new uint[](totalRewardTokenAddresses[vaultAddress].length);
tokenPerBlock = new uint[](totalRewardTokenAddresses[vaultAddress].length);
totalSupply = new uint[](totalRewardTokenAddresses[vaultAddress].length);
for(uint i = 0; i < totalRewardTokenAddresses[vaultAddress].length; i++){
rewardTokens[i] = totalRewardTokenAddresses[vaultAddress][i];
rewardAmounts[i] = _Rounds[vaultAddress][roundNumber].roundData[totalRewardTokenAddresses[vaultAddress][i]].amount;
commissionAmounts[i] = _Rounds[vaultAddress][roundNumber].roundData[totalRewardTokenAddresses[vaultAddress][i]].commissionAmount;
tokenPerBlock[i] = _Rounds[vaultAddress][roundNumber].roundData[totalRewardTokenAddresses[vaultAddress][i]].tokenPerBlock;
totalSupply[i] = _Rounds[vaultAddress][roundNumber].roundData[totalRewardTokenAddresses[vaultAddress][i]].totalSupply;
}
return(
rewardTokens,
rewardAmounts,
commissionAmounts,
tokenPerBlock,
totalSupply
);
}
function _getIndexForBlock(address vaultAddress, uint startBlock, uint startIndex) internal view returns(uint) {
uint i = startIndex == 0 ? _TotalSupplyKeys[vaultAddress].length.sub(1) : startIndex;
uint blockForIndex = _TotalSupplyKeys[vaultAddress][i];
if(_TotalSupplyKeys[vaultAddress][0] > startBlock){
return 0;
}
if(blockForIndex < startBlock){
return i;
}
while(blockForIndex > startBlock){
i = i.sub(1);
blockForIndex = _TotalSupplyKeys[vaultAddress][i];
}
return i;
}
function _getAccountStakesForAddress(address vaultAddress, address account) internal view
returns(
uint stakingTotal,
uint unStakingTotal,
uint[] memory unStakingAmounts,
uint[] memory unStakingStarts
) {
unStakingAmounts = new uint[](_AccountUnstakings[vaultAddress][account].length);
unStakingStarts = new uint[](_AccountUnstakings[vaultAddress][account].length);
for(uint i = 0; i < _AccountUnstakings[vaultAddress][account].length; i++){
if(_AccountUnstakings[vaultAddress][account][i].endBlock == 0){
unStakingAmounts[i] = _AccountUnstakings[vaultAddress][account][i].amount;
unStakingStarts[i] = _AccountUnstakings[vaultAddress][account][i].startDateTime;
}
}
return(
_AccountStakes[vaultAddress][account].total.sub(_AccountUnstakingTotals[vaultAddress][account]),
_AccountUnstakingTotals[vaultAddress][account],
unStakingAmounts,
unStakingStarts
);
}
function _getAllAcountUnstakesForAddress(address vaultAddress) internal view returns (address[] memory accounts, uint[] memory startTimes, uint[] memory values) {
accounts = new address[](_UnstakingRequests[vaultAddress].length);
startTimes = new uint[](_UnstakingRequests[vaultAddress].length);
values = new uint[](_UnstakingRequests[vaultAddress].length);
for(uint i = 0; i < _UnstakingRequests[vaultAddress].length; i++) {
if(_UnstakingRequests[vaultAddress][i].endBlock == 0 ) {
accounts[i] = _UnstakingRequests[vaultAddress][i].account;
startTimes[i] = _UnstakingRequests[vaultAddress][i].startDateTime;
values[i] = _UnstakingRequests[vaultAddress][i].amount;
}
}
return(accounts, startTimes, values);
}
function getUnstakedWxnmTotal() external view returns(uint total) {
_validateVault();
total = _TotalUnstakedWnxm[_vaultAddress()];
}
function _calculateRewards(address account) internal view returns (address[] memory rewardTokens, uint[] memory rewards) {
rewardTokens = totalRewardTokenAddresses[_vaultAddress()];
rewards = new uint[](rewardTokens.length);
for(uint x = 0; x < totalRewardTokenAddresses[_vaultAddress()].length; x++){
(rewards[x]) = _calculateReward(_vaultAddress(), account, rewardTokens[x]);
rewards[x] = rewards[x].div(1 ether);
}
return (rewardTokens, rewards);
}
function _calculateReward(address vaultAddress, address account, address rewardTokenAddress) internal view returns (uint reward){
VaultLib.ClaimedReward memory claimedReward = _AccountRewards[vaultAddress][account][rewardTokenAddress];
if(_RewardStartingRounds[vaultAddress][rewardTokenAddress] == 0){
return(0);
}
uint futureRoundNumber = _CurrentRoundNumbers[vaultAddress] - 1;// one off as the current hasnt closed
address calcContract = _stakingCalculationsAddress();
while(claimedReward.lastClaimedRound < futureRoundNumber
&& _RewardStartingRounds[vaultAddress][rewardTokenAddress] <= futureRoundNumber
&& futureRoundNumber != 0 )
{
if(_Rounds[vaultAddress][futureRoundNumber].roundData[rewardTokenAddress].amount == 0){
futureRoundNumber--;
continue;
}
(, bytes memory resultData) = calcContract.staticcall(abi.encodeWithSignature(
"getHoldingsForBlockRange((uint256,uint256,uint256,uint256)[],uint256,uint256)",
_AccountStakes[vaultAddress][account].stakes,
_Rounds[vaultAddress][futureRoundNumber].startBlock,
_Rounds[vaultAddress][futureRoundNumber].endBlock
));
uint holdingsForRound = abi.decode(resultData, (uint256));
if (!(_Rounds[vaultAddress][futureRoundNumber].roundData[rewardTokenAddress].ignoreUnstakes)) {
(, bytes memory unstakedResultData) = calcContract.staticcall(abi.encodeWithSignature(
"getUnstakingsForBlockRange((address,uint256,uint256,uint256,uint256)[],uint256,uint256)",
_AccountUnstakings[vaultAddress][account],
_Rounds[vaultAddress][futureRoundNumber].startBlock,
_Rounds[vaultAddress][futureRoundNumber].endBlock
));
holdingsForRound = holdingsForRound.sub(abi.decode(unstakedResultData, (uint256)));
}
holdingsForRound = VaultLib.divider(
holdingsForRound,
_Rounds[vaultAddress][futureRoundNumber].roundData[rewardTokenAddress].totalSupply,
18)
.mul(_Rounds[vaultAddress][futureRoundNumber].roundData[rewardTokenAddress].amount);
reward = reward.add(holdingsForRound);
futureRoundNumber--;
}
return (reward);
}
function _withdrawRewards(address vaultAddress, address[] memory rewardTokens, uint[] memory rewards, address account) internal {
for (uint x = 0; x < rewardTokens.length; x++){
_AccountRewards[vaultAddress][account][rewardTokens[x]].amount = _AccountRewards[vaultAddress][account][rewardTokens[x]].amount + rewards[x];
_AccountRewards[vaultAddress][account][rewardTokens[x]].lastClaimedRound = _CurrentRoundNumbers[vaultAddress] - 1;
}
}
function _vaultAddress() internal view returns(address) {
return _msgSender();
}
function _roundDataImplementationAddress() internal view returns(address) {
ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress);
return vaultFactory.getRoundDataImplementationAddress();
}
function _stakeDataImplementationAddress() internal view returns(address) {
ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress);
return vaultFactory.getStakeDataImplementationAddress();
}
function _stakingCalculationsAddress() internal view returns(address) {
ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress);
return address(vaultFactory.getStakingCalculationsAddress());
}
/**
* Validate functions
*/
function _validateVault() internal view {
ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress);
require(vaultFactory.isActiveVault(_vaultAddress()));
}
function _validateBurnContract() internal view {
ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress);
require(vaultFactory.isBurnAddress(_msgSender()));
}
function _validateFactory() internal view {
require(_msgSender() == _iTrustFactoryAddress);
}
}
pragma solidity 0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "./../BaseContract.sol";
contract RoundData is BaseContract
{
using SafeMathUpgradeable for uint;
function endRound(
address vaultAddress,
address[] memory tokens,
uint[] memory tokenAmounts,
bool[] memory ignoreUnstakes,
uint totalSupplyForBlockRange,
uint totalUnstakings,
uint commissionValue)
external
{
require( _Rounds[vaultAddress][_CurrentRoundNumbers[vaultAddress]].startBlock < block.number);
uint32 roundNumber = _CurrentRoundNumbers[vaultAddress];
uint rewardAmount;
uint commissionAmount;
uint tokensPerBlock; //Amoun
for (uint i=0; i < tokens.length; i++) {
rewardAmount = tokenAmounts[i].sub(tokenAmounts[i].mul(commissionValue).div(10000));
commissionAmount = tokenAmounts[i].mul(commissionValue).div(10000);
tokensPerBlock = VaultLib.divider(rewardAmount, _getAdjustedTotalSupply(totalSupplyForBlockRange, totalUnstakings, ignoreUnstakes[i]), 18);
VaultLib.RewardTokenRoundData memory tokenData = VaultLib.RewardTokenRoundData(
{
tokenAddress: tokens[i],
amount: rewardAmount,
commissionAmount: commissionAmount,
tokenPerBlock: tokensPerBlock,//.div(1e18),
totalSupply: _getAdjustedTotalSupply(totalSupplyForBlockRange, totalUnstakings, ignoreUnstakes[i]),
ignoreUnstakes: ignoreUnstakes[i]
}
);
_Rounds[vaultAddress][roundNumber].roundData[tokens[i]] = tokenData;
if(_RewardTokens[vaultAddress][tokens[i]] != TRUE){
_RewardStartingRounds[vaultAddress][tokens[i]] = roundNumber;
totalRewardTokenAddresses[vaultAddress].push(tokens[i]);
_RewardTokens[vaultAddress][tokens[i]] = TRUE;
}
}
//do this last
_Rounds[vaultAddress][_CurrentRoundNumbers[vaultAddress]].endBlock = block.number;
_CurrentRoundNumbers[vaultAddress]++;
_Rounds[vaultAddress][_CurrentRoundNumbers[vaultAddress]].startBlock = block.number;
}
function _getAdjustedTotalSupply(uint totalSupply, uint totalUnstaking, bool ignoreUnstaking) internal pure returns(uint) {
if(ignoreUnstaking) {
return totalSupply;
}
return (totalUnstaking > totalSupply ? 0 : totalSupply.sub(totalUnstaking));
}
}
pragma solidity 0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "./../BaseContract.sol";
import "./../GovernanceDistribution.sol";
contract StakeData is BaseContract
{
using SafeMathUpgradeable for uint;
function startUnstakeForAddress(address vaultAddress, address account, uint256 value) external {
require(
( _AccountStakes[vaultAddress][account].total.sub(_AccountUnstakingTotals[vaultAddress][account]) )
>= value);
_AccountUnstakingTotals[vaultAddress][account] =_AccountUnstakingTotals[vaultAddress][account].add(value);
VaultLib.UnStaking memory unstaking = VaultLib.UnStaking(account, value, block.timestamp, block.number, 0 );
_AccountUnstakings[vaultAddress][account].push(unstaking);
_UnstakingRequests[vaultAddress].push(unstaking);
_UnstakingAddresses[vaultAddress].push(account);
_TotalUnstakingKeys[vaultAddress].push(block.number);
_TotalUnstakingHistory[vaultAddress][block.number] = unstaking;
}
function authoriseUnstake(address vaultAddress, address account, uint timestamp) external {
uint amount = 0;
for(uint i = 0; i < _AccountUnstakings[vaultAddress][account].length; i++){
if(_AccountUnstakings[vaultAddress][account][i].startDateTime == timestamp) {
amount = _AccountUnstakings[vaultAddress][account][i].amount;
_AccountUnstakedTotals[vaultAddress][account] = _AccountUnstakedTotals[vaultAddress][account] + amount;
_AccountUnstakings[vaultAddress][account][i].endBlock = block.number;
_AccountUnstakingTotals[vaultAddress][account] = _AccountUnstakingTotals[vaultAddress][account] - amount;
_TotalUnstakedWnxm[vaultAddress] = _TotalUnstakedWnxm[vaultAddress].add(amount);
break;
}
}
for(uint i = 0; i < _UnstakingRequests[vaultAddress].length; i++){
if(_UnstakingRequests[vaultAddress][i].startDateTime == timestamp &&
_UnstakingRequests[vaultAddress][i].amount == amount &&
_UnstakingRequests[vaultAddress][i].endBlock == 0 &&
_UnstakingAddresses[vaultAddress][i] == account)
{
delete _UnstakingAddresses[vaultAddress][i];
_UnstakingRequests[vaultAddress][i].endBlock = block.number;
_TotalUnstakingHistory[vaultAddress]
[_UnstakingRequests[vaultAddress][i].startBlock].endBlock = block.number;
}
}
_AccountStakes[vaultAddress][account].total = _AccountStakes[vaultAddress][account].total.sub(amount);
_AccountStakes[vaultAddress][account].stakes.push(VaultLib.Staking(block.timestamp, block.number, amount, _AccountStakes[vaultAddress][account].total));
_governanceDistributionContract().removeStake(account, amount);
}
function createStake(address vaultAddress, uint amount, address account) external {
if( _AccountStakes[vaultAddress][account].startRound == 0) {
_AccountStakes[vaultAddress][account].startRound = _CurrentRoundNumbers[vaultAddress];
_AccountStakesAddresses[vaultAddress].push(account);
}
_AccountStakes[vaultAddress][account].total = _AccountStakes[vaultAddress][account].total.add(amount);
// block number is being used to record the block at which staking started for governance token distribution
_AccountStakes[vaultAddress][account].stakes.push(
VaultLib.Staking(block.timestamp, block.number, amount, _AccountStakes[vaultAddress][account].total)
);
_governanceDistributionContract().addStake(account, amount);
}
function removeStake(address vaultAddress, uint amount, address account) external {
if( _AccountStakes[vaultAddress][account].startRound == 0) {
_AccountStakes[vaultAddress][account].startRound = _CurrentRoundNumbers[vaultAddress];
_AccountStakesAddresses[vaultAddress].push(account);
}
require(_AccountStakes[vaultAddress][account].total >= amount);
_AccountStakes[vaultAddress][account].total = _AccountStakes[vaultAddress][account].total.sub(amount);
// block number is being used to record the block at which staking started for governance token distribution
_AccountStakes[vaultAddress][account].stakes.push(
VaultLib.Staking(block.timestamp, block.number, amount, _AccountStakes[vaultAddress][account].total)
);
_governanceDistributionContract().removeStake(account, amount);
}
function _governanceDistributionAddress() internal view returns(address) {
ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress);
return vaultFactory.getGovernanceDistributionAddress();
}
function _governanceDistributionContract() internal view returns(GovernanceDistribution) {
return GovernanceDistribution(_governanceDistributionAddress());
}
function getTotalUnstakingsForBlockRange(address vaultAddress, uint endBlock, uint startBlock) external view returns(uint) {
// If we have bad data, no supply data or it starts after the block we are looking for then we can return zero
if(endBlock < startBlock
|| _TotalUnstakingKeys[vaultAddress].length == 0
|| _TotalUnstakingKeys[vaultAddress][0] > endBlock){
return 0;
}
uint lastIndex = _TotalUnstakingKeys[vaultAddress].length - 1;
uint total;
uint diff;
uint stakeEnd;
uint stakeStart;
if(_TotalUnstakingHistory[vaultAddress][_TotalUnstakingKeys[vaultAddress][lastIndex]].endBlock < startBlock
&& lastIndex == 0) {
return 0;
}
//last index should now be in our range so loop through until all block numbers are covered
while( lastIndex >= 0 ) {
if( _TotalUnstakingHistory[vaultAddress][_TotalUnstakingKeys[vaultAddress][lastIndex]].endBlock < startBlock &&
_TotalUnstakingHistory[vaultAddress][_TotalUnstakingKeys[vaultAddress][lastIndex]].endBlock != 0 )
{
if (lastIndex == 0) {
break;
}
lastIndex = lastIndex.sub(1);
continue;
}
stakeEnd = _TotalUnstakingHistory[vaultAddress][_TotalUnstakingKeys[vaultAddress][lastIndex]].endBlock == 0
? endBlock : _TotalUnstakingHistory[vaultAddress][_TotalUnstakingKeys[vaultAddress][lastIndex]].endBlock;
stakeEnd = (stakeEnd >= endBlock ? endBlock : stakeEnd);
stakeStart = _TotalUnstakingHistory[vaultAddress][_TotalUnstakingKeys[vaultAddress][lastIndex]].startBlock < startBlock
? startBlock : _TotalUnstakingHistory[vaultAddress][_TotalUnstakingKeys[vaultAddress][lastIndex]].startBlock;
diff = (stakeEnd == stakeStart ? 1 : stakeEnd.sub(stakeStart));
total = total.add(_TotalUnstakingHistory[vaultAddress][_TotalUnstakingKeys[vaultAddress][lastIndex]].amount.mul(diff));
if(lastIndex == 0){
break;
}
lastIndex = lastIndex.sub(1);
}
return total;
}
function getTotalSupplyForBlockRange(address vaultAddress, uint endBlock, uint startBlock) external view returns(uint) {
// If we have bad data, no supply data or it starts after the block we are looking for then we can return zero
if(endBlock < startBlock
|| _TotalSupplyKeys[vaultAddress].length == 0
|| _TotalSupplyKeys[vaultAddress][0] > endBlock){
return 0;
}
uint lastIndex = _TotalSupplyKeys[vaultAddress].length - 1;
// If the last total supply is before the start we are looking for we can take the last value
if(_TotalSupplyKeys[vaultAddress][lastIndex] <= startBlock){
return _TotalSupplyHistory[vaultAddress][_TotalSupplyKeys[vaultAddress][lastIndex]].mul(endBlock.sub(startBlock));
}
// working our way back we need to get the first index that falls into our range
// This could be large so need to think of a better way to get here
while(lastIndex > 0 && _TotalSupplyKeys[vaultAddress][lastIndex] > endBlock){
if(lastIndex == 0){
break;
}
lastIndex = lastIndex.sub(1);
}
uint total;
uint diff;
//last index should now be in our range so loop through until all block numbers are covered
while(_TotalSupplyKeys[vaultAddress][lastIndex] >= startBlock) {
diff = 0;
if(_TotalSupplyKeys[vaultAddress][lastIndex] <= startBlock){
diff = endBlock.sub(startBlock) == 0 ? 1 : endBlock.sub(startBlock);
total = total.add(_TotalSupplyHistory[vaultAddress][_TotalSupplyKeys[vaultAddress][lastIndex]].mul(diff));
break;
}
diff = endBlock.sub(_TotalSupplyKeys[vaultAddress][lastIndex]) == 0 ? 1 : endBlock.sub(_TotalSupplyKeys[vaultAddress][lastIndex]);
total = total.add(_TotalSupplyHistory[vaultAddress][_TotalSupplyKeys[vaultAddress][lastIndex]].mul(diff));
endBlock = _TotalSupplyKeys[vaultAddress][lastIndex];
if(lastIndex == 0){
break;
}
lastIndex = lastIndex.sub(1);
}
// If the last total supply is before the start we are looking for we can take the last value
if(_TotalSupplyKeys[vaultAddress][lastIndex] <= startBlock && startBlock < endBlock){
total = total.add(_TotalSupplyHistory[vaultAddress][_TotalSupplyKeys[vaultAddress][lastIndex]].mul(endBlock.sub(startBlock)));
}
return total;
}
}
pragma solidity 0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "./StakingData.sol";
import "./../iTrustVaultFactory.sol";
import { ITrustVaultLib as VaultLib } from "./../libraries/ItrustVaultLib.sol";
contract Vault is
ERC20Upgradeable
{
using SafeMathUpgradeable for uint;
uint8 internal constant FALSE = 0;
uint8 internal constant TRUE = 1;
uint8 internal _Locked;
uint internal _RewardCommission;
uint internal _AdminFee;
address internal _NXMAddress;
address internal _WNXMAddress;
address payable internal _VaultWalletAddress;
address payable internal _TreasuryAddress;
address internal _StakingDataAddress;
address internal _BurnDataAddress;
address internal _iTrustFactoryAddress;
mapping (address => uint256) internal _ReentrantCheck;
mapping(address => mapping(string => bool)) internal _UsedNonces;
event Stake(address indexed account, address indexed tokenAddress, uint amount, uint balance, uint totalStaked);
event UnstakedRequest(address indexed account, uint amount, uint balance, uint totalStaked);
event UnstakedApproved(address indexed account, uint amount, uint balance, uint totalStaked);
event TransferITV(
address indexed fromAccount,
address indexed toAccount,
uint amount,
uint fromBalance,
uint fromTotalStaked,
uint toBalance,
uint toTotalStaked);
function initialize(
address nxmAddress,
address wnxmAddress,
address vaultWalletAddress,
address stakingDataAddress,
address burnDataAddress,
string memory tokenName,
string memory tokenSymbol,
uint adminFee,
uint commission,
address treasuryAddress
)
initializer
external
{
__ERC20_init(tokenName, tokenSymbol);
_Locked = FALSE;
_NXMAddress = nxmAddress;
_WNXMAddress = wnxmAddress;
_VaultWalletAddress = payable(vaultWalletAddress);
_StakingDataAddress = stakingDataAddress;
_BurnDataAddress = burnDataAddress;
_AdminFee = adminFee;
_iTrustFactoryAddress = _msgSender();
_RewardCommission = commission;
_TreasuryAddress = payable(treasuryAddress);
}
/**
* Public functions
*/
function getAdminFee() external view returns (uint) {
return _AdminFee;
}
function SetAdminFee(uint newFee) external {
_onlyAdmin();
_AdminFee = newFee;
}
function setCommission(uint newCommission) external {
_onlyAdmin();
_RewardCommission = newCommission;
}
function setTreasury(address newTreasury) external {
_onlyAdmin();
_TreasuryAddress = payable(newTreasury);
}
function depositNXM(uint256 value) external {
_valueCheck(value);
_nonReentrant();
_Locked = TRUE;
IERC20Upgradeable nxmToken = IERC20Upgradeable(_NXMAddress);
_mint(
_msgSender(),
value
);
require(_getStakingDataContract().createStake(value, _msgSender()));
require(nxmToken.transferFrom(_msgSender(), _VaultWalletAddress, value));
emit Stake(
_msgSender(),
_NXMAddress,
value,
balanceOf(_msgSender()),
_getStakingDataContract().getAccountStakingTotal(_msgSender()));
_Locked = FALSE;
}
function _depositRewardToken(address token, uint amount) internal {
require(token != address(0));
uint commission = 0;
uint remain = amount;
if (_RewardCommission != 0) {
commission = amount.mul(_RewardCommission).div(10000);
remain = amount.sub(commission);
}
IERC20Upgradeable tokenContract = IERC20Upgradeable(token);
if (commission != 0) {
require(tokenContract.transferFrom(msg.sender, _TreasuryAddress, commission));
}
require(tokenContract.transferFrom(msg.sender, address(this), remain));
}
function endRound(address[] calldata tokens, uint[] calldata tokenAmounts, bool[] calldata ignoreUnstakes) external {
_onlyAdmin();
require(tokens.length == tokenAmounts.length);
require(_getStakingDataContract().endRound(tokens, tokenAmounts, ignoreUnstakes, _RewardCommission));
for(uint i = 0; i < tokens.length; i++) {
_depositRewardToken(tokens[i], tokenAmounts[i]);
}
}
function getCurrentRoundData() external view returns(uint roundNumber, uint startBlock, uint endBlock) {
_onlyAdmin();
return _getStakingDataContract().getCurrentRoundData();
}
function getRoundData(uint roundNumberIn) external view returns(uint roundNumber, uint startBlock, uint endBlock) {
_onlyAdmin();
return _getStakingDataContract().getRoundData(roundNumberIn);
}
function getRoundRewards(uint roundNumber) external view
returns(
address[] memory rewardTokens,
uint[] memory rewardAmounts ,
uint[] memory commissionAmounts,
uint[] memory tokenPerDay,
uint[] memory totalSupply
) {
_onlyAdmin();
return _getStakingDataContract().getRoundRewards(roundNumber);
}
function depositWNXM(uint256 value) external {
_valueCheck(value);
_nonReentrant();
_Locked = TRUE;
IERC20Upgradeable wnxmToken = IERC20Upgradeable(_WNXMAddress);
_mint(
_msgSender(),
value
);
require(_getStakingDataContract().createStake(value, _msgSender()));
require(wnxmToken.transferFrom(_msgSender(), _VaultWalletAddress, value));
emit Stake(
_msgSender(),
_WNXMAddress,
value,
balanceOf(_msgSender()),
_getStakingDataContract().getAccountStakingTotal(_msgSender()));
_Locked = FALSE;
}
function startUnstake(uint256 value) external payable {
_nonReentrant();
_Locked = TRUE;
uint adminFee = _AdminFee;
if(adminFee != 0) {
require(msg.value == _AdminFee);
}
require(_getStakingDataContract().startUnstake(_msgSender(), value));
if(adminFee != 0) {
(bool sent, ) = _VaultWalletAddress.call{value: adminFee}("");
require(sent);
}
emit UnstakedRequest(
_msgSender(),
value,
balanceOf(_msgSender()),
_getStakingDataContract().getAccountStakingTotal(_msgSender()));
_Locked = FALSE;
}
function getAccountStakes() external view
returns(
uint stakingTotal,
uint unStakingTotal,
uint[] memory unStakingAmounts,
uint[] memory unStakingStarts
) {
return _getStakingDataContract().getAccountStakes(_msgSender());
}
function getAllAcountUnstakes() external view returns (address[] memory accounts, uint[] memory startTimes, uint[] memory values) {
_onlyAdmin();
return _getStakingDataContract().getAllAcountUnstakes();
}
function getAccountUnstakedTotal() external view returns (uint) {
return _getStakingDataContract().getAccountUnstakedTotal(_msgSender());
}
function getUnstakedwNXMTotal() external view returns (uint) {
return _getStakingDataContract().getUnstakedWxnmTotal();
}
function authoriseUnstakes(address[] memory account, uint[] memory timestamp, uint[] memory amounts) external {
_onlyAdmin();
require(_getStakingDataContract().authoriseUnstakes(account, timestamp));
//for each unstake burn
for(uint i = 0; i < account.length; i++) {
_burn(account[i], amounts[i]);
emit UnstakedApproved(
account[i],
amounts[i],
balanceOf(account[i]),
_getStakingDataContract().getAccountStakingTotal(account[i]));
}
}
function withdrawUnstakedwNXM(uint amount) external {
_nonReentrant();
_Locked = TRUE;
IERC20Upgradeable wnxm = IERC20Upgradeable(_WNXMAddress);
uint balance = wnxm.balanceOf(address(this));
require(amount <= balance);
require(_getStakingDataContract().withdrawUnstakedToken(_msgSender(), amount));
require(wnxm.transfer(msg.sender, amount));
// emit ClaimUnstaked(msg.sender, amount);
_Locked = FALSE;
}
function isAdmin() external view returns (bool) {
ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress);
return vaultFactory.isAddressAdmin(_msgSender());
}
function calculateRewards() external view returns (address[] memory rewardTokens, uint[] memory rewards) {
return _getStakingDataContract().calculateRewards(_msgSender());
}
function calculateRewardsForAccount(address account) external view returns (address[] memory rewardTokens, uint[] memory rewards) {
_isTrustedSigner(_msgSender());
return _getStakingDataContract().calculateRewards(account);
}
function withdrawRewards(address[] memory tokens, uint[] memory rewards, string memory nonce, bytes memory sig) external returns (bool) {
require(!_UsedNonces[_msgSender()][nonce]);
_nonReentrant();
_Locked = TRUE;
bool toClaim = false;
for(uint x = 0; x < tokens.length; x++){
if(rewards[x] != 0) {
toClaim = true;
}
}
require(toClaim == true);
bytes32 abiBytes = keccak256(abi.encodePacked(_msgSender(), tokens, rewards, nonce, address(this)));
bytes32 message = VaultLib.prefixed(abiBytes);
address signer = VaultLib.recoverSigner(message, sig);
_isTrustedSigner(signer);
require(_getStakingDataContract().withdrawRewards(_msgSender(), tokens, rewards));
_UsedNonces[_msgSender()][nonce] = true;
for(uint x = 0; x < tokens.length; x++){
if(rewards[x] != 0) {
IERC20Upgradeable token = IERC20Upgradeable(tokens[x]);
require(token.balanceOf(address(this)) >= rewards[x]);
require(token.transfer(_msgSender() ,rewards[x]));
}
}
_Locked = FALSE;
return true;
}
function burnTokensForAccount(address account, uint tokensToBurn) external returns(bool) {
_nonReentrant();
_validBurnSender();
require(tokensToBurn > 0);
_Locked = TRUE;
_burn(account, tokensToBurn);
require(_getStakingDataContract().removeStake(tokensToBurn, account));
_Locked = FALSE;
return true;
}
/**
* @dev See {IERC20Upgradeable-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 {IERC20Upgradeable-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 override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), allowance(_msgSender(), sender).sub(amount));
return true;
}
/**
* @dev required to be allow for receiving ETH claim payouts
*/
receive() external payable {}
/**
* Private functions
*/
/** @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 override {
super._mint(account, amount);
_updateTotalSupplyForBlock();
}
/**
* @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 override {
super._burn(account, amount);
_updateTotalSupplyForBlock();
}
function _getStakingDataContract() internal view returns (StakingData){
return StakingData(_StakingDataAddress);
}
function _updateTotalSupplyForBlock() internal {
require(_getStakingDataContract().updateTotalSupplyForDayAndBlock(totalSupply()));
}
/**
* @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 override {
require(_getStakingDataContract().removeStake(amount, sender));
require(_getStakingDataContract().createStake(amount, recipient));
super._transfer(sender, recipient, amount);
emit TransferITV(
sender,
recipient,
amount,
balanceOf(sender),
_getStakingDataContract().getAccountStakingTotal(sender),
balanceOf(recipient),
_getStakingDataContract().getAccountStakingTotal(recipient));
_updateTotalSupplyForBlock();
}
/**
* Private validation functions
*/
function _valueCheck(uint value) internal pure {
require(value != 0, "!");
}
function _onlyAdmin() internal view {
ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress);
require(
vaultFactory.isAddressAdmin(_msgSender()),
"NTA"
);
}
function _validBurnSender() internal view {
require(
_BurnDataAddress == _msgSender(),
"NTB"
);
}
function _isTrustedSigner(address signer) internal view {
ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress);
require(
vaultFactory.isTrustedSignerAddress(signer),
"NTS"
);
}
function _nonReentrant() internal view {
require(_Locked == FALSE);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.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 ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
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;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../GSN/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @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 SafeMathUpgradeable {
/**
* @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;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ERC20Upgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Extension of {ERC20} that adds a cap to the supply of tokens.
*/
abstract contract ERC20CappedUpgradeable is Initializable, ERC20Upgradeable {
using SafeMathUpgradeable for uint256;
uint256 private _cap;
/**
* @dev Sets the value of the `cap`. This value is immutable, it can only be
* set once during construction.
*/
function __ERC20Capped_init(uint256 cap_) internal initializer {
__Context_init_unchained();
__ERC20Capped_init_unchained(cap_);
}
function __ERC20Capped_init_unchained(uint256 cap_) internal initializer {
require(cap_ > 0, "ERC20Capped: cap is 0");
_cap = cap_;
}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view returns (uint256) {
return _cap;
}
/**
* @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, "ERC20Capped: cap exceeded");
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../GSN/ContextUpgradeable.sol";
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../proxy/Initializable.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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable for uint256;
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.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_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 { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../GSN/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal {
// solhint-disable-next-line no-inline-assembly
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal virtual view returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback () external payable {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive () external payable {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./UpgradeableProxy.sol";
/**
* @dev This contract implements a proxy that is upgradeable by an admin.
*
* To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
* clashing], which can potentially be used in an attack, this contract uses the
* https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
* things that go hand in hand:
*
* 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
* that call matches one of the admin functions exposed by the proxy itself.
* 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the
* implementation. If the admin tries to call a function on the implementation it will fail with an error that says
* "admin cannot fallback to proxy target".
*
* These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing
* the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due
* to sudden errors when trying to call a function from the proxy implementation.
*
* Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,
* you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.
*/
contract TransparentUpgradeableProxy is UpgradeableProxy {
/**
* @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
* optionally initialized with `_data` as explained in {UpgradeableProxy-constructor}.
*/
constructor(address _logic, address admin_, bytes memory _data) public payable UpgradeableProxy(_logic, _data) {
assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
_setAdmin(admin_);
}
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @dev Returns the current admin.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function admin() external ifAdmin returns (address admin_) {
admin_ = _admin();
}
/**
* @dev Returns the current implementation.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
*/
function implementation() external ifAdmin returns (address implementation_) {
implementation_ = _implementation();
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "TransparentUpgradeableProxy: new admin is the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the implementation of the proxy.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified
* by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the
* proxied contract.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
_upgradeTo(newImplementation);
// solhint-disable-next-line avoid-low-level-calls
(bool success,) = newImplementation.delegatecall(data);
require(success);
}
/**
* @dev Returns the current admin.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = _ADMIN_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
adm := sload(slot)
}
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
bytes32 slot = _ADMIN_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.
*/
function _beforeFallback() internal override virtual {
require(msg.sender != _admin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
super._beforeFallback();
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Proxy.sol";
import "../utils/Address.sol";
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*
* Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see
* {TransparentUpgradeableProxy}.
*/
contract UpgradeableProxy is Proxy {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
* function call, and allows initializating the storage of the proxy like a Solidity constructor.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
// solhint-disable-next-line avoid-low-level-calls
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation address.
*/
function _implementation() internal override view returns (address impl) {
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "UpgradeableProxy: new implementation is not a contract");
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newImplementation)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @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 on 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");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
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);
}
}
}
}
| emit ClaimUnstaked(msg.sender, amount); | function withdrawUnstakedwNXM(uint amount) external {
_nonReentrant();
_Locked = TRUE;
IERC20Upgradeable wnxm = IERC20Upgradeable(_WNXMAddress);
uint balance = wnxm.balanceOf(address(this));
require(amount <= balance);
require(_getStakingDataContract().withdrawUnstakedToken(_msgSender(), amount));
require(wnxm.transfer(msg.sender, amount));
_Locked = FALSE;
}
| 11,785,452 |
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMathLibrary {
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @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;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Integer module of two numbers, truncating the quotient.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) onlyOwner public {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
bool public paused = false;
event Pause();
event Unpause();
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract Operator is Ownable {
mapping(address => bool) public operators;
event OperatorAddressAdded(address addr);
event OperatorAddressRemoved(address addr);
/**
* @dev Throws if called by any account that's not operator.
*/
modifier onlyOperator() {
require(operators[msg.sender]);
_;
}
/**
* @dev add an address to the operators
* @param addr address
* @return true if the address was added to the operators, false if the address was already in the operators
*/
function addAddressToOperators(address addr) onlyOwner public returns(bool success) {
if (!operators[addr]) {
operators[addr] = true;
emit OperatorAddressAdded(addr);
success = true;
}
}
/**
* @dev add addresses to the operators
* @param addrs addresses
* @return true if at least one address was added to the operators,
* false if all addresses were already in the operators
*/
function addAddressesToOperators(address[] addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (addAddressToOperators(addrs[i])) {
success = true;
}
}
}
/**
* @dev remove an address from the operators
* @param addr address
* @return true if the address was removed from the operators,
* false if the address wasn't in the operators in the first place
*/
function removeAddressFromOperators(address addr) onlyOwner public returns(bool success) {
if (operators[addr]) {
operators[addr] = false;
emit OperatorAddressRemoved(addr);
success = true;
}
}
/**
* @dev remove addresses from the operators
* @param addrs addresses
* @return true if at least one address was removed from the operators,
* false if all addresses weren't in the operators in the first place
*/
function removeAddressesFromOperators(address[] addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (removeAddressFromOperators(addrs[i])) {
success = true;
}
}
}
}
contract Whitelist is Operator {
mapping(address => bool) public whitelist;
event WhitelistedAddressAdded(address addr);
event WhitelistedAddressRemoved(address addr);
/**
* @dev Throws if called by any account that's not whitelisted.
*/
modifier onlyWhitelisted() {
require(whitelist[msg.sender]);
_;
}
/**
* @dev add an address to the whitelist
* @param addr address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function addAddressToWhitelist(address addr) onlyOperator public returns(bool success) {
if (!whitelist[addr]) {
whitelist[addr] = true;
emit WhitelistedAddressAdded(addr);
success = true;
}
}
/**
* @dev add addresses to the whitelist
* @param addrs addresses
* @return true if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/
function addAddressesToWhitelist(address[] addrs) onlyOperator public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (addAddressToWhitelist(addrs[i])) {
success = true;
}
}
}
/**
* @dev remove an address from the whitelist
* @param addr address
* @return true if the address was removed from the whitelist,
* false if the address wasn't in the whitelist in the first place
*/
function removeAddressFromWhitelist(address addr) onlyOperator public returns(bool success) {
if (whitelist[addr]) {
whitelist[addr] = false;
emit WhitelistedAddressRemoved(addr);
success = true;
}
}
/**
* @dev remove addresses from the whitelist
* @param addrs addresses
* @return true if at least one address was removed from the whitelist,
* false if all addresses weren't in the whitelist in the first place
*/
function removeAddressesFromWhitelist(address[] addrs) onlyOperator public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (removeAddressFromWhitelist(addrs[i])) {
success = true;
}
}
}
}
interface Token {
function transferFrom(address from, address to, uint amount) external returns(bool);
}
contract Crowdsale is Pausable, Whitelist {
using SafeMathLibrary for uint;
address private EMPTY_ADDRESS = address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF);
Token public token;
address public beneficiary;
address public pool;
uint internal decimals = 10 ** 18;
struct Funding {
address[] buyers;
address[] winners;
uint32 exchangeRatio;
uint8 minAccepting;
uint8 maxAccepting;
uint8 maxLotteryNumber;
}
struct BuyerStage {
uint8 funded;
bool lotteryBonusWon;
bool ultimateBonusWon;
bool bonusReleased;
}
struct Bonus {
uint32 buying;
uint32 lottery;
uint32 ultimate;
}
struct Stage {
Bonus bonus;
address[] buyers;
address[] winners;
address ultimateBonusWinner;
uint32 openingTime;
uint16 fundGoal;
uint16 fundRaised;
uint16 nextLotteryRaised;
}
Funding private funding;
mapping(address => mapping(uint8 => BuyerStage)) private buyers;
mapping(uint8 => Stage) private stages;
event BuyerFunded(address indexed buyer, uint8 stageIndex, uint8 amount);
event BuyerLotteryBonusWon(address indexed buyer, uint8 stageIndex, uint8 lotteryNumber, uint16 fundRaised);
event BuyerUltimateBonusWon(address indexed buyer, uint8 stageIndex);
event StageOpeningTimeSet(uint8 index);
event StageGoalReached(uint8 index);
event FinalGoalReached();
constructor (
address _tokenContractAddress,
address _beneficiary,
address _pool
) public {
token = Token(_tokenContractAddress);
beneficiary = _beneficiary;
pool = _pool;
funding.exchangeRatio = 75000;
funding.minAccepting = 1;
funding.maxAccepting = 10;
funding.maxLotteryNumber = 9;
stages[1].openingTime = 1535500800;
stages[1].fundGoal = 3000;
stages[1].bonus.buying = 3600000; // 80%
stages[1].bonus.lottery = 450000; // 10%
stages[1].bonus.ultimate = 450000; // 10%
stages[2].fundGoal = 3000;
stages[2].bonus.buying = 2250000; // 50%
stages[2].bonus.lottery = 1125000; // 25%
stages[2].bonus.ultimate = 1125000; // 25%
stages[3].fundGoal = 3000;
stages[3].bonus.buying = 1350000; // 30%
stages[3].bonus.lottery = 1575000; // 35%
stages[3].bonus.ultimate = 1575000; // 35%
stages[4].fundGoal = 3000;
stages[4].bonus.buying = 0; // 0%
stages[4].bonus.lottery = 2250000; // 50%
stages[4].bonus.ultimate = 2250000; // 50%
for (uint8 i = 1; i <= 4; i++) {
stages[i].ultimateBonusWinner = EMPTY_ADDRESS;
}
}
function getStageAverageBonus(uint8 _index) public view returns(
uint32 buying,
uint32 lottery,
uint32 ultimate
) {
Stage storage stage = stages[_index];
buying = stage.bonus.buying > 0 ? stage.bonus.buying / stage.fundGoal : 0;
if (stageFundGoalReached(_index) == true) {
lottery = stage.bonus.lottery / uint16(stage.winners.length);
ultimate = stage.bonus.ultimate + (stage.bonus.lottery - lottery * uint16(stage.winners.length));
}
}
function getOpenedStageIndex() public view returns(uint8) {
for (uint8 i = 1; i <= 4; i++) {
if (stages[i].openingTime > 0 && now >= stages[i].openingTime && stages[i].fundRaised < stages[i].fundGoal) {
return i;
}
}
return 0;
}
function getRandomNumber(uint256 power) private view returns (uint256) {
uint256 ddb = uint256(blockhash(block.number - 1));
uint256 r = uint256(keccak256(abi.encodePacked(ddb - 1)));
while (r == 0) {
ddb += 256;
r = uint256(keccak256(abi.encodePacked(ddb - 1)));
}
return uint256(keccak256(abi.encodePacked(r, block.difficulty, now))) % power;
}
function getTodayLotteryNumber() public view returns(uint8) {
return uint8(uint256(keccak256(abi.encodePacked(uint16(now / 1 days)))) % funding.maxLotteryNumber);
}
function getSummary() public view returns(
uint32 exchangeRatio,
uint16 fundGoal,
uint32 bonus,
uint16 fundRaised,
uint16 buyersCount,
uint16 winnersCount,
uint8 minAccepting,
uint8 maxAccepting,
uint8 openedStageIndex,
uint8 todayLotteryNumber
) {
for (uint8 i = 1; i <= 4; i++) {
fundGoal += stages[i].fundGoal;
fundRaised += stages[i].fundRaised;
bonus += stages[i].bonus.buying + stages[i].bonus.lottery + stages[i].bonus.ultimate;
}
exchangeRatio = funding.exchangeRatio;
minAccepting = funding.minAccepting;
maxAccepting = funding.maxAccepting;
buyersCount = uint16(funding.buyers.length);
winnersCount = uint16(funding.winners.length);
openedStageIndex = getOpenedStageIndex();
todayLotteryNumber = getTodayLotteryNumber();
}
function setStageOpeningTime(uint8 _index, uint32 _openingTime) public onlyOwner whenNotPaused returns(bool) {
if (stages[_index].openingTime > 0) {
require(stages[_index].openingTime > now, "Stage has been already opened.");
}
stages[_index].openingTime = _openingTime;
emit StageOpeningTimeSet(_index);
return true;
}
function getStages() public view returns(
uint8[4] index,
uint32[4] openingTime,
uint32[4] buyingBonus,
uint32[4] lotteryBonus,
uint32[4] ultimateBonus,
uint16[4] fundGoal,
uint16[4] fundRaised,
uint16[4] buyersCount,
uint16[4] winnersCount,
address[4] ultimateBonusWinner
) {
for (uint8 i = 1; i <= 4; i++) {
uint8 _i = i - 1;
index[_i] = i;
openingTime[_i] = stages[i].openingTime;
buyingBonus[_i] = stages[i].bonus.buying;
lotteryBonus[_i] = stages[i].bonus.lottery;
ultimateBonus[_i] = stages[i].bonus.ultimate;
fundGoal[_i] = stages[i].fundGoal;
fundRaised[_i] = stages[i].fundRaised;
buyersCount[_i] = uint16(stages[i].buyers.length);
winnersCount[_i] = uint16(stages[i].winners.length);
ultimateBonusWinner[_i] = stages[i].ultimateBonusWinner == EMPTY_ADDRESS ? address(0) : stages[i].ultimateBonusWinner;
}
}
function getBuyers(uint16 _offset, uint8 _limit) public view returns(
uint16 total,
uint16 start,
uint16 end,
uint8 count,
address[] items
) {
total = uint16(funding.buyers.length);
if (total > 0) {
start = _offset > total - 1 ? total - 1 : _offset;
end = (start + _limit > total) ? total - 1 : (start + _limit > 0 ? start + _limit - 1 : 0);
count = uint8(end - start + 1);
}
if (count > 0) {
address[] memory _items = new address[](count);
uint8 j = 0;
for (uint16 i = start; i <= end; i++) {
_items[j] = funding.buyers[i];
j++;
}
items = _items;
}
}
function getWinners(uint16 _offset, uint8 _limit) public view returns(
uint16 total,
uint16 start,
uint16 end,
uint8 count,
address[] items
) {
total = uint16(funding.winners.length);
if (total > 0) {
start = _offset > total - 1 ? total - 1 : _offset;
end = (start + _limit > total) ? total - 1 : (start + _limit > 0 ? start + _limit - 1 : 0);
count = uint8(end - start + 1);
}
if (count > 0) {
address[] memory _items = new address[](count);
uint8 j = 0;
for (uint16 i = start; i <= end; i++) {
_items[j] = funding.winners[i];
j++;
}
items = _items;
}
}
function getStageBuyers(uint8 _index, uint16 _offset, uint8 _limit) public view returns(
uint16 total,
uint16 start,
uint16 end,
uint8 count,
address[] items
) {
Stage storage stage = stages[_index];
total = uint16(stage.buyers.length);
if (total > 0) {
start = _offset > total - 1 ? total - 1 : _offset;
end = (start + _limit > total) ? total - 1 : (start + _limit > 0 ? start + _limit - 1 : 0);
count = uint8(end - start + 1);
}
if (count > 0) {
address[] memory _items = new address[](count);
uint8 j = 0;
for (uint16 i = start; i <= end; i++) {
_items[j] = stage.buyers[i];
j++;
}
items = _items;
}
}
function getStageWinners(uint8 _index, uint16 _offset, uint8 _limit) public view returns(
uint16 total,
uint16 start,
uint16 end,
uint8 count,
address[] items
) {
Stage storage stage = stages[_index];
total = uint16(stage.winners.length);
if (total > 0) {
start = _offset > total - 1 ? total - 1 : _offset;
end = (start + _limit > total) ? total - 1 : (start + _limit > 0 ? start + _limit - 1 : 0);
count = uint8(end - start + 1);
}
if (count > 0) {
address[] memory _items = new address[](count);
uint8 j = 0;
for (uint16 i = start; i <= end; i++) {
_items[j] = stage.winners[i];
j++;
}
items = _items;
}
}
function getBuyer(address _buyer) public view returns(
uint8[4] funded,
uint32[4] buyingBonus,
uint32[4] lotteryBonus,
uint32[4] ultimateBonus,
bool[4] lotteryBonusWon,
bool[4] ultimateBonusWon,
bool[4] bonusReleasable,
bool[4] bonusReleased
) {
for (uint8 i = 1; i <= 4; i++) {
BuyerStage storage buyerStage = buyers[_buyer][i];
funded[i - 1] = buyerStage.funded;
lotteryBonusWon[i - 1] = buyerStage.lotteryBonusWon;
ultimateBonusWon[i - 1] = buyerStage.ultimateBonusWon;
bonusReleasable[i - 1] = stageFundGoalReached(i);
bonusReleased[i - 1] = buyerStage.bonusReleased;
uint32 _buyingBonus;
uint32 _lotteryBonus;
uint32 _ultimateBonus;
(_buyingBonus, _lotteryBonus, _ultimateBonus) = getStageAverageBonus(i);
buyingBonus[i - 1] = buyerStage.funded * _buyingBonus;
if (buyerStage.lotteryBonusWon == true) {
lotteryBonus[i - 1] = _lotteryBonus;
}
if (buyerStage.ultimateBonusWon == true) {
ultimateBonus[i - 1] = _ultimateBonus;
}
}
}
function finalFundGoalReached() public view returns(bool) {
for (uint8 i = 1; i <= 4; i++) {
if (stageFundGoalReached(i) == false) {
return false;
}
}
return true;
}
function stageFundGoalReached(uint8 _index) public view returns(bool) {
Stage storage stage = stages[_index];
return (stage.openingTime > 0 && stage.openingTime <= now && stage.fundRaised >= stage.fundGoal);
}
function tokenFallback(address _from, uint256 _value) public returns(bool) {
require(msg.sender == address(token));
return true;
}
function releasableViewOrSend(address _buyer, bool _send) private returns(uint32) {
uint32 bonus;
for (uint8 i = 1; i <= 4; i++) {
BuyerStage storage buyerStage = buyers[_buyer][i];
if (stageFundGoalReached(i) == false || buyerStage.bonusReleased == true) {
continue;
}
uint32 buyingBonus;
uint32 lotteryBonus;
uint32 ultimateBonus;
(buyingBonus, lotteryBonus, ultimateBonus) = getStageAverageBonus(i);
bonus += buyerStage.funded * buyingBonus;
if (buyerStage.lotteryBonusWon == true) {
bonus += lotteryBonus;
}
if (buyerStage.ultimateBonusWon == true) {
bonus += ultimateBonus;
}
if (_send == true) {
buyerStage.bonusReleased = true;
}
}
if (_send == true) {
require(bonus > 0, "No bonus.");
token.transferFrom(pool, _buyer, uint256(bonus).mul(decimals));
}
return bonus;
}
function releasable(address _buyer) public view returns(uint32) {
return releasableViewOrSend(_buyer, false);
}
function release(address _buyer) private {
releasableViewOrSend(_buyer, true);
}
function getBuyerFunded(address _buyer) private view returns(uint8) {
uint8 funded;
for (uint8 i = 1; i <= 4; i++) {
funded += buyers[_buyer][i].funded;
}
return funded;
}
function hasBuyerLotteryBonusWon(address _buyer) private view returns(bool) {
for (uint8 i = 1; i <= 4; i++) {
if (buyers[_buyer][i].lotteryBonusWon) {
return true;
}
}
return false;
}
function buy(address _buyer, uint256 value) private {
uint8 i = getOpenedStageIndex();
require(i > 0, "No opening stage found.");
require(value >= 1 ether, "The amount too low.");
Stage storage stage = stages[i];
uint16 remain;
uint16 funded = getBuyerFunded(_buyer);
uint256 amount = value.div(1 ether);
uint256 refund = value.sub(amount.mul(1 ether));
remain = funding.maxAccepting - funded;
require(remain > 0, "Total amount too high.");
if (remain < amount) {
refund = refund.add(amount.sub(uint256(remain)).mul(1 ether));
amount = remain;
}
remain = stage.fundGoal - stage.fundRaised;
require(remain > 0, "Stage funding goal reached.");
if (remain < amount) {
refund = refund.add(amount.sub(uint256(remain)).mul(1 ether));
amount = remain;
}
if (refund > 0) {
require(_buyer.send(refund), "Refund failed.");
}
BuyerStage storage buyerStage = buyers[_buyer][i];
if (funded == 0) {
funding.buyers.push(_buyer);
}
if (buyerStage.funded == 0) {
stage.buyers.push(_buyer);
}
buyerStage.funded += uint8(amount);
stage.fundRaised += uint16(amount);
emit BuyerFunded(_buyer, i, uint8(amount));
uint8 todayLotteryNumber = getTodayLotteryNumber();
if (stage.nextLotteryRaised == 0) {
stage.nextLotteryRaised = todayLotteryNumber;
}
uint8 mod;
if (stage.fundRaised > 10) {
mod = uint8(stage.fundRaised % 10);
if (mod == 0) {
mod = 10;
}
} else {
mod = uint8(stage.fundRaised);
}
if (mod >= todayLotteryNumber && stage.fundRaised >= stage.nextLotteryRaised) {
if (hasBuyerLotteryBonusWon(_buyer) == false) {
funding.winners.push(_buyer);
}
if (buyerStage.lotteryBonusWon == false) {
buyerStage.lotteryBonusWon = true;
stage.winners.push(_buyer);
emit BuyerLotteryBonusWon(_buyer, i, todayLotteryNumber, stage.fundRaised);
}
stage.nextLotteryRaised += 10;
}
if (stage.fundGoal == stage.fundRaised) {
stage.ultimateBonusWinner = stage.winners[uint16(getRandomNumber(stage.winners.length - 1))];
buyers[stage.ultimateBonusWinner][i].ultimateBonusWon = true;
emit StageGoalReached(i);
emit BuyerUltimateBonusWon(_buyer, i);
}
if (finalFundGoalReached() == true) {
emit FinalGoalReached();
}
uint256 tokens = amount * funding.exchangeRatio;
require(beneficiary.send(amount.mul(1 ether)), "Send failed.");
require(token.transferFrom(pool, _buyer, tokens.mul(decimals)), "Deliver failed.");
}
function () whenNotPaused onlyWhitelisted public payable {
require(beneficiary != msg.sender, "The beneficiary cannot buy CATT.");
if (msg.value == 0) {
release(msg.sender);
} else {
buy(msg.sender, msg.value);
}
}
} | add an address to the whitelist addr address return true if the address was added to the whitelist, false if the address was already in the whitelist/ | function addAddressToWhitelist(address addr) onlyOperator public returns(bool success) {
if (!whitelist[addr]) {
whitelist[addr] = true;
emit WhitelistedAddressAdded(addr);
success = true;
}
}
| 8,060,229 |
./partial_match/3/0xd6777d4D9877Fc0993609C38d78FB35717a24d11/sources/MasterChef.sol | Withdraw LP tokens from MasterChef. | function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(
user.rewardDebt
);
if (pending > 0) {
safeSushiTransfer(msg.sender, pending);
}
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
| 5,118,722 |
./partial_match/1/0x4511E45687b0F18152A03C4FD20E61fb9B373431/sources/contracts/LOVProduct.sol | Calculates the current yield accumulated to the current day for a given vault vaultAddress is the address of the vault/ | function calculateCurrentYield(address vaultAddress) public onlyValidVault(vaultAddress) {
FCNVaultMetadata storage vaultMetadata = vaults[vaultAddress];
vaultMetadata.calculateCurrentYield();
}
| 3,626,802 |
./full_match/1/0x959D3DdC42740F13A2de31Fb21642B0D332f7203/sources/HoldefiV1.1/HoldefiPausableOwnable.sol | Called by owner to unpause an operation, returns to normal state operation Name of the operation | function unpause(string memory operation)
public
onlyOwner
operationIsValid(operation)
whenPaused(operation)
{
paused[operation].pauseEndTime = 0;
emit OperationUnpaused(operation);
}
| 4,911,715 |
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// ----------------------------------------------------------------------------
// Optino Governance Token
//
// Enjoy. (c) The Optino Project 2020
//
// SPDX-License-Identifier: MIT
// ----------------------------------------------------------------------------
contract TestVote {
string public constant name = "Optino Gov";
bytes32 public constant EIP712_DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
bytes32 public constant EIP712_VOTE_TYPEHASH = keccak256("Vote(uint256 proposalId,uint256 value)");
bytes public constant SIGNING_PREFIX = "\x19Ethereum Signed Message:\n32";
event Voted(address voter, uint proposalId, uint value);
// ------------------------------------------------------------------------
// ecrecover from a signature rather than the signature in parts [v, r, s]
// The signature format is a compact form {bytes32 r}{bytes32 s}{uint8 v}.
// Compact means, uint8 is not padded to 32 bytes.
//
// An invalid signature results in the address(0) being returned, make
// sure that the returned result is checked to be non-zero for validity
//
// Parts from https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
// ------------------------------------------------------------------------
function ecrecoverFromSig(bytes32 hash, bytes memory sig) public pure returns (address recoveredAddress) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65) return address(0);
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
}
// Albeit non-transactional signatures are not specified by the YP, one would expect it to match the YP range of [27, 28]
// geth uses [0, 1] and some clients have followed. This might change, see https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) return address(0);
return ecrecover(hash, v, r, s);
}
function getChainId() internal pure returns (uint) {
uint chainId;
assembly {
chainId := chainid()
}
return chainId;
}
function vote(uint proposalId, uint value) public {
/* return */ _vote(msg.sender, proposalId, value);
}
function voteBySig(uint proposalId, uint value, bytes memory sig) public {
bytes32 digest = voteDigest(proposalId, value);
// EIP-712 address voter = ecrecoverFromSig(digest, sig);
// web3js 0.x go-ethereum
address voter = ecrecoverFromSig(keccak256(abi.encodePacked(SIGNING_PREFIX, digest)), sig);
require(voter != address(0), "OptinoGov::voteBySig: invalid signature");
/* return */ _vote(voter, proposalId, value);
}
function voteBySigs(uint proposalId, uint[] memory values, bytes[] memory sigs) public {
require(values.length == sigs.length);
for (uint i = 0; i < values.length; i++) {
uint value = values[i];
bytes memory sig = sigs[i];
bytes32 digest = voteDigest(proposalId, value);
// EIP-712 address voter = ecrecoverFromSig(digest, sig);
// web3js 0.x go-ethereum
address voter = ecrecoverFromSig(keccak256(abi.encodePacked(SIGNING_PREFIX, digest)), sig);
require(voter != address(0), "OptinoGov::voteBySig: invalid signature");
/* return */ _vote(voter, proposalId, value);
}
}
function voteDigest(uint proposalId, uint value) public view returns (bytes32 digest) {
bytes32 domainSeparator = keccak256(abi.encode(EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(EIP712_VOTE_TYPEHASH, proposalId, value));
digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
function _vote(address voter, uint proposalId, uint value) internal {
emit Voted(voter, proposalId, value);
// require(state(proposalId) == ProposalState.Active, "GovernorAlpha::_castVote: voting is closed");
// Proposal storage proposal = proposals[proposalId];
// Receipt storage receipt = proposal.receipts[voter];
// require(receipt.hasVoted == false, "GovernorAlpha::_castVote: voter already voted");
// uint96 votes = comp.getPriorVotes(voter, proposal.startBlock);
// if (support) {
// proposal.forVotes = add256(proposal.forVotes, votes);
// } else {
// proposal.againstVotes = add256(proposal.againstVotes, votes);
// }
// receipt.hasVoted = true;
// receipt.support = support;
// receipt.votes = votes;
// emit VoteCast(voter, proposalId, support, votes);
}
// function voteHash(address tokenOwner, uint vote) public view returns (bytes32 hash) {
// hash = keccak256(signedTransferSig, address(this), tokenOwner, to, tokens, fee, nonce);
// }
}
| EIP-712 address voter = ecrecoverFromSig(digest, sig); web3js 0.x go-ethereum | function voteBySigs(uint proposalId, uint[] memory values, bytes[] memory sigs) public {
require(values.length == sigs.length);
for (uint i = 0; i < values.length; i++) {
uint value = values[i];
bytes memory sig = sigs[i];
bytes32 digest = voteDigest(proposalId, value);
address voter = ecrecoverFromSig(keccak256(abi.encodePacked(SIGNING_PREFIX, digest)), sig);
require(voter != address(0), "OptinoGov::voteBySig: invalid signature");
}
| 12,544,107 |
./full_match/5/0x4D8BD96BD1718DAcb06D3359f978E985Aa9B25D7/sources/contracts/pcdeployed beeboxPayroll.sol | change token address | function changeTokenAddress(address _tokenAddress) public {
require(msg.sender == owner, "You are not allowed to change token address");
tokenAddress = _tokenAddress;
Token = IERC20(tokenAddress);
}
| 1,869,897 |
// the azimuth logic contract
// https://azimuth.network
pragma solidity 0.4.24;
////////////////////////////////////////////////////////////////////////////////
// Imports
////////////////////////////////////////////////////////////////////////////////
// OpenZeppelin's Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// Azimuth's SafeMath8.sol
/**
* @title SafeMath8
* @dev Math operations for uint8 with safety checks that throw on error
*/
library SafeMath8 {
function mul(uint8 a, uint8 b) internal pure returns (uint8) {
uint8 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint8 a, uint8 b) internal pure returns (uint8) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint8 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint8 a, uint8 b) internal pure returns (uint8) {
assert(b <= a);
return a - b;
}
function add(uint8 a, uint8 b) internal pure returns (uint8) {
uint8 c = a + b;
assert(c >= a);
return c;
}
}
// Azimuth's SafeMath16.sol
/**
* @title SafeMath16
* @dev Math operations for uint16 with safety checks that throw on error
*/
library SafeMath16 {
function mul(uint16 a, uint16 b) internal pure returns (uint16) {
uint16 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint16 a, uint16 b) internal pure returns (uint16) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint16 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint16 a, uint16 b) internal pure returns (uint16) {
assert(b <= a);
return a - b;
}
function add(uint16 a, uint16 b) internal pure returns (uint16) {
uint16 c = a + b;
assert(c >= a);
return c;
}
}
// OpenZeppelin's SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// OpenZeppelin's ERC165.sol
/**
* @title ERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface ERC165 {
/**
* @notice Query if a contract implements an interface
* @param _interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
// OpenZeppelin's SupportsInterfaceWithLookup.sol
/**
* @title SupportsInterfaceWithLookup
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract SupportsInterfaceWithLookup is ERC165 {
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor()
public
{
_registerInterface(InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool)
{
return supportedInterfaces[_interfaceId];
}
/**
* @dev private method for registering an interface
*/
function _registerInterface(bytes4 _interfaceId)
internal
{
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
// OpenZeppelin's ERC721Basic.sol
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic is ERC165 {
bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
bytes4 internal constant InterfaceId_ERC721Exists = 0x4f558e79;
/*
* 0x4f558e79 ===
* bytes4(keccak256('exists(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId)
public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator)
public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
// OpenZeppelin's ERC721.sol
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic {
function name() external view returns (string _name);
function symbol() external view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
// OpenZeppelin's ERC721Receiver.sol
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the contract address is always the message sender.
* @param _operator The address which called `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _tokenId The NFT identifier which is being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes _data
)
public
returns(bytes4);
}
// OpenZeppelin's AddressUtils.sol
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param _addr address to check
* @return whether the target address is a contract
*/
function isContract(address _addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
// Azimuth's Azimuth.sol
// Azimuth: point state data contract
//
// This contract is used for storing all data related to Azimuth points
// and their ownership. Consider this contract the Azimuth ledger.
//
// It also contains permissions data, which ties in to ERC721
// functionality. Operators of an address are allowed to transfer
// ownership of all points owned by their associated address
// (ERC721's approveAll()). A transfer proxy is allowed to transfer
// ownership of a single point (ERC721's approve()).
// Separate from ERC721 are managers, assigned per point. They are
// allowed to perform "low-impact" operations on the owner's points,
// like configuring public keys and making escape requests.
//
// Since data stores are difficult to upgrade, this contract contains
// as little actual business logic as possible. Instead, the data stored
// herein can only be modified by this contract's owner, which can be
// changed and is thus upgradable/replaceable.
//
// This contract will be owned by the Ecliptic contract.
//
contract Azimuth is Ownable
{
//
// Events
//
// OwnerChanged: :point is now owned by :owner
//
event OwnerChanged(uint32 indexed point, address indexed owner);
// Activated: :point is now active
//
event Activated(uint32 indexed point);
// Spawned: :prefix has spawned :child
//
event Spawned(uint32 indexed prefix, uint32 indexed child);
// EscapeRequested: :point has requested a new :sponsor
//
event EscapeRequested(uint32 indexed point, uint32 indexed sponsor);
// EscapeCanceled: :point's :sponsor request was canceled or rejected
//
event EscapeCanceled(uint32 indexed point, uint32 indexed sponsor);
// EscapeAccepted: :point confirmed with a new :sponsor
//
event EscapeAccepted(uint32 indexed point, uint32 indexed sponsor);
// LostSponsor: :point's :sponsor is now refusing it service
//
event LostSponsor(uint32 indexed point, uint32 indexed sponsor);
// ChangedKeys: :point has new network public keys
//
event ChangedKeys( uint32 indexed point,
bytes32 encryptionKey,
bytes32 authenticationKey,
uint32 cryptoSuiteVersion,
uint32 keyRevisionNumber );
// BrokeContinuity: :point has a new continuity number, :number
//
event BrokeContinuity(uint32 indexed point, uint32 number);
// ChangedSpawnProxy: :spawnProxy can now spawn using :point
//
event ChangedSpawnProxy(uint32 indexed point, address indexed spawnProxy);
// ChangedTransferProxy: :transferProxy can now transfer ownership of :point
//
event ChangedTransferProxy( uint32 indexed point,
address indexed transferProxy );
// ChangedManagementProxy: :managementProxy can now manage :point
//
event ChangedManagementProxy( uint32 indexed point,
address indexed managementProxy );
// ChangedVotingProxy: :votingProxy can now vote using :point
//
event ChangedVotingProxy(uint32 indexed point, address indexed votingProxy);
// ChangedDns: dnsDomains have been updated
//
event ChangedDns(string primary, string secondary, string tertiary);
//
// Structures
//
// Size: kinds of points registered on-chain
//
// NOTE: the order matters, because of Solidity enum numbering
//
enum Size
{
Galaxy, // = 0
Star, // = 1
Planet // = 2
}
// Point: state of a point
//
// While the ordering of the struct members is semantically chaotic,
// they are ordered to tightly pack them into Ethereum's 32-byte storage
// slots, which reduces gas costs for some function calls.
// The comment ticks indicate assumed slot boundaries.
//
struct Point
{
// encryptionKey: (curve25519) encryption public key, or 0 for none
//
bytes32 encryptionKey;
//
// authenticationKey: (ed25519) authentication public key, or 0 for none
//
bytes32 authenticationKey;
//
// spawned: for stars and galaxies, all :active children
//
uint32[] spawned;
//
// hasSponsor: true if the sponsor still supports the point
//
bool hasSponsor;
// active: whether point can be linked
//
// false: point belongs to prefix, cannot be configured or linked
// true: point no longer belongs to prefix, can be configured and linked
//
bool active;
// escapeRequested: true if the point has requested to change sponsors
//
bool escapeRequested;
// sponsor: the point that supports this one on the network, or,
// if :hasSponsor is false, the last point that supported it.
// (by default, the point's half-width prefix)
//
uint32 sponsor;
// escapeRequestedTo: if :escapeRequested is true, new sponsor requested
//
uint32 escapeRequestedTo;
// cryptoSuiteVersion: version of the crypto suite used for the pubkeys
//
uint32 cryptoSuiteVersion;
// keyRevisionNumber: incremented every time the public keys change
//
uint32 keyRevisionNumber;
// continuityNumber: incremented to indicate network-side state loss
//
uint32 continuityNumber;
}
// Deed: permissions for a point
//
struct Deed
{
// owner: address that owns this point
//
address owner;
// managementProxy: 0, or another address with the right to perform
// low-impact, managerial operations on this point
//
address managementProxy;
// spawnProxy: 0, or another address with the right to spawn children
// of this point
//
address spawnProxy;
// votingProxy: 0, or another address with the right to vote as this point
//
address votingProxy;
// transferProxy: 0, or another address with the right to transfer
// ownership of this point
//
address transferProxy;
}
//
// General state
//
// points: per point, general network-relevant point state
//
mapping(uint32 => Point) public points;
// rights: per point, on-chain ownership and permissions
//
mapping(uint32 => Deed) public rights;
// operators: per owner, per address, has the right to transfer ownership
// of all the owner's points (ERC721)
//
mapping(address => mapping(address => bool)) public operators;
// dnsDomains: base domains for contacting galaxies
//
// dnsDomains[0] is primary, the others are used as fallbacks
//
string[3] public dnsDomains;
//
// Lookups
//
// sponsoring: per point, the points they are sponsoring
//
mapping(uint32 => uint32[]) public sponsoring;
// sponsoringIndexes: per point, per point, (index + 1) in
// the sponsoring array
//
mapping(uint32 => mapping(uint32 => uint256)) public sponsoringIndexes;
// escapeRequests: per point, the points they have open escape requests from
//
mapping(uint32 => uint32[]) public escapeRequests;
// escapeRequestsIndexes: per point, per point, (index + 1) in
// the escapeRequests array
//
mapping(uint32 => mapping(uint32 => uint256)) public escapeRequestsIndexes;
// pointsOwnedBy: per address, the points they own
//
mapping(address => uint32[]) public pointsOwnedBy;
// pointOwnerIndexes: per owner, per point, (index + 1) in
// the pointsOwnedBy array
//
// We delete owners by moving the last entry in the array to the
// newly emptied slot, which is (n - 1) where n is the value of
// pointOwnerIndexes[owner][point].
//
mapping(address => mapping(uint32 => uint256)) public pointOwnerIndexes;
// managerFor: per address, the points they are the management proxy for
//
mapping(address => uint32[]) public managerFor;
// managerForIndexes: per address, per point, (index + 1) in
// the managerFor array
//
mapping(address => mapping(uint32 => uint256)) public managerForIndexes;
// spawningFor: per address, the points they can spawn with
//
mapping(address => uint32[]) public spawningFor;
// spawningForIndexes: per address, per point, (index + 1) in
// the spawningFor array
//
mapping(address => mapping(uint32 => uint256)) public spawningForIndexes;
// votingFor: per address, the points they can vote with
//
mapping(address => uint32[]) public votingFor;
// votingForIndexes: per address, per point, (index + 1) in
// the votingFor array
//
mapping(address => mapping(uint32 => uint256)) public votingForIndexes;
// transferringFor: per address, the points they can transfer
//
mapping(address => uint32[]) public transferringFor;
// transferringForIndexes: per address, per point, (index + 1) in
// the transferringFor array
//
mapping(address => mapping(uint32 => uint256)) public transferringForIndexes;
//
// Logic
//
// constructor(): configure default dns domains
//
constructor()
public
{
setDnsDomains("example.com", "example.com", "example.com");
}
// setDnsDomains(): set the base domains used for contacting galaxies
//
// Note: since a string is really just a byte[], and Solidity can't
// work with two-dimensional arrays yet, we pass in the three
// domains as individual strings.
//
function setDnsDomains(string _primary, string _secondary, string _tertiary)
onlyOwner
public
{
dnsDomains[0] = _primary;
dnsDomains[1] = _secondary;
dnsDomains[2] = _tertiary;
emit ChangedDns(_primary, _secondary, _tertiary);
}
//
// Point reading
//
// isActive(): return true if _point is active
//
function isActive(uint32 _point)
view
external
returns (bool equals)
{
return points[_point].active;
}
// getKeys(): returns the public keys and their details, as currently
// registered for _point
//
function getKeys(uint32 _point)
view
external
returns (bytes32 crypt, bytes32 auth, uint32 suite, uint32 revision)
{
Point storage point = points[_point];
return (point.encryptionKey,
point.authenticationKey,
point.cryptoSuiteVersion,
point.keyRevisionNumber);
}
// getKeyRevisionNumber(): gets the revision number of _point's current
// public keys
//
function getKeyRevisionNumber(uint32 _point)
view
external
returns (uint32 revision)
{
return points[_point].keyRevisionNumber;
}
// hasBeenLinked(): returns true if the point has ever been assigned keys
//
function hasBeenLinked(uint32 _point)
view
external
returns (bool result)
{
return ( points[_point].keyRevisionNumber > 0 );
}
// isLive(): returns true if _point currently has keys properly configured
//
function isLive(uint32 _point)
view
external
returns (bool result)
{
Point storage point = points[_point];
return ( point.encryptionKey != 0 &&
point.authenticationKey != 0 &&
point.cryptoSuiteVersion != 0 );
}
// getContinuityNumber(): returns _point's current continuity number
//
function getContinuityNumber(uint32 _point)
view
external
returns (uint32 continuityNumber)
{
return points[_point].continuityNumber;
}
// getSpawnCount(): return the number of children spawned by _point
//
function getSpawnCount(uint32 _point)
view
external
returns (uint32 spawnCount)
{
uint256 len = points[_point].spawned.length;
assert(len < 2**32);
return uint32(len);
}
// getSpawned(): return array of points created under _point
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getSpawned(uint32 _point)
view
external
returns (uint32[] spawned)
{
return points[_point].spawned;
}
// hasSponsor(): returns true if _point's sponsor is providing it service
//
function hasSponsor(uint32 _point)
view
external
returns (bool has)
{
return points[_point].hasSponsor;
}
// getSponsor(): returns _point's current (or most recent) sponsor
//
function getSponsor(uint32 _point)
view
external
returns (uint32 sponsor)
{
return points[_point].sponsor;
}
// isSponsor(): returns true if _sponsor is currently providing service
// to _point
//
function isSponsor(uint32 _point, uint32 _sponsor)
view
external
returns (bool result)
{
Point storage point = points[_point];
return ( point.hasSponsor &&
(point.sponsor == _sponsor) );
}
// getSponsoringCount(): returns the number of points _sponsor is
// providing service to
//
function getSponsoringCount(uint32 _sponsor)
view
external
returns (uint256 count)
{
return sponsoring[_sponsor].length;
}
// getSponsoring(): returns a list of points _sponsor is providing
// service to
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getSponsoring(uint32 _sponsor)
view
external
returns (uint32[] sponsees)
{
return sponsoring[_sponsor];
}
// escaping
// isEscaping(): returns true if _point has an outstanding escape request
//
function isEscaping(uint32 _point)
view
external
returns (bool escaping)
{
return points[_point].escapeRequested;
}
// getEscapeRequest(): returns _point's current escape request
//
// the returned escape request is only valid as long as isEscaping()
// returns true
//
function getEscapeRequest(uint32 _point)
view
external
returns (uint32 escape)
{
return points[_point].escapeRequestedTo;
}
// isRequestingEscapeTo(): returns true if _point has an outstanding
// escape request targetting _sponsor
//
function isRequestingEscapeTo(uint32 _point, uint32 _sponsor)
view
public
returns (bool equals)
{
Point storage point = points[_point];
return (point.escapeRequested && (point.escapeRequestedTo == _sponsor));
}
// getEscapeRequestsCount(): returns the number of points _sponsor
// is providing service to
//
function getEscapeRequestsCount(uint32 _sponsor)
view
external
returns (uint256 count)
{
return escapeRequests[_sponsor].length;
}
// getEscapeRequests(): get the points _sponsor has received escape
// requests from
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getEscapeRequests(uint32 _sponsor)
view
external
returns (uint32[] requests)
{
return escapeRequests[_sponsor];
}
//
// Point writing
//
// activatePoint(): activate a point, register it as spawned by its prefix
//
function activatePoint(uint32 _point)
onlyOwner
external
{
// make a point active, setting its sponsor to its prefix
//
Point storage point = points[_point];
require(!point.active);
point.active = true;
registerSponsor(_point, true, getPrefix(_point));
emit Activated(_point);
}
// setKeys(): set network public keys of _point to _encryptionKey and
// _authenticationKey, with the specified _cryptoSuiteVersion
//
function setKeys(uint32 _point,
bytes32 _encryptionKey,
bytes32 _authenticationKey,
uint32 _cryptoSuiteVersion)
onlyOwner
external
{
Point storage point = points[_point];
if ( point.encryptionKey == _encryptionKey &&
point.authenticationKey == _authenticationKey &&
point.cryptoSuiteVersion == _cryptoSuiteVersion )
{
return;
}
point.encryptionKey = _encryptionKey;
point.authenticationKey = _authenticationKey;
point.cryptoSuiteVersion = _cryptoSuiteVersion;
point.keyRevisionNumber++;
emit ChangedKeys(_point,
_encryptionKey,
_authenticationKey,
_cryptoSuiteVersion,
point.keyRevisionNumber);
}
// incrementContinuityNumber(): break continuity for _point
//
function incrementContinuityNumber(uint32 _point)
onlyOwner
external
{
Point storage point = points[_point];
point.continuityNumber++;
emit BrokeContinuity(_point, point.continuityNumber);
}
// registerSpawn(): add a point to its prefix's list of spawned points
//
function registerSpawned(uint32 _point)
onlyOwner
external
{
// if a point is its own prefix (a galaxy) then don't register it
//
uint32 prefix = getPrefix(_point);
if (prefix == _point)
{
return;
}
// register a new spawned point for the prefix
//
points[prefix].spawned.push(_point);
emit Spawned(prefix, _point);
}
// loseSponsor(): indicates that _point's sponsor is no longer providing
// it service
//
function loseSponsor(uint32 _point)
onlyOwner
external
{
Point storage point = points[_point];
if (!point.hasSponsor)
{
return;
}
registerSponsor(_point, false, point.sponsor);
emit LostSponsor(_point, point.sponsor);
}
// setEscapeRequest(): for _point, start an escape request to _sponsor
//
function setEscapeRequest(uint32 _point, uint32 _sponsor)
onlyOwner
external
{
if (isRequestingEscapeTo(_point, _sponsor))
{
return;
}
registerEscapeRequest(_point, true, _sponsor);
emit EscapeRequested(_point, _sponsor);
}
// cancelEscape(): for _point, stop the current escape request, if any
//
function cancelEscape(uint32 _point)
onlyOwner
external
{
Point storage point = points[_point];
if (!point.escapeRequested)
{
return;
}
uint32 request = point.escapeRequestedTo;
registerEscapeRequest(_point, false, 0);
emit EscapeCanceled(_point, request);
}
// doEscape(): perform the requested escape
//
function doEscape(uint32 _point)
onlyOwner
external
{
Point storage point = points[_point];
require(point.escapeRequested);
registerSponsor(_point, true, point.escapeRequestedTo);
registerEscapeRequest(_point, false, 0);
emit EscapeAccepted(_point, point.sponsor);
}
//
// Point utils
//
// getPrefix(): compute prefix ("parent") of _point
//
function getPrefix(uint32 _point)
pure
public
returns (uint16 prefix)
{
if (_point < 0x10000)
{
return uint16(_point % 0x100);
}
return uint16(_point % 0x10000);
}
// getPointSize(): return the size of _point
//
function getPointSize(uint32 _point)
external
pure
returns (Size _size)
{
if (_point < 0x100) return Size.Galaxy;
if (_point < 0x10000) return Size.Star;
return Size.Planet;
}
// internal use
// registerSponsor(): set the sponsorship state of _point and update the
// reverse lookup for sponsors
//
function registerSponsor(uint32 _point, bool _hasSponsor, uint32 _sponsor)
internal
{
Point storage point = points[_point];
bool had = point.hasSponsor;
uint32 prev = point.sponsor;
// if we didn't have a sponsor, and won't get one,
// or if we get the sponsor we already have,
// nothing will change, so jump out early.
//
if ( (!had && !_hasSponsor) ||
(had && _hasSponsor && prev == _sponsor) )
{
return;
}
// if the point used to have a different sponsor, do some gymnastics
// to keep the reverse lookup gapless. delete the point from the old
// sponsor's list, then fill that gap with the list tail.
//
if (had)
{
// i: current index in previous sponsor's list of sponsored points
//
uint256 i = sponsoringIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :sponsoringIndexes reference
//
uint32[] storage prevSponsoring = sponsoring[prev];
uint256 last = prevSponsoring.length - 1;
uint32 moved = prevSponsoring[last];
prevSponsoring[i] = moved;
sponsoringIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevSponsoring[last]);
prevSponsoring.length = last;
sponsoringIndexes[prev][_point] = 0;
}
if (_hasSponsor)
{
uint32[] storage newSponsoring = sponsoring[_sponsor];
newSponsoring.push(_point);
sponsoringIndexes[_sponsor][_point] = newSponsoring.length;
}
point.sponsor = _sponsor;
point.hasSponsor = _hasSponsor;
}
// registerEscapeRequest(): set the escape state of _point and update the
// reverse lookup for sponsors
//
function registerEscapeRequest( uint32 _point,
bool _isEscaping, uint32 _sponsor )
internal
{
Point storage point = points[_point];
bool was = point.escapeRequested;
uint32 prev = point.escapeRequestedTo;
// if we weren't escaping, and won't be,
// or if we were escaping, and the new target is the same,
// nothing will change, so jump out early.
//
if ( (!was && !_isEscaping) ||
(was && _isEscaping && prev == _sponsor) )
{
return;
}
// if the point used to have a different request, do some gymnastics
// to keep the reverse lookup gapless. delete the point from the old
// sponsor's list, then fill that gap with the list tail.
//
if (was)
{
// i: current index in previous sponsor's list of sponsored points
//
uint256 i = escapeRequestsIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :escapeRequestsIndexes reference
//
uint32[] storage prevRequests = escapeRequests[prev];
uint256 last = prevRequests.length - 1;
uint32 moved = prevRequests[last];
prevRequests[i] = moved;
escapeRequestsIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevRequests[last]);
prevRequests.length = last;
escapeRequestsIndexes[prev][_point] = 0;
}
if (_isEscaping)
{
uint32[] storage newRequests = escapeRequests[_sponsor];
newRequests.push(_point);
escapeRequestsIndexes[_sponsor][_point] = newRequests.length;
}
point.escapeRequestedTo = _sponsor;
point.escapeRequested = _isEscaping;
}
//
// Deed reading
//
// owner
// getOwner(): return owner of _point
//
function getOwner(uint32 _point)
view
external
returns (address owner)
{
return rights[_point].owner;
}
// isOwner(): true if _point is owned by _address
//
function isOwner(uint32 _point, address _address)
view
external
returns (bool result)
{
return (rights[_point].owner == _address);
}
// getOwnedPointCount(): return length of array of points that _whose owns
//
function getOwnedPointCount(address _whose)
view
external
returns (uint256 count)
{
return pointsOwnedBy[_whose].length;
}
// getOwnedPoints(): return array of points that _whose owns
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getOwnedPoints(address _whose)
view
external
returns (uint32[] ownedPoints)
{
return pointsOwnedBy[_whose];
}
// getOwnedPointAtIndex(): get point at _index from array of points that
// _whose owns
//
function getOwnedPointAtIndex(address _whose, uint256 _index)
view
external
returns (uint32 point)
{
uint32[] storage owned = pointsOwnedBy[_whose];
require(_index < owned.length);
return owned[_index];
}
// management proxy
// getManagementProxy(): returns _point's current management proxy
//
function getManagementProxy(uint32 _point)
view
external
returns (address manager)
{
return rights[_point].managementProxy;
}
// isManagementProxy(): returns true if _proxy is _point's management proxy
//
function isManagementProxy(uint32 _point, address _proxy)
view
external
returns (bool result)
{
return (rights[_point].managementProxy == _proxy);
}
// canManage(): true if _who is the owner or manager of _point
//
function canManage(uint32 _point, address _who)
view
external
returns (bool result)
{
Deed storage deed = rights[_point];
return ( (0x0 != _who) &&
( (_who == deed.owner) ||
(_who == deed.managementProxy) ) );
}
// getManagerForCount(): returns the amount of points _proxy can manage
//
function getManagerForCount(address _proxy)
view
external
returns (uint256 count)
{
return managerFor[_proxy].length;
}
// getManagerFor(): returns the points _proxy can manage
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getManagerFor(address _proxy)
view
external
returns (uint32[] mfor)
{
return managerFor[_proxy];
}
// spawn proxy
// getSpawnProxy(): returns _point's current spawn proxy
//
function getSpawnProxy(uint32 _point)
view
external
returns (address spawnProxy)
{
return rights[_point].spawnProxy;
}
// isSpawnProxy(): returns true if _proxy is _point's spawn proxy
//
function isSpawnProxy(uint32 _point, address _proxy)
view
external
returns (bool result)
{
return (rights[_point].spawnProxy == _proxy);
}
// canSpawnAs(): true if _who is the owner or spawn proxy of _point
//
function canSpawnAs(uint32 _point, address _who)
view
external
returns (bool result)
{
Deed storage deed = rights[_point];
return ( (0x0 != _who) &&
( (_who == deed.owner) ||
(_who == deed.spawnProxy) ) );
}
// getSpawningForCount(): returns the amount of points _proxy
// can spawn with
//
function getSpawningForCount(address _proxy)
view
external
returns (uint256 count)
{
return spawningFor[_proxy].length;
}
// getSpawningFor(): get the points _proxy can spawn with
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getSpawningFor(address _proxy)
view
external
returns (uint32[] sfor)
{
return spawningFor[_proxy];
}
// voting proxy
// getVotingProxy(): returns _point's current voting proxy
//
function getVotingProxy(uint32 _point)
view
external
returns (address voter)
{
return rights[_point].votingProxy;
}
// isVotingProxy(): returns true if _proxy is _point's voting proxy
//
function isVotingProxy(uint32 _point, address _proxy)
view
external
returns (bool result)
{
return (rights[_point].votingProxy == _proxy);
}
// canVoteAs(): true if _who is the owner of _point,
// or the voting proxy of _point's owner
//
function canVoteAs(uint32 _point, address _who)
view
external
returns (bool result)
{
Deed storage deed = rights[_point];
return ( (0x0 != _who) &&
( (_who == deed.owner) ||
(_who == deed.votingProxy) ) );
}
// getVotingForCount(): returns the amount of points _proxy can vote as
//
function getVotingForCount(address _proxy)
view
external
returns (uint256 count)
{
return votingFor[_proxy].length;
}
// getVotingFor(): returns the points _proxy can vote as
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getVotingFor(address _proxy)
view
external
returns (uint32[] vfor)
{
return votingFor[_proxy];
}
// transfer proxy
// getTransferProxy(): returns _point's current transfer proxy
//
function getTransferProxy(uint32 _point)
view
external
returns (address transferProxy)
{
return rights[_point].transferProxy;
}
// isTransferProxy(): returns true if _proxy is _point's transfer proxy
//
function isTransferProxy(uint32 _point, address _proxy)
view
external
returns (bool result)
{
return (rights[_point].transferProxy == _proxy);
}
// canTransfer(): true if _who is the owner or transfer proxy of _point,
// or is an operator for _point's current owner
//
function canTransfer(uint32 _point, address _who)
view
external
returns (bool result)
{
Deed storage deed = rights[_point];
return ( (0x0 != _who) &&
( (_who == deed.owner) ||
(_who == deed.transferProxy) ||
operators[deed.owner][_who] ) );
}
// getTransferringForCount(): returns the amount of points _proxy
// can transfer
//
function getTransferringForCount(address _proxy)
view
external
returns (uint256 count)
{
return transferringFor[_proxy].length;
}
// getTransferringFor(): get the points _proxy can transfer
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getTransferringFor(address _proxy)
view
external
returns (uint32[] tfor)
{
return transferringFor[_proxy];
}
// isOperator(): returns true if _operator is allowed to transfer
// ownership of _owner's points
//
function isOperator(address _owner, address _operator)
view
external
returns (bool result)
{
return operators[_owner][_operator];
}
//
// Deed writing
//
// setOwner(): set owner of _point to _owner
//
// Note: setOwner() only implements the minimal data storage
// logic for a transfer; the full transfer is implemented in
// Ecliptic.
//
// Note: _owner must not be the zero address.
//
function setOwner(uint32 _point, address _owner)
onlyOwner
external
{
// prevent burning of points by making zero the owner
//
require(0x0 != _owner);
// prev: previous owner, if any
//
address prev = rights[_point].owner;
if (prev == _owner)
{
return;
}
// if the point used to have a different owner, do some gymnastics to
// keep the list of owned points gapless. delete this point from the
// list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous owner's list of owned points
//
uint256 i = pointOwnerIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :pointOwnerIndexes reference
//
uint32[] storage owner = pointsOwnedBy[prev];
uint256 last = owner.length - 1;
uint32 moved = owner[last];
owner[i] = moved;
pointOwnerIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(owner[last]);
owner.length = last;
pointOwnerIndexes[prev][_point] = 0;
}
// update the owner list and the owner's index list
//
rights[_point].owner = _owner;
pointsOwnedBy[_owner].push(_point);
pointOwnerIndexes[_owner][_point] = pointsOwnedBy[_owner].length;
emit OwnerChanged(_point, _owner);
}
// setManagementProxy(): makes _proxy _point's management proxy
//
function setManagementProxy(uint32 _point, address _proxy)
onlyOwner
external
{
Deed storage deed = rights[_point];
address prev = deed.managementProxy;
if (prev == _proxy)
{
return;
}
// if the point used to have a different manager, do some gymnastics
// to keep the reverse lookup gapless. delete the point from the
// old manager's list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous manager's list of managed points
//
uint256 i = managerForIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :managerForIndexes reference
//
uint32[] storage prevMfor = managerFor[prev];
uint256 last = prevMfor.length - 1;
uint32 moved = prevMfor[last];
prevMfor[i] = moved;
managerForIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevMfor[last]);
prevMfor.length = last;
managerForIndexes[prev][_point] = 0;
}
if (0x0 != _proxy)
{
uint32[] storage mfor = managerFor[_proxy];
mfor.push(_point);
managerForIndexes[_proxy][_point] = mfor.length;
}
deed.managementProxy = _proxy;
emit ChangedManagementProxy(_point, _proxy);
}
// setSpawnProxy(): makes _proxy _point's spawn proxy
//
function setSpawnProxy(uint32 _point, address _proxy)
onlyOwner
external
{
Deed storage deed = rights[_point];
address prev = deed.spawnProxy;
if (prev == _proxy)
{
return;
}
// if the point used to have a different spawn proxy, do some
// gymnastics to keep the reverse lookup gapless. delete the point
// from the old proxy's list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous proxy's list of spawning points
//
uint256 i = spawningForIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :spawningForIndexes reference
//
uint32[] storage prevSfor = spawningFor[prev];
uint256 last = prevSfor.length - 1;
uint32 moved = prevSfor[last];
prevSfor[i] = moved;
spawningForIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevSfor[last]);
prevSfor.length = last;
spawningForIndexes[prev][_point] = 0;
}
if (0x0 != _proxy)
{
uint32[] storage sfor = spawningFor[_proxy];
sfor.push(_point);
spawningForIndexes[_proxy][_point] = sfor.length;
}
deed.spawnProxy = _proxy;
emit ChangedSpawnProxy(_point, _proxy);
}
// setVotingProxy(): makes _proxy _point's voting proxy
//
function setVotingProxy(uint32 _point, address _proxy)
onlyOwner
external
{
Deed storage deed = rights[_point];
address prev = deed.votingProxy;
if (prev == _proxy)
{
return;
}
// if the point used to have a different voter, do some gymnastics
// to keep the reverse lookup gapless. delete the point from the
// old voter's list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous voter's list of points it was
// voting for
//
uint256 i = votingForIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :votingForIndexes reference
//
uint32[] storage prevVfor = votingFor[prev];
uint256 last = prevVfor.length - 1;
uint32 moved = prevVfor[last];
prevVfor[i] = moved;
votingForIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevVfor[last]);
prevVfor.length = last;
votingForIndexes[prev][_point] = 0;
}
if (0x0 != _proxy)
{
uint32[] storage vfor = votingFor[_proxy];
vfor.push(_point);
votingForIndexes[_proxy][_point] = vfor.length;
}
deed.votingProxy = _proxy;
emit ChangedVotingProxy(_point, _proxy);
}
// setManagementProxy(): makes _proxy _point's transfer proxy
//
function setTransferProxy(uint32 _point, address _proxy)
onlyOwner
external
{
Deed storage deed = rights[_point];
address prev = deed.transferProxy;
if (prev == _proxy)
{
return;
}
// if the point used to have a different transfer proxy, do some
// gymnastics to keep the reverse lookup gapless. delete the point
// from the old proxy's list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous proxy's list of transferable points
//
uint256 i = transferringForIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :transferringForIndexes reference
//
uint32[] storage prevTfor = transferringFor[prev];
uint256 last = prevTfor.length - 1;
uint32 moved = prevTfor[last];
prevTfor[i] = moved;
transferringForIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevTfor[last]);
prevTfor.length = last;
transferringForIndexes[prev][_point] = 0;
}
if (0x0 != _proxy)
{
uint32[] storage tfor = transferringFor[_proxy];
tfor.push(_point);
transferringForIndexes[_proxy][_point] = tfor.length;
}
deed.transferProxy = _proxy;
emit ChangedTransferProxy(_point, _proxy);
}
// setOperator(): dis/allow _operator to transfer ownership of all points
// owned by _owner
//
// operators are part of the ERC721 standard
//
function setOperator(address _owner, address _operator, bool _approved)
onlyOwner
external
{
operators[_owner][_operator] = _approved;
}
}
// Azimuth's ReadsAzimuth.sol
// ReadsAzimuth: referring to and testing against the Azimuth
// data contract
//
// To avoid needless repetition, this contract provides common
// checks and operations using the Azimuth contract.
//
contract ReadsAzimuth
{
// azimuth: points data storage contract.
//
Azimuth public azimuth;
// constructor(): set the Azimuth data contract's address
//
constructor(Azimuth _azimuth)
public
{
azimuth = _azimuth;
}
// activePointOwner(): require that :msg.sender is the owner of _point,
// and that _point is active
//
modifier activePointOwner(uint32 _point)
{
require( azimuth.isOwner(_point, msg.sender) &&
azimuth.isActive(_point) );
_;
}
// activePointManager(): require that :msg.sender can manage _point,
// and that _point is active
//
modifier activePointManager(uint32 _point)
{
require( azimuth.canManage(_point, msg.sender) &&
azimuth.isActive(_point) );
_;
}
// activePointSpawner(): require that :msg.sender can spawn as _point,
// and that _point is active
//
modifier activePointSpawner(uint32 _point)
{
require( azimuth.canSpawnAs(_point, msg.sender) &&
azimuth.isActive(_point) );
_;
}
// activePointVoter(): require that :msg.sender can vote as _point,
// and that _point is active
//
modifier activePointVoter(uint32 _point)
{
require( azimuth.canVoteAs(_point, msg.sender) &&
azimuth.isActive(_point) );
_;
}
}
// Azimuth's Polls.sol
// Polls: proposals & votes data contract
//
// This contract is used for storing all data related to the proposals
// of the senate (galaxy owners) and their votes on those proposals.
// It keeps track of votes and uses them to calculate whether a majority
// is in favor of a proposal.
//
// Every galaxy can only vote on a proposal exactly once. Votes cannot
// be changed. If a proposal fails to achieve majority within its
// duration, it can be restarted after its cooldown period has passed.
//
// The requirements for a proposal to achieve majority are as follows:
// - At least 1/4 of the currently active voters (rounded down) must have
// voted in favor of the proposal,
// - More than half of the votes cast must be in favor of the proposal,
// and this can no longer change, either because
// - the poll duration has passed, or
// - not enough voters remain to take away the in-favor majority.
// As soon as these conditions are met, no further interaction with
// the proposal is possible. Achieving majority is permanent.
//
// Since data stores are difficult to upgrade, all of the logic unrelated
// to the voting itself (that is, determining who is eligible to vote)
// is expected to be implemented by this contract's owner.
//
// This contract will be owned by the Ecliptic contract.
//
contract Polls is Ownable
{
using SafeMath for uint256;
using SafeMath16 for uint16;
using SafeMath8 for uint8;
// UpgradePollStarted: a poll on :proposal has opened
//
event UpgradePollStarted(address proposal);
// DocumentPollStarted: a poll on :proposal has opened
//
event DocumentPollStarted(bytes32 proposal);
// UpgradeMajority: :proposal has achieved majority
//
event UpgradeMajority(address proposal);
// DocumentMajority: :proposal has achieved majority
//
event DocumentMajority(bytes32 proposal);
// Poll: full poll state
//
struct Poll
{
// start: the timestamp at which the poll was started
//
uint256 start;
// voted: per galaxy, whether they have voted on this poll
//
bool[256] voted;
// yesVotes: amount of votes in favor of the proposal
//
uint16 yesVotes;
// noVotes: amount of votes against the proposal
//
uint16 noVotes;
// duration: amount of time during which the poll can be voted on
//
uint256 duration;
// cooldown: amount of time before the (non-majority) poll can be reopened
//
uint256 cooldown;
}
// pollDuration: duration set for new polls. see also Poll.duration above
//
uint256 public pollDuration;
// pollCooldown: cooldown set for new polls. see also Poll.cooldown above
//
uint256 public pollCooldown;
// totalVoters: amount of active galaxies
//
uint16 public totalVoters;
// upgradeProposals: list of all upgrades ever proposed
//
// this allows clients to discover the existence of polls.
// from there, they can do liveness checks on the polls themselves.
//
address[] public upgradeProposals;
// upgradePolls: per address, poll held to determine if that address
// will become the new ecliptic
//
mapping(address => Poll) public upgradePolls;
// upgradeHasAchievedMajority: per address, whether that address
// has ever achieved majority
//
// If we did not store this, we would have to look at old poll data
// to see whether or not a proposal has ever achieved majority.
// Since the outcome of a poll is calculated based on :totalVoters,
// which may not be consistent across time, we need to store outcomes
// explicitly instead of re-calculating them. This allows us to always
// tell with certainty whether or not a majority was achieved,
// regardless of the current :totalVoters.
//
mapping(address => bool) public upgradeHasAchievedMajority;
// documentProposals: list of all documents ever proposed
//
// this allows clients to discover the existence of polls.
// from there, they can do liveness checks on the polls themselves.
//
bytes32[] public documentProposals;
// documentPolls: per hash, poll held to determine if the corresponding
// document is accepted by the galactic senate
//
mapping(bytes32 => Poll) public documentPolls;
// documentHasAchievedMajority: per hash, whether that hash has ever
// achieved majority
//
// the note for upgradeHasAchievedMajority above applies here as well
//
mapping(bytes32 => bool) public documentHasAchievedMajority;
// documentMajorities: all hashes that have achieved majority
//
bytes32[] public documentMajorities;
// constructor(): initial contract configuration
//
constructor(uint256 _pollDuration, uint256 _pollCooldown)
public
{
reconfigure(_pollDuration, _pollCooldown);
}
// reconfigure(): change poll duration and cooldown
//
function reconfigure(uint256 _pollDuration, uint256 _pollCooldown)
public
onlyOwner
{
require( (5 days <= _pollDuration) && (_pollDuration <= 90 days) &&
(5 days <= _pollCooldown) && (_pollCooldown <= 90 days) );
pollDuration = _pollDuration;
pollCooldown = _pollCooldown;
}
// incrementTotalVoters(): increase the amount of registered voters
//
function incrementTotalVoters()
external
onlyOwner
{
require(totalVoters < 256);
totalVoters = totalVoters.add(1);
}
// getAllUpgradeProposals(): return array of all upgrade proposals ever made
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getUpgradeProposals()
external
view
returns (address[] proposals)
{
return upgradeProposals;
}
// getUpgradeProposalCount(): get the number of unique proposed upgrades
//
function getUpgradeProposalCount()
external
view
returns (uint256 count)
{
return upgradeProposals.length;
}
// getAllDocumentProposals(): return array of all upgrade proposals ever made
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getDocumentProposals()
external
view
returns (bytes32[] proposals)
{
return documentProposals;
}
// getDocumentProposalCount(): get the number of unique proposed upgrades
//
function getDocumentProposalCount()
external
view
returns (uint256 count)
{
return documentProposals.length;
}
// getDocumentMajorities(): return array of all document majorities
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getDocumentMajorities()
external
view
returns (bytes32[] majorities)
{
return documentMajorities;
}
// hasVotedOnUpgradePoll(): returns true if _galaxy has voted
// on the _proposal
//
function hasVotedOnUpgradePoll(uint8 _galaxy, address _proposal)
external
view
returns (bool result)
{
return upgradePolls[_proposal].voted[_galaxy];
}
// hasVotedOnDocumentPoll(): returns true if _galaxy has voted
// on the _proposal
//
function hasVotedOnDocumentPoll(uint8 _galaxy, bytes32 _proposal)
external
view
returns (bool result)
{
return documentPolls[_proposal].voted[_galaxy];
}
// startUpgradePoll(): open a poll on making _proposal the new ecliptic
//
function startUpgradePoll(address _proposal)
external
onlyOwner
{
// _proposal must not have achieved majority before
//
require(!upgradeHasAchievedMajority[_proposal]);
Poll storage poll = upgradePolls[_proposal];
// if the proposal is being made for the first time, register it.
//
if (0 == poll.start)
{
upgradeProposals.push(_proposal);
}
startPoll(poll);
emit UpgradePollStarted(_proposal);
}
// startDocumentPoll(): open a poll on accepting the document
// whose hash is _proposal
//
function startDocumentPoll(bytes32 _proposal)
external
onlyOwner
{
// _proposal must not have achieved majority before
//
require(!documentHasAchievedMajority[_proposal]);
Poll storage poll = documentPolls[_proposal];
// if the proposal is being made for the first time, register it.
//
if (0 == poll.start)
{
documentProposals.push(_proposal);
}
startPoll(poll);
emit DocumentPollStarted(_proposal);
}
// startPoll(): open a new poll, or re-open an old one
//
function startPoll(Poll storage _poll)
internal
{
// check that the poll has cooled down enough to be started again
//
// for completely new polls, the values used will be zero
//
require( block.timestamp > ( _poll.start.add(
_poll.duration.add(
_poll.cooldown )) ) );
// set started poll state
//
_poll.start = block.timestamp;
delete _poll.voted;
_poll.yesVotes = 0;
_poll.noVotes = 0;
_poll.duration = pollDuration;
_poll.cooldown = pollCooldown;
}
// castUpgradeVote(): as galaxy _as, cast a vote on the _proposal
//
// _vote is true when in favor of the proposal, false otherwise
//
function castUpgradeVote(uint8 _as, address _proposal, bool _vote)
external
onlyOwner
returns (bool majority)
{
Poll storage poll = upgradePolls[_proposal];
processVote(poll, _as, _vote);
return updateUpgradePoll(_proposal);
}
// castDocumentVote(): as galaxy _as, cast a vote on the _proposal
//
// _vote is true when in favor of the proposal, false otherwise
//
function castDocumentVote(uint8 _as, bytes32 _proposal, bool _vote)
external
onlyOwner
returns (bool majority)
{
Poll storage poll = documentPolls[_proposal];
processVote(poll, _as, _vote);
return updateDocumentPoll(_proposal);
}
// processVote(): record a vote from _as on the _poll
//
function processVote(Poll storage _poll, uint8 _as, bool _vote)
internal
{
// assist symbolic execution tools
//
assert(block.timestamp >= _poll.start);
require( // may only vote once
//
!_poll.voted[_as] &&
//
// may only vote when the poll is open
//
(block.timestamp < _poll.start.add(_poll.duration)) );
// update poll state to account for the new vote
//
_poll.voted[_as] = true;
if (_vote)
{
_poll.yesVotes = _poll.yesVotes.add(1);
}
else
{
_poll.noVotes = _poll.noVotes.add(1);
}
}
// updateUpgradePoll(): check whether the _proposal has achieved
// majority, updating state, sending an event,
// and returning true if it has
//
function updateUpgradePoll(address _proposal)
public
onlyOwner
returns (bool majority)
{
// _proposal must not have achieved majority before
//
require(!upgradeHasAchievedMajority[_proposal]);
// check for majority in the poll
//
Poll storage poll = upgradePolls[_proposal];
majority = checkPollMajority(poll);
// if majority was achieved, update the state and send an event
//
if (majority)
{
upgradeHasAchievedMajority[_proposal] = true;
emit UpgradeMajority(_proposal);
}
return majority;
}
// updateDocumentPoll(): check whether the _proposal has achieved majority,
// updating the state and sending an event if it has
//
// this can be called by anyone, because the ecliptic does not
// need to be aware of the result
//
function updateDocumentPoll(bytes32 _proposal)
public
returns (bool majority)
{
// _proposal must not have achieved majority before
//
require(!documentHasAchievedMajority[_proposal]);
// check for majority in the poll
//
Poll storage poll = documentPolls[_proposal];
majority = checkPollMajority(poll);
// if majority was achieved, update state and send an event
//
if (majority)
{
documentHasAchievedMajority[_proposal] = true;
documentMajorities.push(_proposal);
emit DocumentMajority(_proposal);
}
return majority;
}
// checkPollMajority(): returns true if the majority is in favor of
// the subject of the poll
//
function checkPollMajority(Poll _poll)
internal
view
returns (bool majority)
{
return ( // poll must have at least the minimum required yes-votes
//
(_poll.yesVotes >= (totalVoters / 4)) &&
//
// and have a majority...
//
(_poll.yesVotes > _poll.noVotes) &&
//
// ...that is indisputable
//
( // either because the poll has ended
//
(block.timestamp > _poll.start.add(_poll.duration)) ||
//
// or there are more yes votes than there can be no votes
//
( _poll.yesVotes > totalVoters.sub(_poll.yesVotes) ) ) );
}
}
// Azimuth's Claims.sol
// Claims: simple identity management
//
// This contract allows points to document claims about their owner.
// Most commonly, these are about identity, with a claim's protocol
// defining the context or platform of the claim, and its dossier
// containing proof of its validity.
// Points are limited to a maximum of 16 claims.
//
// For existing claims, the dossier can be updated, or the claim can
// be removed entirely. It is recommended to remove any claims associated
// with a point when it is about to be transferred to a new owner.
// For convenience, the owner of the Azimuth contract (the Ecliptic)
// is allowed to clear claims for any point, allowing it to do this for
// you on-transfer.
//
contract Claims is ReadsAzimuth
{
// ClaimAdded: a claim was added by :by
//
event ClaimAdded( uint32 indexed by,
string _protocol,
string _claim,
bytes _dossier );
// ClaimRemoved: a claim was removed by :by
//
event ClaimRemoved(uint32 indexed by, string _protocol, string _claim);
// maxClaims: the amount of claims that can be registered per point
//
uint8 constant maxClaims = 16;
// Claim: claim details
//
struct Claim
{
// protocol: context of the claim
//
string protocol;
// claim: the claim itself
//
string claim;
// dossier: data relating to the claim, as proof
//
bytes dossier;
}
// per point, list of claims
//
mapping(uint32 => Claim[maxClaims]) public claims;
// constructor(): register the azimuth contract.
//
constructor(Azimuth _azimuth)
ReadsAzimuth(_azimuth)
public
{
//
}
// addClaim(): register a claim as _point
//
function addClaim(uint32 _point,
string _protocol,
string _claim,
bytes _dossier)
external
activePointManager(_point)
{
// require non-empty protocol and claim fields
//
require( ( 0 < bytes(_protocol).length ) &&
( 0 < bytes(_claim).length ) );
// cur: index + 1 of the claim if it already exists, 0 otherwise
//
uint8 cur = findClaim(_point, _protocol, _claim);
// if the claim doesn't yet exist, store it in state
//
if (cur == 0)
{
// if there are no empty slots left, this throws
//
uint8 empty = findEmptySlot(_point);
claims[_point][empty] = Claim(_protocol, _claim, _dossier);
}
//
// if the claim has been made before, update the version in state
//
else
{
claims[_point][cur-1] = Claim(_protocol, _claim, _dossier);
}
emit ClaimAdded(_point, _protocol, _claim, _dossier);
}
// removeClaim(): unregister a claim as _point
//
function removeClaim(uint32 _point, string _protocol, string _claim)
external
activePointManager(_point)
{
// i: current index + 1 in _point's list of claims
//
uint256 i = findClaim(_point, _protocol, _claim);
// we store index + 1, because 0 is the eth default value
// can only delete an existing claim
//
require(i > 0);
i--;
// clear out the claim
//
delete claims[_point][i];
emit ClaimRemoved(_point, _protocol, _claim);
}
// clearClaims(): unregister all of _point's claims
//
// can also be called by the ecliptic during point transfer
//
function clearClaims(uint32 _point)
external
{
// both point owner and ecliptic may do this
//
// We do not necessarily need to check for _point's active flag here,
// since inactive points cannot have claims set. Doing the check
// anyway would make this function slightly harder to think about due
// to its relation to Ecliptic's transferPoint().
//
require( azimuth.canManage(_point, msg.sender) ||
( msg.sender == azimuth.owner() ) );
Claim[maxClaims] storage currClaims = claims[_point];
// clear out all claims
//
for (uint8 i = 0; i < maxClaims; i++)
{
// only emit the removed event if there was a claim here
//
if ( 0 < bytes(currClaims[i].claim).length )
{
emit ClaimRemoved(_point, currClaims[i].protocol, currClaims[i].claim);
}
delete currClaims[i];
}
}
// findClaim(): find the index of the specified claim
//
// returns 0 if not found, index + 1 otherwise
//
function findClaim(uint32 _whose, string _protocol, string _claim)
public
view
returns (uint8 index)
{
// we use hashes of the string because solidity can't do string
// comparison yet
//
bytes32 protocolHash = keccak256(bytes(_protocol));
bytes32 claimHash = keccak256(bytes(_claim));
Claim[maxClaims] storage theirClaims = claims[_whose];
for (uint8 i = 0; i < maxClaims; i++)
{
Claim storage thisClaim = theirClaims[i];
if ( ( protocolHash == keccak256(bytes(thisClaim.protocol)) ) &&
( claimHash == keccak256(bytes(thisClaim.claim)) ) )
{
return i+1;
}
}
return 0;
}
// findEmptySlot(): find the index of the first empty claim slot
//
// returns the index of the slot, throws if there are no empty slots
//
function findEmptySlot(uint32 _whose)
internal
view
returns (uint8 index)
{
Claim[maxClaims] storage theirClaims = claims[_whose];
for (uint8 i = 0; i < maxClaims; i++)
{
Claim storage thisClaim = theirClaims[i];
if ( (0 == bytes(thisClaim.claim).length) )
{
return i;
}
}
revert();
}
}
// Treasury's ITreasuryProxy
interface ITreasuryProxy {
function upgradeTo(address _impl) external returns (bool);
function freeze() external returns (bool);
}
// Azimuth's EclipticBase.sol
// EclipticBase: upgradable ecliptic
//
// This contract implements the upgrade logic for the Ecliptic.
// Newer versions of the Ecliptic are expected to provide at least
// the onUpgrade() function. If they don't, upgrading to them will
// fail.
//
// Note that even though this contract doesn't specify any required
// interface members aside from upgrade() and onUpgrade(), contracts
// and clients may still rely on the presence of certain functions
// provided by the Ecliptic proper. Keep this in mind when writing
// new versions of it.
//
contract EclipticBase is Ownable, ReadsAzimuth
{
// Upgraded: _to is the new canonical Ecliptic
//
event Upgraded(address to);
// polls: senate voting contract
//
Polls public polls;
// previousEcliptic: address of the previous ecliptic this
// instance expects to upgrade from, stored and
// checked for to prevent unexpected upgrade paths
//
address public previousEcliptic;
constructor( address _previous,
Azimuth _azimuth,
Polls _polls )
ReadsAzimuth(_azimuth)
internal
{
previousEcliptic = _previous;
polls = _polls;
}
// onUpgrade(): called by previous ecliptic when upgrading
//
// in future ecliptics, this might perform more logic than
// just simple checks and verifications.
// when overriding this, make sure to call this original as well.
//
function onUpgrade()
external
{
// make sure this is the expected upgrade path,
// and that we have gotten the ownership we require
//
require( msg.sender == previousEcliptic &&
this == azimuth.owner() &&
this == polls.owner() );
}
// upgrade(): transfer ownership of the ecliptic data to the new
// ecliptic contract, notify it, then self-destruct.
//
// Note: any eth that have somehow ended up in this contract
// are also sent to the new ecliptic.
//
function upgrade(EclipticBase _new)
internal
{
// transfer ownership of the data contracts
//
azimuth.transferOwnership(_new);
polls.transferOwnership(_new);
// trigger upgrade logic on the target contract
//
_new.onUpgrade();
// emit event and destroy this contract
//
emit Upgraded(_new);
selfdestruct(_new);
}
}
////////////////////////////////////////////////////////////////////////////////
// Ecliptic
////////////////////////////////////////////////////////////////////////////////
// Ecliptic: logic for interacting with the Azimuth ledger
//
// This contract is the point of entry for all operations on the Azimuth
// ledger as stored in the Azimuth data contract. The functions herein
// are responsible for performing all necessary business logic.
// Examples of such logic include verifying permissions of the caller
// and ensuring a requested change is actually valid.
// Point owners can always operate on their own points. Ethereum addresses
// can also perform specific operations if they've been given the
// appropriate permissions. (For example, managers for general management,
// spawn proxies for spawning child points, etc.)
//
// This contract uses external contracts (Azimuth, Polls) for data storage
// so that it itself can easily be replaced in case its logic needs to
// be changed. In other words, it can be upgraded. It does this by passing
// ownership of the data contracts to a new Ecliptic contract.
//
// Because of this, it is advised for clients to not store this contract's
// address directly, but rather ask the Azimuth contract for its owner
// attribute to ensure transactions get sent to the latest Ecliptic.
// Alternatively, the ENS name ecliptic.eth will resolve to the latest
// Ecliptic as well.
//
// Upgrading happens based on polls held by the senate (galaxy owners).
// Through this contract, the senate can submit proposals, opening polls
// for the senate to cast votes on. These proposals can be either hashes
// of documents or addresses of new Ecliptics.
// If an ecliptic proposal gains majority, this contract will transfer
// ownership of the data storage contracts to that address, so that it may
// operate on the data they contain. This contract will selfdestruct at
// the end of the upgrade process.
//
// This contract implements the ERC721 interface for non-fungible tokens,
// allowing points to be managed using generic clients that support the
// standard. It also implements ERC165 to allow this to be discovered.
//
contract Ecliptic is EclipticBase, SupportsInterfaceWithLookup, ERC721Metadata
{
using SafeMath for uint256;
using AddressUtils for address;
// Transfer: This emits when ownership of any NFT changes by any mechanism.
// This event emits when NFTs are created (`from` == 0) and
// destroyed (`to` == 0). At the time of any transfer, the
// approved address for that NFT (if any) is reset to none.
//
event Transfer(address indexed _from, address indexed _to,
uint256 indexed _tokenId);
// Approval: This emits when the approved address for an NFT is changed or
// reaffirmed. The zero address indicates there is no approved
// address. When a Transfer event emits, this also indicates that
// the approved address for that NFT (if any) is reset to none.
//
event Approval(address indexed _owner, address indexed _approved,
uint256 indexed _tokenId);
// ApprovalForAll: This emits when an operator is enabled or disabled for an
// owner. The operator can manage all NFTs of the owner.
//
event ApprovalForAll(address indexed _owner, address indexed _operator,
bool _approved);
// erc721Received: equal to:
// bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))
// which can be also obtained as:
// ERC721Receiver(0).onERC721Received.selector`
bytes4 constant erc721Received = 0x150b7a02;
// depositAddress: Special address respresenting L2. Ships sent to
// this address are controlled on L2 instead of here.
//
address constant public depositAddress =
0x1111111111111111111111111111111111111111;
ITreasuryProxy public treasuryProxy;
// treasuryUpgradeHash
// hash of the treasury implementation to upgrade to
// Note: stand-in, just hash of no bytes
// could be made immutable and passed in as constructor argument
bytes32 constant public treasuryUpgradeHash = hex"26f3eae628fa1a4d23e34b91a4d412526a47620ced37c80928906f9fa07c0774";
bool public treasuryUpgraded = false;
// claims: contract reference, for clearing claims on-transfer
//
Claims public claims;
// constructor(): set data contract addresses and signal interface support
//
// Note: during first deploy, ownership of these data contracts must
// be manually transferred to this contract.
//
constructor(address _previous,
Azimuth _azimuth,
Polls _polls,
Claims _claims,
ITreasuryProxy _treasuryProxy)
EclipticBase(_previous, _azimuth, _polls)
public
{
claims = _claims;
treasuryProxy = _treasuryProxy;
// register supported interfaces for ERC165
//
_registerInterface(0x80ac58cd); // ERC721
_registerInterface(0x5b5e139f); // ERC721Metadata
_registerInterface(0x7f5828d0); // ERC173 (ownership)
}
//
// ERC721 interface
//
// balanceOf(): get the amount of points owned by _owner
//
function balanceOf(address _owner)
public
view
returns (uint256 balance)
{
require(0x0 != _owner);
return azimuth.getOwnedPointCount(_owner);
}
// ownerOf(): get the current owner of point _tokenId
//
function ownerOf(uint256 _tokenId)
public
view
validPointId(_tokenId)
returns (address owner)
{
uint32 id = uint32(_tokenId);
// this will throw if the owner is the zero address,
// active points always have a valid owner.
//
require(azimuth.isActive(id));
return azimuth.getOwner(id);
}
// exists(): returns true if point _tokenId is active
//
function exists(uint256 _tokenId)
public
view
returns (bool doesExist)
{
return ( (_tokenId < 0x100000000) &&
azimuth.isActive(uint32(_tokenId)) );
}
// safeTransferFrom(): transfer point _tokenId from _from to _to
//
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
public
{
// transfer with empty data
//
safeTransferFrom(_from, _to, _tokenId, "");
}
// safeTransferFrom(): transfer point _tokenId from _from to _to,
// and call recipient if it's a contract
//
function safeTransferFrom(address _from, address _to, uint256 _tokenId,
bytes _data)
public
{
// perform raw transfer
//
transferFrom(_from, _to, _tokenId);
// do the callback last to avoid re-entrancy
//
if (_to.isContract())
{
bytes4 retval = ERC721Receiver(_to)
.onERC721Received(msg.sender, _from, _tokenId, _data);
//
// standard return idiom to confirm contract semantics
//
require(retval == erc721Received);
}
}
// transferFrom(): transfer point _tokenId from _from to _to,
// WITHOUT notifying recipient contract
//
function transferFrom(address _from, address _to, uint256 _tokenId)
public
validPointId(_tokenId)
{
uint32 id = uint32(_tokenId);
require(azimuth.isOwner(id, _from));
// the ERC721 operator/approved address (if any) is
// accounted for in transferPoint()
//
transferPoint(id, _to, true);
}
// approve(): allow _approved to transfer ownership of point
// _tokenId
//
function approve(address _approved, uint256 _tokenId)
public
validPointId(_tokenId)
{
setTransferProxy(uint32(_tokenId), _approved);
}
// setApprovalForAll(): allow or disallow _operator to
// transfer ownership of ALL points
// owned by :msg.sender
//
function setApprovalForAll(address _operator, bool _approved)
public
{
require(0x0 != _operator);
azimuth.setOperator(msg.sender, _operator, _approved);
emit ApprovalForAll(msg.sender, _operator, _approved);
}
// getApproved(): get the approved address for point _tokenId
//
function getApproved(uint256 _tokenId)
public
view
validPointId(_tokenId)
returns (address approved)
{
//NOTE redundant, transfer proxy cannot be set for
// inactive points
//
require(azimuth.isActive(uint32(_tokenId)));
return azimuth.getTransferProxy(uint32(_tokenId));
}
// isApprovedForAll(): returns true if _operator is an
// operator for _owner
//
function isApprovedForAll(address _owner, address _operator)
public
view
returns (bool result)
{
return azimuth.isOperator(_owner, _operator);
}
//
// ERC721Metadata interface
//
// name(): returns the name of a collection of points
//
function name()
external
view
returns (string)
{
return "Azimuth Points";
}
// symbol(): returns an abbreviates name for points
//
function symbol()
external
view
returns (string)
{
return "AZP";
}
// tokenURI(): returns a URL to an ERC-721 standard JSON file
//
function tokenURI(uint256 _tokenId)
public
view
validPointId(_tokenId)
returns (string _tokenURI)
{
_tokenURI = "https://azimuth.network/erc721/0000000000.json";
bytes memory _tokenURIBytes = bytes(_tokenURI);
_tokenURIBytes[31] = byte(48+(_tokenId / 1000000000) % 10);
_tokenURIBytes[32] = byte(48+(_tokenId / 100000000) % 10);
_tokenURIBytes[33] = byte(48+(_tokenId / 10000000) % 10);
_tokenURIBytes[34] = byte(48+(_tokenId / 1000000) % 10);
_tokenURIBytes[35] = byte(48+(_tokenId / 100000) % 10);
_tokenURIBytes[36] = byte(48+(_tokenId / 10000) % 10);
_tokenURIBytes[37] = byte(48+(_tokenId / 1000) % 10);
_tokenURIBytes[38] = byte(48+(_tokenId / 100) % 10);
_tokenURIBytes[39] = byte(48+(_tokenId / 10) % 10);
_tokenURIBytes[40] = byte(48+(_tokenId / 1) % 10);
}
//
// Points interface
//
// configureKeys(): configure _point with network public keys
// _encryptionKey, _authenticationKey,
// and corresponding _cryptoSuiteVersion,
// incrementing the point's continuity number if needed
//
function configureKeys(uint32 _point,
bytes32 _encryptionKey,
bytes32 _authenticationKey,
uint32 _cryptoSuiteVersion,
bool _discontinuous)
external
activePointManager(_point)
onL1(_point)
{
if (_discontinuous)
{
azimuth.incrementContinuityNumber(_point);
}
azimuth.setKeys(_point,
_encryptionKey,
_authenticationKey,
_cryptoSuiteVersion);
}
// spawn(): spawn _point, then either give, or allow _target to take,
// ownership of _point
//
// if _target is the :msg.sender, _targets owns the _point right away.
// otherwise, _target becomes the transfer proxy of _point.
//
// Requirements:
// - _point must not be active
// - _point must not be a planet with a galaxy prefix
// - _point's prefix must be linked and under its spawn limit
// - :msg.sender must be either the owner of _point's prefix,
// or an authorized spawn proxy for it
//
function spawn(uint32 _point, address _target)
external
{
// only currently unowned (and thus also inactive) points can be spawned
//
require(azimuth.isOwner(_point, 0x0));
// prefix: half-width prefix of _point
//
uint16 prefix = azimuth.getPrefix(_point);
// can't spawn if we deposited ownership or spawn rights to L2
//
require( depositAddress != azimuth.getOwner(prefix) );
require( depositAddress != azimuth.getSpawnProxy(prefix) );
// only allow spawning of points of the size directly below the prefix
//
// this is possible because of how the address space works,
// but supporting it introduces complexity through broken assumptions.
//
// example:
// 0x0000.0000 - galaxy zero
// 0x0000.0100 - the first star of galaxy zero
// 0x0001.0100 - the first planet of the first star
// 0x0001.0000 - the first planet of galaxy zero
//
require( (uint8(azimuth.getPointSize(prefix)) + 1) ==
uint8(azimuth.getPointSize(_point)) );
// prefix point must be linked and able to spawn
//
require( (azimuth.hasBeenLinked(prefix)) &&
( azimuth.getSpawnCount(prefix) <
getSpawnLimit(prefix, block.timestamp) ) );
// the owner of a prefix can always spawn its children;
// other addresses need explicit permission (the role
// of "spawnProxy" in the Azimuth contract)
//
require( azimuth.canSpawnAs(prefix, msg.sender) );
// if the caller is spawning the point to themselves,
// assume it knows what it's doing and resolve right away
//
if (msg.sender == _target)
{
doSpawn(_point, _target, true, 0x0);
}
//
// when sending to a "foreign" address, enforce a withdraw pattern
// making the _point prefix's owner the _point owner in the mean time
//
else
{
doSpawn(_point, _target, false, azimuth.getOwner(prefix));
}
}
// doSpawn(): actual spawning logic, used in spawn(). creates _point,
// making the _target its owner if _direct, or making the
// _holder the owner and the _target the transfer proxy
// if not _direct.
//
function doSpawn( uint32 _point,
address _target,
bool _direct,
address _holder )
internal
{
// register the spawn for _point's prefix, incrementing spawn count
//
azimuth.registerSpawned(_point);
// if the spawn is _direct, assume _target knows what they're doing
// and resolve right away
//
if (_direct)
{
// make the point active and set its new owner
//
azimuth.activatePoint(_point);
azimuth.setOwner(_point, _target);
emit Transfer(0x0, _target, uint256(_point));
}
//
// when spawning indirectly, enforce a withdraw pattern by approving
// the _target for transfer of the _point instead.
// we make the _holder the owner of this _point in the mean time,
// so that it may cancel the transfer (un-approve) if _target flakes.
// we don't make _point active yet, because it still doesn't really
// belong to anyone.
//
else
{
// have _holder hold on to the _point while _target gets to transfer
// ownership of it
//
azimuth.setOwner(_point, _holder);
azimuth.setTransferProxy(_point, _target);
emit Transfer(0x0, _holder, uint256(_point));
emit Approval(_holder, _target, uint256(_point));
}
}
// transferPoint(): transfer _point to _target, clearing all permissions
// data and keys if _reset is true
//
// Note: the _reset flag is useful when transferring the point to
// a recipient who doesn't trust the previous owner.
//
// We know _point is not on L2, since otherwise its owner would be
// depositAddress (which has no operator) and its transfer proxy
// would be zero.
//
// Requirements:
// - :msg.sender must be either _point's current owner, authorized
// to transfer _point, or authorized to transfer the current
// owner's points (as in ERC721's operator)
// - _target must not be the zero address
//
function transferPoint(uint32 _point, address _target, bool _reset)
public
{
// transfer is legitimate if the caller is the current owner, or
// an operator for the current owner, or the _point's transfer proxy
//
require(azimuth.canTransfer(_point, msg.sender));
// can't deposit galaxy to L2
// can't deposit contract-owned point to L2
//
require( depositAddress != _target ||
( azimuth.getPointSize(_point) != Azimuth.Size.Galaxy &&
!azimuth.getOwner(_point).isContract() ) );
// if the point wasn't active yet, that means transferring it
// is part of the "spawn" flow, so we need to activate it
//
if ( !azimuth.isActive(_point) )
{
azimuth.activatePoint(_point);
}
// if the owner would actually change, change it
//
// the only time this deliberately wouldn't be the case is when a
// prefix owner wants to activate a spawned but untransferred child.
//
if ( !azimuth.isOwner(_point, _target) )
{
// remember the previous owner, to be included in the Transfer event
//
address old = azimuth.getOwner(_point);
azimuth.setOwner(_point, _target);
// according to ERC721, the approved address (here, transfer proxy)
// gets cleared during every Transfer event
//
// we also rely on this so that transfer-related functions don't need
// to verify the point is on L1
//
azimuth.setTransferProxy(_point, 0);
emit Transfer(old, _target, uint256(_point));
}
// if we're depositing to L2, clear L1 data so that no proxies
// can be used
//
if ( depositAddress == _target )
{
azimuth.setKeys(_point, 0, 0, 0);
azimuth.setManagementProxy(_point, 0);
azimuth.setVotingProxy(_point, 0);
azimuth.setTransferProxy(_point, 0);
azimuth.setSpawnProxy(_point, 0);
claims.clearClaims(_point);
azimuth.cancelEscape(_point);
}
// reset sensitive data
// used when transferring the point to a new owner
//
else if ( _reset )
{
// clear the network public keys and break continuity,
// but only if the point has already been linked
//
if ( azimuth.hasBeenLinked(_point) )
{
azimuth.incrementContinuityNumber(_point);
azimuth.setKeys(_point, 0, 0, 0);
}
// clear management proxy
//
azimuth.setManagementProxy(_point, 0);
// clear voting proxy
//
azimuth.setVotingProxy(_point, 0);
// clear transfer proxy
//
// in most cases this is done above, during the ownership transfer,
// but we might not hit that and still be expected to reset the
// transfer proxy.
// doing it a second time is a no-op in Azimuth.
//
azimuth.setTransferProxy(_point, 0);
// clear spawning proxy
//
// don't clear if the spawn rights have been deposited to L2,
//
if ( depositAddress != azimuth.getSpawnProxy(_point) )
{
azimuth.setSpawnProxy(_point, 0);
}
// clear claims
//
claims.clearClaims(_point);
}
}
// escape(): request escape as _point to _sponsor
//
// if an escape request is already active, this overwrites
// the existing request
//
// Requirements:
// - :msg.sender must be the owner or manager of _point,
// - _point must be able to escape to _sponsor as per to canEscapeTo()
//
function escape(uint32 _point, uint32 _sponsor)
external
activePointManager(_point)
onL1(_point)
{
// if the sponsor is on L2, we need to escape using L2
//
require( depositAddress != azimuth.getOwner(_sponsor) );
require(canEscapeTo(_point, _sponsor));
azimuth.setEscapeRequest(_point, _sponsor);
}
// cancelEscape(): cancel the currently set escape for _point
//
function cancelEscape(uint32 _point)
external
activePointManager(_point)
{
azimuth.cancelEscape(_point);
}
// adopt(): as the relevant sponsor, accept the _point
//
// Requirements:
// - :msg.sender must be the owner or management proxy
// of _point's requested sponsor
//
function adopt(uint32 _point)
external
onL1(_point)
{
uint32 request = azimuth.getEscapeRequest(_point);
require( azimuth.isEscaping(_point) &&
azimuth.canManage( request, msg.sender ) );
require( depositAddress != azimuth.getOwner(request) );
// _sponsor becomes _point's sponsor
// its escape request is reset to "not escaping"
//
azimuth.doEscape(_point);
}
// reject(): as the relevant sponsor, deny the _point's request
//
// Requirements:
// - :msg.sender must be the owner or management proxy
// of _point's requested sponsor
//
function reject(uint32 _point)
external
{
uint32 request = azimuth.getEscapeRequest(_point);
require( azimuth.isEscaping(_point) &&
azimuth.canManage( request, msg.sender ) );
require( depositAddress != azimuth.getOwner(request) );
// reset the _point's escape request to "not escaping"
//
azimuth.cancelEscape(_point);
}
// detach(): as the _sponsor, stop sponsoring the _point
//
// Requirements:
// - :msg.sender must be the owner or management proxy
// of _point's current sponsor
//
// We allow detachment even of points that are on L2. This is
// so that a star controlled by a contract can detach from a
// planet which was on L1 originally but now is on L2. L2 will
// ignore this if this is not the actual sponsor anymore (i.e. if
// they later changed their sponsor on L2).
//
function detach(uint32 _point)
external
{
uint32 sponsor = azimuth.getSponsor(_point);
require( azimuth.hasSponsor(_point) &&
azimuth.canManage(sponsor, msg.sender) );
require( depositAddress != azimuth.getOwner(sponsor) );
// signal that its sponsor no longer supports _point
//
azimuth.loseSponsor(_point);
}
//
// Point rules
//
// getSpawnLimit(): returns the total number of children the _point
// is allowed to spawn at _time.
//
function getSpawnLimit(uint32 _point, uint256 _time)
public
view
returns (uint32 limit)
{
Azimuth.Size size = azimuth.getPointSize(_point);
if ( size == Azimuth.Size.Galaxy )
{
return 255;
}
else if ( size == Azimuth.Size.Star )
{
// in 2019, stars may spawn at most 1024 planets. this limit doubles
// for every subsequent year.
//
// Note: 1546300800 corresponds to 2019-01-01
//
uint256 yearsSince2019 = (_time - 1546300800) / 365 days;
if (yearsSince2019 < 6)
{
limit = uint32( 1024 * (2 ** yearsSince2019) );
}
else
{
limit = 65535;
}
return limit;
}
else // size == Azimuth.Size.Planet
{
// planets can create moons, but moons aren't on the chain
//
return 0;
}
}
// canEscapeTo(): true if _point could try to escape to _sponsor
//
function canEscapeTo(uint32 _point, uint32 _sponsor)
public
view
returns (bool canEscape)
{
// can't escape to a sponsor that hasn't been linked
//
if ( !azimuth.hasBeenLinked(_sponsor) ) return false;
// Can only escape to a point one size higher than ourselves,
// except in the special case where the escaping point hasn't
// been linked yet -- in that case we may escape to points of
// the same size, to support lightweight invitation chains.
//
// The use case for lightweight invitations is that a planet
// owner should be able to invite their friends onto an
// Azimuth network in a two-party transaction, without a new
// star relationship.
// The lightweight invitation process works by escaping your
// own active (but never linked) point to one of your own
// points, then transferring the point to your friend.
//
// These planets can, in turn, sponsor other unlinked planets,
// so the "planet sponsorship chain" can grow to arbitrary
// length. Most users, especially deep down the chain, will
// want to improve their performance by switching to direct
// star sponsors eventually.
//
Azimuth.Size pointSize = azimuth.getPointSize(_point);
Azimuth.Size sponsorSize = azimuth.getPointSize(_sponsor);
return ( // normal hierarchical escape structure
//
( (uint8(sponsorSize) + 1) == uint8(pointSize) ) ||
//
// special peer escape
//
( (sponsorSize == pointSize) &&
//
// peer escape is only for points that haven't been linked
// yet, because it's only for lightweight invitation chains
//
!azimuth.hasBeenLinked(_point) ) );
}
//
// Permission management
//
// setManagementProxy(): configure the management proxy for _point
//
// The management proxy may perform "reversible" operations on
// behalf of the owner. This includes public key configuration and
// operations relating to sponsorship.
//
function setManagementProxy(uint32 _point, address _manager)
external
activePointManager(_point)
onL1(_point)
{
azimuth.setManagementProxy(_point, _manager);
}
// setSpawnProxy(): give _spawnProxy the right to spawn points
// with the prefix _prefix
//
// takes a uint16 so that we can't set spawn proxy for a planet
//
// fails if spawn rights have been deposited to L2
//
function setSpawnProxy(uint16 _prefix, address _spawnProxy)
external
activePointSpawner(_prefix)
onL1(_prefix)
{
require( depositAddress != azimuth.getSpawnProxy(_prefix) );
azimuth.setSpawnProxy(_prefix, _spawnProxy);
}
// setVotingProxy(): configure the voting proxy for _galaxy
//
// the voting proxy is allowed to start polls and cast votes
// on the point's behalf.
//
function setVotingProxy(uint8 _galaxy, address _voter)
external
activePointVoter(_galaxy)
{
azimuth.setVotingProxy(_galaxy, _voter);
}
// setTransferProxy(): give _transferProxy the right to transfer _point
//
// Requirements:
// - :msg.sender must be either _point's current owner,
// or be an operator for the current owner
//
function setTransferProxy(uint32 _point, address _transferProxy)
public
onL1(_point)
{
// owner: owner of _point
//
address owner = azimuth.getOwner(_point);
// caller must be :owner, or an operator designated by the owner.
//
require((owner == msg.sender) || azimuth.isOperator(owner, msg.sender));
// set transfer proxy field in Azimuth contract
//
azimuth.setTransferProxy(_point, _transferProxy);
// emit Approval event
//
emit Approval(owner, _transferProxy, uint256(_point));
}
//
// Poll actions
//
// startUpgradePoll(): as _galaxy, start a poll for the ecliptic
// upgrade _proposal
//
// Requirements:
// - :msg.sender must be the owner or voting proxy of _galaxy,
// - the _proposal must expect to be upgraded from this specific
// contract, as indicated by its previousEcliptic attribute
//
function startUpgradePoll(uint8 _galaxy, EclipticBase _proposal)
external
activePointVoter(_galaxy)
{
// ensure that the upgrade target expects this contract as the source
//
require(_proposal.previousEcliptic() == address(this));
polls.startUpgradePoll(_proposal);
}
// startDocumentPoll(): as _galaxy, start a poll for the _proposal
//
// the _proposal argument is the keccak-256 hash of any arbitrary
// document or string of text
//
function startDocumentPoll(uint8 _galaxy, bytes32 _proposal)
external
activePointVoter(_galaxy)
{
polls.startDocumentPoll(_proposal);
}
// castUpgradeVote(): as _galaxy, cast a _vote on the ecliptic
// upgrade _proposal
//
// _vote is true when in favor of the proposal, false otherwise
//
// If this vote results in a majority for the _proposal, it will
// be upgraded to immediately.
//
function castUpgradeVote(uint8 _galaxy,
EclipticBase _proposal,
bool _vote)
external
activePointVoter(_galaxy)
{
// majority: true if the vote resulted in a majority, false otherwise
//
bool majority = polls.castUpgradeVote(_galaxy, _proposal, _vote);
// if a majority is in favor of the upgrade, it happens as defined
// in the ecliptic base contract
//
if (majority)
{
upgrade(_proposal);
}
}
// castDocumentVote(): as _galaxy, cast a _vote on the _proposal
//
// _vote is true when in favor of the proposal, false otherwise
//
function castDocumentVote(uint8 _galaxy, bytes32 _proposal, bool _vote)
external
activePointVoter(_galaxy)
{
polls.castDocumentVote(_galaxy, _proposal, _vote);
}
// updateUpgradePoll(): check whether the _proposal has achieved
// majority, upgrading to it if it has
//
function updateUpgradePoll(EclipticBase _proposal)
external
{
// majority: true if the poll ended in a majority, false otherwise
//
bool majority = polls.updateUpgradePoll(_proposal);
// if a majority is in favor of the upgrade, it happens as defined
// in the ecliptic base contract
//
if (majority)
{
upgrade(_proposal);
}
}
// updateDocumentPoll(): check whether the _proposal has achieved majority
//
// Note: the polls contract publicly exposes the function this calls,
// but we offer it in the ecliptic interface as a convenience
//
function updateDocumentPoll(bytes32 _proposal)
external
{
polls.updateDocumentPoll(_proposal);
}
// upgradeTreasury: upgrade implementation for treasury
//
// Note: we specify when deploying Ecliptic the keccak hash
// of the implementation we're upgrading to
//
function upgradeTreasury(address _treasuryImpl) external {
require(!treasuryUpgraded);
require(keccak256(_treasuryImpl) == treasuryUpgradeHash);
treasuryProxy.upgradeTo(_treasuryImpl);
treasuryUpgraded = true;
}
//
// Contract owner operations
//
// createGalaxy(): grant _target ownership of the _galaxy and register
// it for voting
//
function createGalaxy(uint8 _galaxy, address _target)
external
onlyOwner
{
// only currently unowned (and thus also inactive) galaxies can be
// created, and only to non-zero addresses
//
require( azimuth.isOwner(_galaxy, 0x0) &&
0x0 != _target );
// new galaxy means a new registered voter
//
polls.incrementTotalVoters();
// if the caller is sending the galaxy to themselves,
// assume it knows what it's doing and resolve right away
//
if (msg.sender == _target)
{
doSpawn(_galaxy, _target, true, 0x0);
}
//
// when sending to a "foreign" address, enforce a withdraw pattern,
// making the caller the owner in the mean time
//
else
{
doSpawn(_galaxy, _target, false, msg.sender);
}
}
function setDnsDomains(string _primary, string _secondary, string _tertiary)
external
onlyOwner
{
azimuth.setDnsDomains(_primary, _secondary, _tertiary);
}
//
// Function modifiers for this contract
//
// validPointId(): require that _id is a valid point
//
modifier validPointId(uint256 _id)
{
require(_id < 0x100000000);
_;
}
// onL1(): require that ship is not deposited
modifier onL1(uint32 _point)
{
require( depositAddress != azimuth.getOwner(_point) );
_;
}
} | setManagementProxy(): configure the management proxy for _point The management proxy may perform "reversible" operations on behalf of the owner. This includes public key configuration and operations relating to sponsorship. | function setManagementProxy(uint32 _point, address _manager)
external
activePointManager(_point)
onL1(_point)
{
azimuth.setManagementProxy(_point, _manager);
}
| 1,053,764 |
./full_match/42220/0xf1ddeC2478f932Df6f78CdF261154B79cC740Fe0/sources/libs/SignedSafeMath.sol | Returns the addition of two signed integers, reverting on overflow. 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;
}
| 16,336,685 |
./full_match/3/0x0651Ab69495f79d78a473e170248C839Efa137dC/sources/MasterChef.sol | Withdraw LP tokens from MasterChef. | function withdraw(uint256 _pid, uint256 _amount) public {
require (_pid != 0, 'withdraw JJAMPPONG by unstaking');
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accJjamPpongPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeJjamPpongTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accJjamPpongPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
| 8,119,668 |
pragma solidity ^0.4.24;
/*
* gibmireinbier
* 0xA4a799086aE18D7db6C4b57f496B081b44888888
* [email protected]
*/
interface F2mInterface {
function joinNetwork(address[6] _contract) public;
// one time called
function disableRound0() public;
function activeBuy() public;
// Dividends from all sources (DApps, Donate ...)
function pushDividends() public payable;
/**
* Converts all of caller's dividends to tokens.
*/
//function reinvest() public;
//function buy() public payable;
function buyFor(address _buyer) public payable;
function sell(uint256 _tokenAmount) public;
function exit() public;
function devTeamWithdraw() public returns(uint256);
function withdrawFor(address sender) public returns(uint256);
function transfer(address _to, uint256 _tokenAmount) public returns(bool);
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
function setAutoBuy() public;
/*==========================================
= public FUNCTIONS =
==========================================*/
// function totalEthBalance() public view returns(uint256);
function ethBalance(address _address) public view returns(uint256);
function myBalance() public view returns(uint256);
function myEthBalance() public view returns(uint256);
function swapToken() public;
function setNewToken(address _newTokenAddress) public;
}
interface CitizenInterface {
function joinNetwork(address[6] _contract) public;
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
function devTeamWithdraw() public;
/*---------- WRITE FUNCTIONS ----------*/
function updateUsername(string _sNewUsername) public;
//Sources: Token contract, DApps
function pushRefIncome(address _sender) public payable;
function withdrawFor(address _sender) public payable returns(uint256);
function devTeamReinvest() public returns(uint256);
/*---------- READ FUNCTIONS ----------*/
function getRefWallet(address _address) public view returns(uint256);
}
interface DevTeamInterface {
function setF2mAddress(address _address) public;
function setLotteryAddress(address _address) public;
function setCitizenAddress(address _address) public;
function setBankAddress(address _address) public;
function setRewardAddress(address _address) public;
function setWhitelistAddress(address _address) public;
function setupNetwork() public;
}
interface BankInterface {
function joinNetwork(address[6] _contract) public;
// Core functions
function pushToBank(address _player) public payable;
}
interface RewardInterface {
function mintReward(
address _lucker,
uint256 curRoundId,
uint256 _tNumberFrom,
uint256 _tNumberTo,
uint256 _value,
uint256 _rewardType)
public;
function joinNetwork(address[6] _contract) public;
function pushBounty(uint256 _curRoundId) public payable;
}
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
int256 constant private INT256_MIN = -2**255;
/**
* @dev Multiplies two unsigned integers, reverts on 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-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// 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-solidity/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below
int256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0); // Solidity only automatically asserts when dividing by 0
require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow
int256 c = a / b;
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Subtracts two signed integers, reverts on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Adds two signed integers, reverts on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
library Helper {
using SafeMath for uint256;
uint256 constant public ZOOM = 1000;
uint256 constant public SDIVIDER = 3450000;
uint256 constant public PDIVIDER = 3450000;
uint256 constant public RDIVIDER = 1580000;
// Starting LS price (SLP)
uint256 constant public SLP = 0.002 ether;
// Starting Added Time (SAT)
uint256 constant public SAT = 30; // seconds
// Price normalization (PN)
uint256 constant public PN = 777;
// EarlyIncome base
uint256 constant public PBASE = 13;
uint256 constant public PMULTI = 26;
uint256 constant public LBase = 15;
uint256 constant public ONE_HOUR = 3600;
uint256 constant public ONE_DAY = 24 * ONE_HOUR;
//uint256 constant public TIMEOUT0 = 3 * ONE_HOUR;
uint256 constant public TIMEOUT1 = 12 * ONE_HOUR;
function bytes32ToString (bytes32 data)
public
pure
returns (string)
{
bytes memory bytesString = new bytes(32);
for (uint j=0; j<32; j++) {
byte char = byte(bytes32(uint(data) * 2 ** (8 * j)));
if (char != 0) {
bytesString[j] = char;
}
}
return string(bytesString);
}
function uintToBytes32(uint256 n)
public
pure
returns (bytes32)
{
return bytes32(n);
}
function bytes32ToUint(bytes32 n)
public
pure
returns (uint256)
{
return uint256(n);
}
function stringToBytes32(string memory source)
public
pure
returns (bytes32 result)
{
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
function stringToUint(string memory source)
public
pure
returns (uint256)
{
return bytes32ToUint(stringToBytes32(source));
}
function uintToString(uint256 _uint)
public
pure
returns (string)
{
return bytes32ToString(uintToBytes32(_uint));
}
/*
function getSlice(uint256 begin, uint256 end, string text) public pure returns (string) {
bytes memory a = new bytes(end-begin+1);
for(uint i = 0; i <= end - begin; i++){
a[i] = bytes(text)[i + begin - 1];
}
return string(a);
}
*/
function validUsername(string _username)
public
pure
returns(bool)
{
uint256 len = bytes(_username).length;
// Im Raum [4, 18]
if ((len < 4) || (len > 18)) return false;
// Letzte Char != ' '
if (bytes(_username)[len-1] == 32) return false;
// Erste Char != '0'
return uint256(bytes(_username)[0]) != 48;
}
// Lottery Helper
// Seconds added per LT = SAT - ((Current no. of LT + 1) / SDIVIDER)^6
function getAddedTime(uint256 _rTicketSum, uint256 _tAmount)
public
pure
returns (uint256)
{
//Luppe = 10000 = 10^4
uint256 base = (_rTicketSum + 1).mul(10000) / SDIVIDER;
uint256 expo = base;
expo = expo.mul(expo).mul(expo); // ^3
expo = expo.mul(expo); // ^6
// div 10000^6
expo = expo / (10**24);
if (expo > SAT) return 0;
return (SAT - expo).mul(_tAmount);
}
function getNewEndTime(uint256 toAddTime, uint256 slideEndTime, uint256 fixedEndTime)
public
view
returns(uint256)
{
uint256 _slideEndTime = (slideEndTime).add(toAddTime);
uint256 timeout = _slideEndTime.sub(block.timestamp);
// timeout capped at TIMEOUT1
if (timeout > TIMEOUT1) timeout = TIMEOUT1;
_slideEndTime = (block.timestamp).add(timeout);
// Capped at fixedEndTime
if (_slideEndTime > fixedEndTime) return fixedEndTime;
return _slideEndTime;
}
// get random in range [1, _range] with _seed
function getRandom(uint256 _seed, uint256 _range)
public
pure
returns(uint256)
{
if (_range == 0) return _seed;
return (_seed % _range) + 1;
}
function getEarlyIncomeMul(uint256 _ticketSum)
public
pure
returns(uint256)
{
// Early-Multiplier = 1 + PBASE / (1 + PMULTI * ((Current No. of LT)/RDIVIDER)^6)
uint256 base = _ticketSum * ZOOM / RDIVIDER;
uint256 expo = base.mul(base).mul(base); //^3
expo = expo.mul(expo) / (ZOOM**6); //^6
return (1 + PBASE / (1 + expo.mul(PMULTI)));
}
// get reveiced Tickets, based on current round ticketSum
function getTAmount(uint256 _ethAmount, uint256 _ticketSum)
public
pure
returns(uint256)
{
uint256 _tPrice = getTPrice(_ticketSum);
return _ethAmount.div(_tPrice);
}
// Lotto-Multiplier = 1 + LBase * (Current No. of Tickets / PDivider)^6
function getTMul(uint256 _ticketSum) // Unit Wei
public
pure
returns(uint256)
{
uint256 base = _ticketSum * ZOOM / PDIVIDER;
uint256 expo = base.mul(base).mul(base);
expo = expo.mul(expo); // ^6
return 1 + expo.mul(LBase) / (10**18);
}
// get ticket price, based on current round ticketSum
//unit in ETH, no need / zoom^6
function getTPrice(uint256 _ticketSum)
public
pure
returns(uint256)
{
uint256 base = (_ticketSum + 1).mul(ZOOM) / PDIVIDER;
uint256 expo = base;
expo = expo.mul(expo).mul(expo); // ^3
expo = expo.mul(expo); // ^6
uint256 tPrice = SLP + expo / PN;
return tPrice;
}
// get weight of slot, chance to win grandPot
function getSlotWeight(uint256 _ethAmount, uint256 _ticketSum)
public
pure
returns(uint256)
{
uint256 _tAmount = getTAmount(_ethAmount, _ticketSum);
uint256 _tMul = getTMul(_ticketSum);
return (_tAmount).mul(_tMul);
}
// used to draw grandpot results
// weightRange = roundWeight * grandpot / (grandpot - initGrandPot)
// grandPot = initGrandPot + round investedSum(for grandPot)
function getWeightRange(uint256 grandPot, uint256 initGrandPot, uint256 curRWeight)
public
pure
returns(uint256)
{
//calculate round grandPot-investedSum
uint256 grandPotInvest = grandPot - initGrandPot;
if (grandPotInvest == 0) return 8;
uint256 zoomMul = grandPot * ZOOM / grandPotInvest;
uint256 weightRange = zoomMul * curRWeight / ZOOM;
if (weightRange < curRWeight) weightRange = curRWeight;
return weightRange;
}
}
contract Lottery {
using SafeMath for uint256;
modifier withdrawRight(){
require(msg.sender == address(bankContract), "Bank only");
_;
}
modifier onlyDevTeam() {
require(msg.sender == devTeam, "only for development team");
_;
}
modifier buyable() {
require(block.timestamp > round[curRoundId].startTime, "not ready to sell Ticket");
require(block.timestamp < round[curRoundId].slideEndTime, "round over");
_;
}
enum RewardType {
Minor,
Major,
Grand,
Bounty
}
// 1 buy = 1 slot = _ethAmount => (tAmount, tMul)
struct Slot {
address buyer;
uint256 rId;
// ticket numbers in range and unique in all rounds
uint256 tNumberFrom;
uint256 tNumberTo;
// weight to, used for grandPot finalize
uint256 wTo;
uint256 ethAmount;
uint256 salt;
}
struct Round {
// earlyIncome weight sum
uint256 rEarlyIncomeWeight;
// blockNumber to get hash as random seed
uint256 keyBlockNr;
mapping(address => uint256) pTicketSum;
mapping(address => uint256) pInvestedSum;
// early income weight by address
mapping(address => uint256) pEarlyIncomeWeight;
mapping(address => uint256) pEarlyIncomeCredit;
mapping(address => uint256) pEarlyIncomeClaimed;
// early income per weight
uint256 ppw;
// endTime increased every slot sold
// endTime limited by fixedEndTime
uint256 startTime;
uint256 slideEndTime;
uint256 fixedEndTime;
// ticketSum from round 1 to this round
uint256 ticketSum;
// investedSum from round 1 to this round
uint256 investedSum;
// number of slots from round 1 to this round
uint256 slotSum;
}
// round started with this grandPot amount,
// used to calculate the rate for grandPot results
// init in roundInit function
uint256 initGrandPot;
Slot[] slot;
// slotId logs by address
mapping( address => uint256[]) pSlot;
mapping( address => uint256) public pSlotSum;
// logs by address
mapping( address => uint256) public pTicketSum;
mapping( address => uint256) public pInvestedSum;
CitizenInterface public citizenContract;
F2mInterface public f2mContract;
BankInterface public bankContract;
RewardInterface public rewardContract;
address public devTeam;
uint256 constant public ZOOM = 1000;
uint256 constant public ONE_HOUR = 60 * 60;
uint256 constant public ONE_DAY = 24 * ONE_HOUR;
uint256 constant public TIMEOUT0 = 3 * ONE_HOUR;
uint256 constant public TIMEOUT1 = 12 * ONE_HOUR;
uint256 constant public TIMEOUT2 = 7 * ONE_DAY;
uint256 constant public FINALIZE_WAIT_DURATION = 60; // 60 Seconds
uint256 constant public NEWROUND_WAIT_DURATION = ONE_DAY; // 24 Hours
// 15 seconds on Ethereum, 12 seconds used instead to make sure blockHash unavaiable
// when slideEndTime reached
// keyBlockNumber will be estimated again after every slot buy
uint256 constant public BLOCK_TIME = 12;
uint256 constant public MAX_BLOCK_DISTANCE = 254;
uint256 constant public MAJOR_RATE = 1000;
uint256 constant public MINOR_RATE = 1000;
uint256 constant public MAJOR_MIN = 0.1 ether ;
uint256 constant public MINOR_MIN = 0.1 ether ;
//uint256 public toNextPotPercent = 27;
uint256 public grandRewardPercent = 20;
uint256 public jRewardPercent = 60;
uint256 public toTokenPercent = 12; // 10% dividends 2% fund
uint256 public toBuyTokenPercent = 1;
uint256 public earlyIncomePercent = 22;
uint256 public toRefPercent = 15;
// sum == 100% = toPotPercent/100 * investedSum
// uint256 public grandPercent = 68;
uint256 public majorPercent = 24;
uint256 public minorPercent = 8;
uint256 public grandPot;
uint256 public majorPot;
uint256 public minorPot;
uint256 public curRoundId;
uint256 public lastRoundId = 88888888;
uint256 constant public startPrice = 0.002 ether;
mapping (address => uint256) public rewardBalance;
// used to save gas on earlyIncome calculating, curRoundId never included
// only earlyIncome from round 1st to curRoundId-1 are fixed
mapping (address => uint256) public lastWithdrawnRound;
mapping (address => uint256) public earlyIncomeScannedSum;
mapping (uint256 => Round) public round;
// Current Round
// first SlotId in last Block to fire jackpot
uint256 public jSlot;
// jackpot results of all slots in same block will be drawed at the same time,
// by player, who buys the first slot in next block
uint256 public lastBlockNr;
// used to calculate grandPot results
uint256 public curRWeight;
// added by slot salt after every slot buy
// does not matter with overflow
uint256 public curRSalt;
// ticket sum of current round
uint256 public curRTicketSum;
constructor (address _devTeam)
public
{
// register address in network
DevTeamInterface(_devTeam).setLotteryAddress(address(this));
devTeam = _devTeam;
}
// _contract = [f2mAddress, bankAddress, citizenAddress, lotteryAddress, rewardAddress, whitelistAddress];
function joinNetwork(address[6] _contract)
public
{
require(address(citizenContract) == 0x0,"already setup");
f2mContract = F2mInterface(_contract[0]);
bankContract = BankInterface(_contract[1]);
citizenContract = CitizenInterface(_contract[2]);
//lotteryContract = LotteryInterface(lotteryAddress);
rewardContract = RewardInterface(_contract[4]);
}
function activeFirstRound()
public
onlyDevTeam()
{
require(curRoundId == 0, "already activated");
initRound();
}
// Core Functions
function pushToPot()
public
payable
{
addPot(msg.value);
}
function checkpoint()
private
{
// dummy slot between every 2 rounds
// dummy slot never win jackpot cause of min 0.1 ETH
Slot memory _slot;
_slot.tNumberTo = round[curRoundId].ticketSum;
slot.push(_slot);
Round memory _round;
_round.startTime = NEWROUND_WAIT_DURATION.add(block.timestamp);
// started with 3 hours timeout
_round.slideEndTime = TIMEOUT0 + _round.startTime;
_round.fixedEndTime = TIMEOUT2 + _round.startTime;
_round.keyBlockNr = genEstKeyBlockNr(_round.slideEndTime);
_round.ticketSum = round[curRoundId].ticketSum;
_round.investedSum = round[curRoundId].investedSum;
_round.slotSum = slot.length;
curRoundId = curRoundId + 1;
round[curRoundId] = _round;
initGrandPot = grandPot;
curRWeight = 0;
curRTicketSum = 0;
}
// from round 18+ function
function isLastRound()
public
view
returns(bool)
{
return (curRoundId == lastRoundId);
}
function goNext()
private
{
uint256 _totalPot = getTotalPot();
grandPot = 0;
majorPot = 0;
minorPot = 0;
f2mContract.pushDividends.value(_totalPot)();
// never start
round[curRoundId].startTime = block.timestamp * 10;
round[curRoundId].slideEndTime = block.timestamp * 10 + 1;
}
function initRound()
private
{
// update all Round Log
checkpoint();
if (isLastRound()) goNext();
}
function finalizeable()
public
view
returns(bool)
{
uint256 finalizeTime = FINALIZE_WAIT_DURATION.add(round[curRoundId].slideEndTime);
if (finalizeTime > block.timestamp) return false; // too soon to finalize
if (getEstKeyBlockNr(curRoundId) >= block.number) return false; //block hash not exist
return curRoundId > 0;
}
// bounty
function finalize()
public
{
require(finalizeable(), "Not ready to draw results");
// avoid txs blocked => curRTicket ==0 => die
require((round[curRoundId].pTicketSum[msg.sender] > 0) || (curRTicketSum == 0), "must buy at least 1 ticket");
endRound(msg.sender);
initRound();
}
function mintReward(
address _lucker,
uint256 _slotId,
uint256 _value,
RewardType _rewardType)
private
{
// add reward balance
rewardBalance[_lucker] = rewardBalance[_lucker].add(_value);
// reward log
rewardContract.mintReward(
_lucker,
curRoundId,
slot[_slotId].tNumberFrom,
slot[_slotId].tNumberTo,
_value,
uint256(_rewardType)
);
}
function jackpot()
private
{
// get blocknumber to get blockhash
uint256 keyBlockNr = getKeyBlockNr(lastBlockNr);//block.number;
// salt not effected by jackpot, too risk
uint256 seed = getSeed(keyBlockNr);
// slot numberic from 1 ... totalSlot(round)
// jackpot for all slot in last block, jSlot <= i <= lastSlotId (=slotSum - 1)
// _to = first Slot in new block
//uint256 _to = round[curRoundId].slotSum;
uint256 jReward;
uint256 toF2mAmount;
address winner;
// jackpot check for slots in last block
while (jSlot + 1 < round[curRoundId].slotSum) {
// majorPot
if ((seed % MAJOR_RATE == 6) &&
(slot[jSlot].ethAmount >= MAJOR_MIN)) {
winner = slot[jSlot].buyer;
jReward = majorPot / 100 * jRewardPercent;
mintReward(winner, jSlot, jReward, RewardType.Major);
toF2mAmount = majorPot / 100 * toTokenPercent;
f2mContract.pushDividends.value(toF2mAmount)();
majorPot = majorPot - jReward - toF2mAmount;
}
// minorPot
if (((seed + jSlot) % MINOR_RATE == 8) &&
(slot[jSlot].ethAmount >= MINOR_MIN)) {
winner = slot[jSlot].buyer;
jReward = minorPot / 100 * jRewardPercent;
mintReward(winner, jSlot, jReward, RewardType.Minor);
toF2mAmount = minorPot / 100 * toTokenPercent;
f2mContract.pushDividends.value(toF2mAmount)();
minorPot = minorPot - jReward - toF2mAmount;
}
seed = seed + 1;
jSlot = jSlot + 1;
}
}
function endRound(address _bountyHunter)
private
{
uint256 _rId = curRoundId;
uint256 keyBlockNr = getKeyBlockNr(round[_rId].keyBlockNr);
uint256 _seed = getSeed(keyBlockNr) + curRSalt;
uint256 onePercent = grandPot / 100;
uint256 rGrandReward = onePercent * grandRewardPercent;
//PUSH DIVIDENDS
uint256 toF2mAmount = onePercent * toTokenPercent;
//uint256 _bountyAmount = onePercent * bountyPercent;
grandPot = grandPot - toF2mAmount - onePercent;
f2mContract.pushDividends.value(toF2mAmount)();
// base on grand-intestedSum current grandPot
uint256 weightRange = getWeightRange();
// roll 3 turns
for (uint256 i = 0; i < 3; i++){
uint256 winNr = Helper.getRandom(_seed, weightRange);
// if winNr > curRoundWeight => no winner this turn
// win Slot : fromWeight <= winNr <= toWeight
// got winner this rolling turn
if (winNr <= curRWeight) {
grandPot -= rGrandReward;
uint256 _winSlot = getWinSlot(winNr);
address _winner = slot[_winSlot].buyer;
mintReward(_winner, _winSlot, rGrandReward, RewardType.Grand);
_seed = _seed + (_seed / 10);
}
}
mintReward(_bountyHunter, 0, onePercent * 3 / 10, RewardType.Bounty);
rewardContract.pushBounty.value(onePercent * 7 / 10)(curRoundId);
}
function buy(string _sSalt)
public
payable
{
buyFor(_sSalt, msg.sender);
}
function updateInvested(address _buyer, uint256 _ethAmount)
private
{
round[curRoundId].investedSum += _ethAmount;
round[curRoundId].pInvestedSum[_buyer] += _ethAmount;
pInvestedSum[_buyer] += _ethAmount;
}
function updateTicketSum(address _buyer, uint256 _tAmount)
private
{
round[curRoundId].ticketSum = round[curRoundId].ticketSum + _tAmount;
round[curRoundId].pTicketSum[_buyer] = round[curRoundId].pTicketSum[_buyer] + _tAmount;
curRTicketSum = curRTicketSum + _tAmount;
pTicketSum[_buyer] = pTicketSum[_buyer] + _tAmount;
}
function updateEarlyIncome(address _buyer, uint256 _pWeight)
private
{
round[curRoundId].rEarlyIncomeWeight = _pWeight.add(round[curRoundId].rEarlyIncomeWeight);
round[curRoundId].pEarlyIncomeWeight[_buyer] = _pWeight.add(round[curRoundId].pEarlyIncomeWeight[_buyer]);
round[curRoundId].pEarlyIncomeCredit[_buyer] = round[curRoundId].pEarlyIncomeCredit[_buyer].add(_pWeight.mul(round[curRoundId].ppw));
}
function buyFor(string _sSalt, address _sender)
public
payable
buyable()
{
uint256 _salt = Helper.stringToUint(_sSalt);
uint256 _ethAmount = msg.value;
uint256 _ticketSum = curRTicketSum;
require(_ethAmount >= Helper.getTPrice(_ticketSum), "not enough to buy 1 ticket");
// investedSum logs
updateInvested(_sender, _ethAmount);
// update salt
curRSalt = curRSalt + _salt;
// init new Slot, Slot Id = 1..curRSlotSum
Slot memory _slot;
_slot.rId = curRoundId;
_slot.buyer = _sender;
_slot.ethAmount = _ethAmount;
_slot.salt = _salt;
uint256 _tAmount = Helper.getTAmount(_ethAmount, _ticketSum);
uint256 _tMul = Helper.getTMul(_ticketSum);
uint256 _pMul = Helper.getEarlyIncomeMul(_ticketSum);
uint256 _pWeight = _pMul.mul(_tAmount);
uint256 _toAddTime = Helper.getAddedTime(_ticketSum, _tAmount);
addTime(curRoundId, _toAddTime);
// update weight
uint256 _slotWeight = (_tAmount).mul(_tMul);
curRWeight = curRWeight.add(_slotWeight);
_slot.wTo = curRWeight;
uint256 lastSlot = slot.length - 1;
// update ticket params
_slot.tNumberFrom = slot[lastSlot].tNumberTo + 1;
_slot.tNumberTo = slot[lastSlot].tNumberTo + _tAmount;
updateTicketSum(_sender, _tAmount);
// EarlyIncome Weight
// ppw and credit zoomed x1000
// earlyIncome mul of each ticket in this slot
updateEarlyIncome(_sender, _pWeight);
// add Slot and update round data
slot.push(_slot);
round[curRoundId].slotSum = slot.length;
// add slot to player logs
pSlot[_sender].push(slot.length - 1);
// first slot in this block draw jacpot results for
// all slot in last block
if (lastBlockNr != block.number) {
jackpot();
lastBlockNr = block.number;
}
distributeSlotBuy(_sender, curRoundId, _ethAmount);
round[curRoundId].keyBlockNr = genEstKeyBlockNr(round[curRoundId].slideEndTime);
}
function distributeSlotBuy(address _sender, uint256 _rId, uint256 _ethAmount)
private
{
uint256 onePercent = _ethAmount / 100;
uint256 toF2mAmount = onePercent * toTokenPercent; // 12
uint256 toRefAmount = onePercent * toRefPercent; // 10
uint256 toBuyTokenAmount = onePercent * toBuyTokenPercent; //1
uint256 earlyIncomeAmount = onePercent * earlyIncomePercent; //27
uint256 taxAmount = toF2mAmount + toRefAmount + toBuyTokenAmount + earlyIncomeAmount; // 50
uint256 taxedEthAmount = _ethAmount.sub(taxAmount); // 50
addPot(taxedEthAmount);
// 10% Ref
citizenContract.pushRefIncome.value(toRefAmount)(_sender);
// 2% Fund + 10% Dividends
f2mContract.pushDividends.value(toF2mAmount)();
// 1% buy Token
f2mContract.buyFor.value(toBuyTokenAmount)(_sender);
// 27% Early
uint256 deltaPpw = (earlyIncomeAmount * ZOOM).div(round[_rId].rEarlyIncomeWeight);
round[_rId].ppw = deltaPpw.add(round[_rId].ppw);
}
function claimEarlyIncomebyAddress(address _buyer)
private
{
if (curRoundId == 0) return;
claimEarlyIncomebyAddressRound(_buyer, curRoundId);
uint256 _rId = curRoundId - 1;
while ((_rId > lastWithdrawnRound[_buyer]) && (_rId + 20 > curRoundId)) {
earlyIncomeScannedSum[_buyer] += claimEarlyIncomebyAddressRound(_buyer, _rId);
_rId = _rId - 1;
}
}
function claimEarlyIncomebyAddressRound(address _buyer, uint256 _rId)
private
returns(uint256)
{
uint256 _amount = getCurEarlyIncomeByAddressRound(_buyer, _rId);
if (_amount == 0) return 0;
round[_rId].pEarlyIncomeClaimed[_buyer] = _amount.add(round[_rId].pEarlyIncomeClaimed[_buyer]);
rewardBalance[_buyer] = _amount.add(rewardBalance[_buyer]);
return _amount;
}
function withdrawFor(address _sender)
public
withdrawRight()
returns(uint256)
{
if (curRoundId == 0) return;
claimEarlyIncomebyAddress(_sender);
lastWithdrawnRound[_sender] = curRoundId - 1;
uint256 _amount = rewardBalance[_sender];
rewardBalance[_sender] = 0;
bankContract.pushToBank.value(_amount)(_sender);
return _amount;
}
function addTime(uint256 _rId, uint256 _toAddTime)
private
{
round[_rId].slideEndTime = Helper.getNewEndTime(_toAddTime, round[_rId].slideEndTime, round[_rId].fixedEndTime);
}
// distribute to 3 pots Grand, Majorm Minor
function addPot(uint256 _amount)
private
{
uint256 onePercent = _amount / 100;
uint256 toMinor = onePercent * minorPercent;
uint256 toMajor = onePercent * majorPercent;
uint256 toGrand = _amount - toMinor - toMajor;
minorPot = minorPot + toMinor;
majorPot = majorPot + toMajor;
grandPot = grandPot + toGrand;
}
//////////////////////////////////////////////////////////////////
// READ FUNCTIONS
//////////////////////////////////////////////////////////////////
function isWinSlot(uint256 _slotId, uint256 _keyNumber)
public
view
returns(bool)
{
return (slot[_slotId - 1].wTo < _keyNumber) && (slot[_slotId].wTo >= _keyNumber);
}
function getWeightRange()
public
view
returns(uint256)
{
return Helper.getWeightRange(grandPot, initGrandPot, curRWeight);
}
function getWinSlot(uint256 _keyNumber)
public
view
returns(uint256)
{
// return 0 if not found
uint256 _to = slot.length - 1;
uint256 _from = round[curRoundId-1].slotSum + 1; // dummy slot ignore
uint256 _pivot;
//Slot memory _slot;
uint256 _pivotWTo;
// Binary search
while (_from <= _to) {
_pivot = (_from + _to) / 2;
//_slot = round[_rId].slot[_pivot];
_pivotWTo = slot[_pivot].wTo;
if (isWinSlot(_pivot, _keyNumber)) return _pivot;
if (_pivotWTo < _keyNumber) { // in right side
_from = _pivot + 1;
} else { // in left side
_to = _pivot - 1;
}
}
return _pivot; // never happens or smt gone wrong
}
// Key Block in future
function genEstKeyBlockNr(uint256 _endTime)
public
view
returns(uint256)
{
if (block.timestamp >= _endTime) return block.number + 8;
uint256 timeDist = _endTime - block.timestamp;
uint256 estBlockDist = timeDist / BLOCK_TIME;
return block.number + estBlockDist + 8;
}
// get block hash of first block with blocktime > _endTime
function getSeed(uint256 _keyBlockNr)
public
view
returns (uint256)
{
// Key Block not mined atm
if (block.number <= _keyBlockNr) return block.number;
return uint256(blockhash(_keyBlockNr));
}
// current reward balance
function getRewardBalance(address _buyer)
public
view
returns(uint256)
{
return rewardBalance[_buyer];
}
// GET endTime
function getSlideEndTime(uint256 _rId)
public
view
returns(uint256)
{
return(round[_rId].slideEndTime);
}
function getFixedEndTime(uint256 _rId)
public
view
returns(uint256)
{
return(round[_rId].fixedEndTime);
}
function getTotalPot()
public
view
returns(uint256)
{
return grandPot + majorPot + minorPot;
}
// EarlyIncome
function getEarlyIncomeByAddress(address _buyer)
public
view
returns(uint256)
{
uint256 _sum = earlyIncomeScannedSum[_buyer];
uint256 _fromRound = lastWithdrawnRound[_buyer] + 1; // >=1
if (_fromRound + 100 < curRoundId) _fromRound = curRoundId - 100;
uint256 _rId = _fromRound;
while (_rId <= curRoundId) {
_sum = _sum + getEarlyIncomeByAddressRound(_buyer, _rId);
_rId++;
}
return _sum;
}
// included claimed amount
function getEarlyIncomeByAddressRound(address _buyer, uint256 _rId)
public
view
returns(uint256)
{
uint256 _pWeight = round[_rId].pEarlyIncomeWeight[_buyer];
uint256 _ppw = round[_rId].ppw;
uint256 _rCredit = round[_rId].pEarlyIncomeCredit[_buyer];
uint256 _rEarlyIncome = ((_ppw.mul(_pWeight)).sub(_rCredit)).div(ZOOM);
return _rEarlyIncome;
}
function getCurEarlyIncomeByAddress(address _buyer)
public
view
returns(uint256)
{
uint256 _sum = 0;
uint256 _fromRound = lastWithdrawnRound[_buyer] + 1; // >=1
if (_fromRound + 100 < curRoundId) _fromRound = curRoundId - 100;
uint256 _rId = _fromRound;
while (_rId <= curRoundId) {
_sum = _sum.add(getCurEarlyIncomeByAddressRound(_buyer, _rId));
_rId++;
}
return _sum;
}
function getCurEarlyIncomeByAddressRound(address _buyer, uint256 _rId)
public
view
returns(uint256)
{
uint256 _rEarlyIncome = getEarlyIncomeByAddressRound(_buyer, _rId);
return _rEarlyIncome.sub(round[_rId].pEarlyIncomeClaimed[_buyer]);
}
////////////////////////////////////////////////////////////////////
function getEstKeyBlockNr(uint256 _rId)
public
view
returns(uint256)
{
return round[_rId].keyBlockNr;
}
function getKeyBlockNr(uint256 _estKeyBlockNr)
public
view
returns(uint256)
{
require(block.number > _estKeyBlockNr, "blockHash not avaiable");
uint256 jump = (block.number - _estKeyBlockNr) / MAX_BLOCK_DISTANCE * MAX_BLOCK_DISTANCE;
return _estKeyBlockNr + jump;
}
// Logs
function getCurRoundId()
public
view
returns(uint256)
{
return curRoundId;
}
function getTPrice()
public
view
returns(uint256)
{
return Helper.getTPrice(curRTicketSum);
}
function getTMul()
public
view
returns(uint256)
{
return Helper.getTMul(curRTicketSum);
}
function getPMul()
public
view
returns(uint256)
{
return Helper.getEarlyIncomeMul(curRTicketSum);
}
function getPTicketSumByRound(uint256 _rId, address _buyer)
public
view
returns(uint256)
{
return round[_rId].pTicketSum[_buyer];
}
function getTicketSumToRound(uint256 _rId)
public
view
returns(uint256)
{
return round[_rId].ticketSum;
}
function getPInvestedSumByRound(uint256 _rId, address _buyer)
public
view
returns(uint256)
{
return round[_rId].pInvestedSum[_buyer];
}
function getInvestedSumToRound(uint256 _rId)
public
view
returns(uint256)
{
return round[_rId].investedSum;
}
function getPSlotLength(address _sender)
public
view
returns(uint256)
{
return pSlot[_sender].length;
}
function getSlotLength()
public
view
returns(uint256)
{
return slot.length;
}
function getSlotId(address _sender, uint256 i)
public
view
returns(uint256)
{
return pSlot[_sender][i];
}
function getSlotInfo(uint256 _slotId)
public
view
returns(address, uint256[4], string)
{
Slot memory _slot = slot[_slotId];
return (_slot.buyer,[_slot.rId, _slot.tNumberFrom, _slot.tNumberTo, _slot.ethAmount], Helper.uintToString(_slot.salt));
}
function cashoutable(address _address)
public
view
returns(bool)
{
// need 1 ticket or in waiting time to start new round
return (round[curRoundId].pTicketSum[_address] > 0) || (round[curRoundId].startTime > block.timestamp);
}
// set endRound, prepare to upgrade new version
function setLastRound(uint256 _lastRoundId)
public
onlyDevTeam()
{
require(_lastRoundId >= 18 && _lastRoundId > curRoundId, "too early to end");
require(lastRoundId == 88888888, "already set");
lastRoundId = _lastRoundId;
}
} | dummy slot between every 2 rounds dummy slot never win jackpot cause of min 0.1 ETH started with 3 hours timeout | function checkpoint()
private
{
Slot memory _slot;
_slot.tNumberTo = round[curRoundId].ticketSum;
slot.push(_slot);
Round memory _round;
_round.startTime = NEWROUND_WAIT_DURATION.add(block.timestamp);
_round.slideEndTime = TIMEOUT0 + _round.startTime;
_round.fixedEndTime = TIMEOUT2 + _round.startTime;
_round.keyBlockNr = genEstKeyBlockNr(_round.slideEndTime);
_round.ticketSum = round[curRoundId].ticketSum;
_round.investedSum = round[curRoundId].investedSum;
_round.slotSum = slot.length;
curRoundId = curRoundId + 1;
round[curRoundId] = _round;
initGrandPot = grandPot;
curRWeight = 0;
curRTicketSum = 0;
}
| 13,442,700 |
pragma solidity ^0.5.13;
import './interfaces/SyscoinSuperblocksI.sol';
import "./SyscoinErrorCodes.sol";
import "./SyscoinTransactionProcessor.sol";
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "./SyscoinParser/SyscoinMessageLibrary.sol";
// @dev - Manages superblocks
//
// Management of superblocks and status transitions
contract SyscoinSuperblocks is Initializable, SyscoinSuperblocksI, SyscoinErrorCodes, SyscoinMessageLibrary {
uint constant ERR_PARSE_TX_SYS = 10170;
uint32 constant SYSCOIN_TX_VERSION_ALLOCATION_BURN_TO_ETHEREUM = 0x7407;
uint32 constant SYSCOIN_TX_VERSION_ALLOCATION_MINT = 0x7406;
// Mapping superblock id => superblock data
mapping (bytes32 => SuperblockInfo) internal superblocks;
bytes32 internal bestSuperblock;
SyscoinTransactionProcessor public syscoinERC20Manager;
event NewSuperblock(bytes32 superblockHash, address who);
event ApprovedSuperblock(bytes32 superblockHash, address who);
event ChallengeSuperblock(bytes32 superblockHash, address who);
event SemiApprovedSuperblock(bytes32 superblockHash, address who);
event InvalidSuperblock(bytes32 superblockHash, address who);
event ErrorSuperblock(bytes32 superblockHash, uint err);
event VerifyTransaction(bytes32 txHash, uint returnCode);
event RelayTransaction(bytes32 txHash, uint returnCode);
event ChallengeCancelTransferRequest(uint returnCode);
// SyscoinClaimManager
address public trustedClaimManager;
uint32 constant SYSCOIN_TX_VERSION_ASSET_ACTIVATE = 0x7402;
uint32 constant SYSCOIN_TX_VERSION_ASSET_UPDATE = 0x7403;
modifier onlyClaimManager() {
require(msg.sender == trustedClaimManager);
_;
}
// @param _syscoinERC20Manager - address of the SyscoinERC20Manager contract to be associated with
// @param _claimManager - address of the ClaimManager contract to be associated with
function init(address _syscoinERC20Manager, address _claimManager) public initializer {
require(address(syscoinERC20Manager) == address(0) && _syscoinERC20Manager != address(0));
syscoinERC20Manager = SyscoinTransactionProcessor(_syscoinERC20Manager);
require(address(trustedClaimManager) == address(0) && _claimManager != address(0));
trustedClaimManager = _claimManager;
}
// Returns true if the tx output is an OP_RETURN output
function isOpReturn(bytes memory txBytes, uint pos) internal pure returns (bool) {
// scriptPub format is
// 0x6a OP_RETURN
return txBytes[pos] == byte(0x6a);
}
function bytesToUint64(bytes memory input, uint pos) public pure returns (uint64 result) {
result = uint64(uint8(input[pos+7])) + uint64(uint8(input[pos + 6]))*(2**8) + uint64(uint8(input[pos + 5]))*(2**16) + uint64(uint8(input[pos + 4]))*(2**24) + uint64(uint8(input[pos + 3]))*(2**32) + uint64(uint8(input[pos + 2]))*(2**40) + uint64(uint8(input[pos + 1]))*(2**48) + uint64(uint8(input[pos]))*(2**56);
}
function bytesToUint32(bytes memory input, uint pos) public pure returns (uint32 result) {
result = uint32(uint8(input[pos+3])) + uint32(uint8(input[pos + 2]))*(2**8) + uint32(uint8(input[pos + 1]))*(2**16) + uint32(uint8(input[pos]))*(2**24);
}
// Returns asset data parsed from the op_return data output from syscoin asset burn transaction
function scanAssetDetails(bytes memory txBytes, uint pos)
internal
pure
returns (uint, address, uint32, uint8, address)
{
uint32 assetGUID;
address destinationAddress;
address erc20Address;
uint output_value;
uint8 precision;
uint8 op;
// vchAsset
(op, pos) = getOpcode(txBytes, pos);
// guid length should be 4 bytes
require(op == 0x04);
assetGUID = bytesToUint32(txBytes, pos);
pos += op;
// amount
(op, pos) = getOpcode(txBytes, pos);
require(op == 0x08);
output_value = bytesToUint64(txBytes, pos);
pos += op;
// destination address
(op, pos) = getOpcode(txBytes, pos);
// ethereum contracts are 20 bytes (without the 0x)
require(op == 0x14);
destinationAddress = readEthereumAddress(txBytes, pos);
pos += op;
// precision
(op, pos) = getOpcode(txBytes, pos);
require(op == 0x01);
precision = uint8(txBytes[pos]);
pos += op;
// erc20Address
(op, pos) = getOpcode(txBytes, pos);
require(op == 0x14);
erc20Address = readEthereumAddress(txBytes, pos);
return (output_value, destinationAddress, assetGUID, precision, erc20Address);
}
// Read the ethereum address embedded in the tx output
function readEthereumAddress(bytes memory txBytes, uint pos) internal pure returns (address) {
uint256 data;
assembly {
data := mload(add(add(txBytes, 20), pos))
}
return address(uint160(data));
}
// Read next opcode from script
function getOpcode(bytes memory txBytes, uint pos) private pure returns (uint8, uint) {
require(pos < txBytes.length);
return (uint8(txBytes[pos]), pos + 1);
}
function getOpReturnPos(bytes memory txBytes, uint pos) public pure returns (uint) {
uint n_inputs;
uint script_len;
uint output_value;
uint n_outputs;
(n_inputs, pos) = parseVarInt(txBytes, pos);
// if dummy 0x00 is present this is a witness transaction
if(n_inputs == 0x00){
(n_inputs, pos) = parseVarInt(txBytes, pos); // flag
require(n_inputs != 0x00, "#SyscoinSuperblocks getOpReturnPos(): Unexpected dummy/flag");
// after dummy/flag the real var int comes for txins
(n_inputs, pos) = parseVarInt(txBytes, pos);
}
require(n_inputs < 100, "#SyscoinSuperblocks getOpReturnPos(): Incorrect size of n_inputs");
for (uint i = 0; i < n_inputs; i++) {
pos += 36; // skip outpoint
(script_len, pos) = parseVarInt(txBytes, pos);
pos += script_len + 4; // skip sig_script, seq
}
(n_outputs, pos) = parseVarInt(txBytes, pos);
require(n_outputs < 10, "#SyscoinSuperblocks getOpReturnPos(): Incorrect size of n_outputs");
for (uint i = 0; i < n_outputs; i++) {
pos += 8;
// varint
(script_len, pos) = parseVarInt(txBytes, pos);
if(!isOpReturn(txBytes, pos)){
// output script
pos += script_len;
output_value = 0;
continue;
}
// skip opreturn marker
pos += 1;
return pos;
}
revert("#SyscoinSuperblocks getOpReturnPos(): No OpReturn found");
}
/**
* @dev Parse syscoin mint transaction to recover bridgeTransferId
* @param txBytes syscoin raw transaction
* @return errorCode, bridgeTransferId
*/
function parseMintTx(bytes memory txBytes)
public
view
returns (uint errorCode, uint32 bridgeTransferId)
{
uint32 version;
uint pos = 0;
version = bytesToUint32Flipped(txBytes, pos);
if(version != SYSCOIN_TX_VERSION_ALLOCATION_MINT){
return (ERR_PARSE_TX_SYS, bridgeTransferId);
}
pos = getOpReturnPos(txBytes, 4);
pos += 3; // skip pushdata2 + 2 bytes for opreturn varint
// SHA3 of TokenFreeze(address,uint256,uint32)
bytes32 tokenFreezeTopic = 0xaabab1db49e504b5156edf3f99042aeecb9607a08f392589571cd49743aaba8d;
bridgeTransferId = uint32(
getBridgeTransactionId(
getLogValuesForTopic(
getEthReceipt(txBytes, pos), tokenFreezeTopic
)
)
);
}
/** @dev Parse syscoin asset transaction to recover asset guid and contract, for purposes of updating asset registry in erc20manager
* @param txBytes syscoin raw transaction
* @return errorCode, assetGuid, erc20Address
*/
function parseAssetTx(bytes memory txBytes)
public
view
returns (uint errorCode, uint32 assetGuid, address erc20Address)
{
uint32 version;
uint pos = 0;
version = bytesToUint32Flipped(txBytes, pos);
if(version != SYSCOIN_TX_VERSION_ASSET_ACTIVATE && version != SYSCOIN_TX_VERSION_ASSET_UPDATE){
return (ERR_PARSE_TX_SYS, 0, address(0));
}
pos = getOpReturnPos(txBytes, 4);
byte pushDataOp = txBytes[pos+1];
pos += 2; // we will have to skip pushdata op as well as atleast 1 byte
if(pushDataOp == 0x4d){
pos++; // skip pushdata2 + 2 bytes for opreturn varint
}
(assetGuid, erc20Address) = scanAssetTx(txBytes, pos);
require(erc20Address != address(0),
"parseAssetTx(): erc20Address cannot be empty");
}
function bytesToUint16(bytes memory input, uint pos) public pure returns (uint16 result) {
result = uint16(uint8(input[pos+1])) + uint16(uint8(input[pos]))*(2**8);
}
/**
* Parse txBytes and returns ethereum tx receipt
* @param txBytes syscoin raw transaction
* @param pos position at where to start parsing
* @return ethTxReceipt ethereum tx receipt
*/
function getEthReceipt(bytes memory txBytes, uint pos)
public
view
returns (bytes memory)
{
bytes memory ethTxReceipt = new bytes(0);
uint bytesToRead;
// skip vchTxValue
(bytesToRead, pos) = parseVarInt(txBytes, pos);
pos += bytesToRead;
// skip vchTxParentNodes
(bytesToRead, pos) = parseVarInt(txBytes, pos);
pos += bytesToRead;
// skip vchTxRoot
(bytesToRead, pos) = parseVarInt(txBytes, pos);
pos += bytesToRead;
// skip vchTxPath
(bytesToRead, pos) = parseVarInt(txBytes, pos);
pos += bytesToRead;
// get vchReceiptValue
(bytesToRead, pos) = parseVarInt(txBytes, pos);
// if position is encoded in receipt value, decode position and read the value from next field (parent nodes)
if(bytesToRead == 2){
uint16 positionOfValue = bytesToUint16(txBytes, pos);
pos += bytesToRead;
// get vchReceiptParentNodes
(bytesToRead, pos) = parseVarInt(txBytes, pos);
pos += positionOfValue;
ethTxReceipt = sliceArray(txBytes, pos, pos+(bytesToRead-positionOfValue));
}
// size > 2 means receipt value is fully serialized in this field and no need to get parent nodes field
else{
ethTxReceipt = sliceArray(txBytes, pos, pos+bytesToRead);
}
return ethTxReceipt;
}
/**
* Parse txBytes and returns assetguid + contract address
* @param txBytes syscoin raw transaction
* @param pos position at where to start parsing
* @return asset guid (uint32) and erc20 address linked to the asset guid to update registry in erc20manager
*/
function scanAssetTx(bytes memory txBytes, uint pos)
public
view
returns (uint32, address)
{
uint32 assetGUID;
address erc20Address;
uint bytesToRead;
// skip vchPubData
(bytesToRead, pos) = parseVarInt(txBytes, pos);
pos += bytesToRead;
// skip txHash
pos += 32;
// get nAsset
assetGUID = bytesToUint32Flipped(txBytes, pos);
pos += 4;
// skip strSymbol
(bytesToRead, pos) = parseVarInt(txBytes, pos);
pos += bytesToRead;
// skip witnessAddress.nVersion
pos += 1;
// skip witnessAddress.vchWitnessProgram
(bytesToRead, pos) = parseVarInt(txBytes, pos);
pos += bytesToRead;
// skip witnessAddressTransfer.nVersion
pos += 1;
// skip witnessAddressTransfer.vchWitnessProgram
(bytesToRead, pos) = parseVarInt(txBytes, pos);
pos += bytesToRead;
// skip nBalance
pos += 8;
// skip nTotalSupply
pos += 8;
// skip nMaxSupply
pos += 8;
// skip nHeight
pos += 4;
// skip nUpdateFlags
pos += 1;
// skip nPrecision
pos += 1;
// get vchContract
(bytesToRead, pos) = parseVarInt(txBytes, pos);
require(bytesToRead == 0x14,
"scanAssetTx(): Invalid number of bytes read for contract field");
erc20Address = readEthereumAddress(txBytes, pos);
return (assetGUID, erc20Address);
}
// @dev converts bytes of any length to bytes32.
// If `_rawBytes` is longer than 32 bytes, it truncates to the 32 leftmost bytes.
// If it is shorter, it pads with 0s on the left.
// Should be private, made internal for testing
//
// @param _rawBytes - arbitrary length bytes
// @return - leftmost 32 or less bytes of input value; padded if less than 32
function bytesToBytes32(bytes memory _rawBytes, uint pos) public pure returns (bytes32) {
bytes32 out;
assembly {
out := mload(add(add(_rawBytes, 0x20), pos))
}
return out;
}
/**
* Return logs for given ethereum transaction receipt
* @param ethTxReceipt ethereum transaction receipt
* @return logs bloom
*/
function getLogValuesForTopic(bytes memory ethTxReceipt, bytes32 expectedTopic)
public
pure
returns (bytes memory)
{
RLPReader.RLPItem[] memory ethTxReceiptList = ethTxReceipt.toRlpItem().toList();
RLPReader.RLPItem[] memory logsList = ethTxReceiptList[3].toList();
for (uint256 i = 0; i < logsList.length; i++) {
RLPReader.RLPItem[] memory log = logsList[i].toList();
bytes memory rawTopic = log[1].toBytes();
bytes32 topic = bytesToBytes32(rawTopic, 1); // need to remove first byte "a0"
if (topic == expectedTopic) {
// data for given log
return log[2].toBytes();
}
}
revert("Topic not found");
}
/**
* Get bridgeTransactionId from logs bloom
* @param logValues log values
* @return bridgeTransactionId
*/
function getBridgeTransactionId(bytes memory logValues) public pure returns (uint256 value) {
uint8 index = 3; // log's third value
assembly {
value := mload(add(logValues, mul(32, index)))
}
}
// @dev - Initializes superblocks contract
//
// Initializes the superblock contract. It can only be called once.
//
// @param _blocksMerkleRoot Root of the merkle tree of blocks contained in a superblock
// @param _timestamp Timestamp of the last block in the superblock
// @param _mtpTimestamp Median Timestamp of the last block in the superblock
// @param _lastHash Hash of the last block in the superblock
// @param _lastBits Difficulty bits of the last block in the superblock bits
// @param _parentId Id of the parent superblock
// @param _blockHeight Block height of last block in superblock
// @return Error code and superblockHash
function initialize(
bytes32 _blocksMerkleRoot,
uint _timestamp,
uint _mtpTimestamp,
bytes32 _lastHash,
uint32 _lastBits,
bytes32 _parentId
) external returns (uint, bytes32) {
require(bestSuperblock == 0);
require(_parentId == 0);
bytes32 superblockHash = calcSuperblockHash(_blocksMerkleRoot, _timestamp, _mtpTimestamp, _lastHash, _lastBits, _parentId);
SuperblockInfo storage superblock = superblocks[superblockHash];
require(superblock.status == Status.Uninitialized);
superblock.blocksMerkleRoot = _blocksMerkleRoot;
superblock.timestamp = _timestamp;
superblock.mtpTimestamp = _mtpTimestamp;
superblock.lastHash = _lastHash;
superblock.parentId = _parentId;
superblock.submitter = msg.sender;
superblock.height = 1;
superblock.lastBits = _lastBits;
superblock.status = Status.Approved;
emit NewSuperblock(superblockHash, msg.sender);
bestSuperblock = superblockHash;
emit ApprovedSuperblock(superblockHash, msg.sender);
return (ERR_SUPERBLOCK_OK, superblockHash);
}
// @dev - Proposes a new superblock
//
// To be accepted, a new superblock needs to have its parent
// either approved or semi-approved.
//
// @param _blocksMerkleRoot Root of the merkle tree of blocks contained in a superblock
// @param _timestamp Timestamp of the last block in the superblock
// @param _mtpTimestamp Median Timestamp of the last block in the superblock
// @param _lastHash Hash of the last block in the superblock
// @param _lastBits Difficulty bits of the last block in the superblock bits
// @param _parentId Id of the parent superblock
// @return Error code and superblockHash
function propose(
bytes32 _blocksMerkleRoot,
uint _timestamp,
uint _mtpTimestamp,
bytes32 _lastHash,
uint32 _lastBits,
bytes32 _parentId,
address submitter
) external returns (uint, bytes32) {
if (msg.sender != trustedClaimManager) {
emit ErrorSuperblock(0, ERR_SUPERBLOCK_NOT_CLAIMMANAGER);
return (ERR_SUPERBLOCK_NOT_CLAIMMANAGER, 0);
}
SuperblockInfo storage parent = superblocks[_parentId];
if (parent.status != Status.SemiApproved && parent.status != Status.Approved) {
emit ErrorSuperblock(_parentId, ERR_SUPERBLOCK_BAD_PARENT + uint(parent.status));
return (ERR_SUPERBLOCK_BAD_PARENT + uint(parent.status), 0);
}
if (parent.height < getChainHeight()) {
emit ErrorSuperblock(_parentId, ERR_SUPERBLOCK_BAD_BLOCKHEIGHT);
return (ERR_SUPERBLOCK_BAD_BLOCKHEIGHT, 0);
}
bytes32 superblockHash = calcSuperblockHash(_blocksMerkleRoot, _timestamp, _mtpTimestamp, _lastHash, _lastBits, _parentId);
SuperblockInfo storage superblock = superblocks[superblockHash];
if (superblock.status == Status.Uninitialized) {
superblock.blocksMerkleRoot = _blocksMerkleRoot;
superblock.timestamp = _timestamp;
superblock.mtpTimestamp = _mtpTimestamp;
superblock.lastHash = _lastHash;
superblock.parentId = _parentId;
superblock.height = parent.height + 1;
superblock.lastBits = _lastBits;
}
superblock.status = Status.New;
superblock.submitter = submitter;
emit NewSuperblock(superblockHash, submitter);
return (ERR_SUPERBLOCK_OK, superblockHash);
}
// @dev - Confirm a proposed superblock
//
// An unchallenged superblock can be confirmed after a timeout.
// A challenged superblock is confirmed if it has enough descendants
// in the main chain.
//
// @param _superblockHash Id of the superblock to confirm
// @param _validator Address requesting superblock confirmation
// @return Error code and superblockHash
function confirm(bytes32 _superblockHash, address _validator) external returns (uint) {
if (msg.sender != trustedClaimManager) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_NOT_CLAIMMANAGER);
return ERR_SUPERBLOCK_NOT_CLAIMMANAGER;
}
SuperblockInfo storage superblock = superblocks[_superblockHash];
if (superblock.status != Status.New && superblock.status != Status.SemiApproved) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_STATUS);
return ERR_SUPERBLOCK_BAD_STATUS;
}
if (superblock.height <= getChainHeight()) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_BLOCKHEIGHT);
return ERR_SUPERBLOCK_BAD_BLOCKHEIGHT;
}
SuperblockInfo storage parent = superblocks[superblock.parentId];
if (parent.status != Status.Approved) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_PARENT);
return ERR_SUPERBLOCK_BAD_PARENT;
}
superblock.status = Status.Approved;
bestSuperblock = _superblockHash;
emit ApprovedSuperblock(_superblockHash, _validator);
return ERR_SUPERBLOCK_OK;
}
// @dev - Challenge a proposed superblock
//
// A new superblock can be challenged to start a battle
// to verify the correctness of the data submitted.
//
// @param _superblockHash Id of the superblock to challenge
// @param _challenger Address requesting a challenge
// @return Error code and superblockHash
function challenge(bytes32 _superblockHash, address _challenger) external returns (uint) {
if (msg.sender != trustedClaimManager) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_NOT_CLAIMMANAGER);
return ERR_SUPERBLOCK_NOT_CLAIMMANAGER;
}
SuperblockInfo storage superblock = superblocks[_superblockHash];
if (superblock.status != Status.New && superblock.status != Status.InBattle) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_STATUS);
return ERR_SUPERBLOCK_BAD_STATUS;
}
if(superblock.submitter == _challenger){
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_OWN_CHALLENGE);
return ERR_SUPERBLOCK_OWN_CHALLENGE;
}
superblock.status = Status.InBattle;
emit ChallengeSuperblock(_superblockHash, _challenger);
return ERR_SUPERBLOCK_OK;
}
// @dev - Semi-approve a challenged superblock
//
// A challenged superblock can be marked as semi-approved
// if it satisfies all the queries or when all challengers have
// stopped participating.
//
// @param _superblockHash Id of the superblock to semi-approve
// @param _validator Address requesting semi approval
// @return Error code and superblockHash
function semiApprove(bytes32 _superblockHash, address _validator) external returns (uint) {
if (msg.sender != trustedClaimManager) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_NOT_CLAIMMANAGER);
return ERR_SUPERBLOCK_NOT_CLAIMMANAGER;
}
SuperblockInfo storage superblock = superblocks[_superblockHash];
if (superblock.status != Status.InBattle && superblock.status != Status.New) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_STATUS);
return ERR_SUPERBLOCK_BAD_STATUS;
}
superblock.status = Status.SemiApproved;
emit SemiApprovedSuperblock(_superblockHash, _validator);
return ERR_SUPERBLOCK_OK;
}
// @dev - Invalidates a superblock
//
// A superblock with incorrect data can be invalidated immediately.
// Superblocks that are not in the main chain can be invalidated
// if not enough superblocks follow them, i.e. they don't have
// enough descendants.
//
// @param _superblockHash Id of the superblock to invalidate
// @param _validator Address requesting superblock invalidation
// @return Error code and superblockHash
function invalidate(bytes32 _superblockHash, address _validator) external returns (uint) {
if (msg.sender != trustedClaimManager) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_NOT_CLAIMMANAGER);
return ERR_SUPERBLOCK_NOT_CLAIMMANAGER;
}
SuperblockInfo storage superblock = superblocks[_superblockHash];
if (superblock.status != Status.InBattle && superblock.status != Status.SemiApproved) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_STATUS);
return ERR_SUPERBLOCK_BAD_STATUS;
}
superblock.status = Status.Invalid;
emit InvalidSuperblock(_superblockHash, _validator);
return ERR_SUPERBLOCK_OK;
}
// @dev - Verify TX SPV to Block proof as well as Block SPV proof to Superblock
// @param _txBytes - transaction bytes
// @param _txIndex - transaction's index within the block
// @param _txSiblings - transaction's Merkle siblings
// @param _syscoinBlockHeader - block header containing transaction
// @param _syscoinBlockIndex - block's index within superblock
// @param _syscoinBlockSiblings - block's merkle siblings
// @param _superblockHash - superblock containing block header
function verifySPVProofs(
bytes memory _syscoinBlockHeader,
uint _syscoinBlockIndex,
uint[] memory _syscoinBlockSiblings,
bytes32 _superblockHash,
bytes memory _txBytes,
uint _txIndex,
uint[] memory _txSiblings
) private returns (uint) {
// Check if Syscoin block belongs to given superblock
if (bytes32(computeMerkle(dblShaFlip(_syscoinBlockHeader), _syscoinBlockIndex, _syscoinBlockSiblings))
!= superblocks[_superblockHash].blocksMerkleRoot) {
// Syscoin block is not in superblock
emit VerifyTransaction(bytes32(0), ERR_SUPERBLOCK_MERKLE_ROOT);
return 0;
}
return verifyTx(_txBytes, _txIndex, _txSiblings, _syscoinBlockHeader, _superblockHash);
}
// @dev - relays transaction `_txBytes` to ERC20Manager's processTransaction() method.
// Also logs the value of processTransaction.
// Note: callers cannot be 100% certain when an ERR_RELAY_VERIFY occurs because
// it may also have been returned by processTransaction(). Callers should be
// aware of the contract that they are relaying transactions to and
// understand what that contract's processTransaction method returns.
//
// @param _txBytes - transaction bytes
// @param _txIndex - transaction's index within the block
// @param _txSiblings - transaction's Merkle siblings
// @param _syscoinBlockHeader - block header containing transaction
// @param _syscoinBlockIndex - block's index within superblock
// @param _syscoinBlockSiblings - block's merkle siblings
// @param _superblockHash - superblock containing block header
function relayTx(
bytes memory _txBytes,
uint _txIndex,
uint[] memory _txSiblings,
bytes memory _syscoinBlockHeader,
uint _syscoinBlockIndex,
uint[] memory _syscoinBlockSiblings,
bytes32 _superblockHash
) public returns (uint) {
uint txHash = verifySPVProofs(_syscoinBlockHeader, _syscoinBlockIndex, _syscoinBlockSiblings, _superblockHash, _txBytes, _txIndex, _txSiblings);
if (txHash != 0) {
uint value;
address destinationAddress;
uint ret;
uint32 assetGUID;
address erc20ContractAddress;
uint8 precision;
(ret, value, destinationAddress, assetGUID, precision, erc20ContractAddress) = parseBurnTx(_txBytes);
if(ret != 0){
emit RelayTransaction(bytes32(txHash), ret);
return ret;
}
syscoinERC20Manager.processTransaction(txHash, value, destinationAddress, superblocks[_superblockHash].submitter, erc20ContractAddress, assetGUID, precision);
return value;
}
emit RelayTransaction(bytes32(0), ERR_RELAY_VERIFY);
return(ERR_RELAY_VERIFY);
}
// @dev - relays asset transaction(new or update) `_txBytes` to ERC20Manager's processAsset() method.
// Also logs the value of processAsset.
// Note: callers cannot be 100% certain when an ERR_RELAY_VERIFY occurs because
// it may also have been returned by processAsset(). Callers should be
// aware of the contract that they are relaying transactions to and
// understand what that contract's processTransaction method returns.
//
// @param _txBytes - transaction bytes
// @param _txIndex - transaction's index within the block
// @param _txSiblings - transaction's Merkle siblings
// @param _syscoinBlockHeader - block header containing transaction
// @param _syscoinBlockIndex - block's index within superblock
// @param _syscoinBlockSiblings - block's merkle siblings
// @param _superblockHash - superblock containing block header
function relayAssetTx(
bytes memory _txBytes,
uint _txIndex,
uint[] memory _txSiblings,
bytes memory _syscoinBlockHeader,
uint _syscoinBlockIndex,
uint[] memory _syscoinBlockSiblings,
bytes32 _superblockHash
) public returns (uint) {
uint txHash = verifySPVProofs(_syscoinBlockHeader, _syscoinBlockIndex, _syscoinBlockSiblings, _superblockHash, _txBytes, _txIndex, _txSiblings);
if (txHash != 0) {
uint ret;
uint32 assetGUID;
address erc20ContractAddress;
(ret, assetGUID, erc20ContractAddress) = parseAssetTx(_txBytes);
if(ret != 0){
emit RelayTransaction(bytes32(txHash), ret);
return ret;
}
uint32 height = superblocks[_superblockHash].height*60;
height += uint32(_syscoinBlockIndex);
// pass in height of block as well by calc superblock sets of 60 blocks
syscoinERC20Manager.processAsset(txHash, assetGUID, height, erc20ContractAddress);
return 0;
}
emit RelayTransaction(bytes32(0), ERR_RELAY_VERIFY);
return(ERR_RELAY_VERIFY);
}
// Challenges a bridge cancellation request with SPV proofs linking tx to superblock and showing that a valid
// cancellation request exists. If challenge fails, the cancellation request continues until timeout at which point erc20 is refunded
//
// @param _txBytes - transaction bytes
// @param _txIndex - transaction's index within the block
// @param _txSiblings - transaction's Merkle siblings
// @param _syscoinBlockHeader - block header containing transaction
// @param _syscoinBlockIndex - block's index within superblock
// @param _syscoinBlockSiblings - block's merkle siblings
// @param _superblockHash - superblock containing block header
function challengeCancelTransfer(
bytes memory _txBytes,
uint _txIndex,
uint[] memory _txSiblings,
bytes memory _syscoinBlockHeader,
uint _syscoinBlockIndex,
uint[] memory _syscoinBlockSiblings,
bytes32 _superblockHash
) public returns (uint) {
uint txHash = verifySPVProofs(_syscoinBlockHeader, _syscoinBlockIndex, _syscoinBlockSiblings, _superblockHash, _txBytes, _txIndex, _txSiblings);
if (txHash != 0) {
uint32 bridgeTransferId;
uint ret;
(ret, bridgeTransferId) = parseMintTx(_txBytes);
if(ret != 0){
emit RelayTransaction(bytes32(txHash), ret);
return ret;
}
// check if cancellation request exists in valid state
// cancel cancellation request if challenger wins, challenger gets paid cancellors deposit
syscoinERC20Manager.processCancelTransferFail(bridgeTransferId, msg.sender);
return 0;
}
emit ChallengeCancelTransferRequest(ERR_CANCEL_TRANSFER_VERIFY);
return(ERR_CANCEL_TRANSFER_VERIFY);
}
// @dev - Parses a syscoin tx
//
// @param txBytes - tx byte array
// Outputs
// @return output_value - amount sent to the lock address in satoshis
// @return destinationAddress - ethereum destination address
function parseBurnTx(bytes memory txBytes)
public
pure
returns (uint, uint, address, uint32, uint8, address)
{
uint output_value;
uint32 assetGUID;
address destinationAddress;
uint32 version;
address erc20Address;
uint8 precision;
uint pos = 0;
version = bytesToUint32Flipped(txBytes, pos);
if(version != SYSCOIN_TX_VERSION_ALLOCATION_BURN_TO_ETHEREUM){
return (ERR_PARSE_TX_SYS, output_value, destinationAddress, assetGUID, precision, erc20Address);
}
pos = getOpReturnPos(txBytes, 4);
(output_value, destinationAddress, assetGUID, precision, erc20Address) = scanAssetDetails(txBytes, pos);
return (0, output_value, destinationAddress, assetGUID, precision, erc20Address);
}
function skipInputs(bytes memory txBytes, uint pos)
private
pure
returns (uint)
{
uint n_inputs;
uint script_len;
(n_inputs, pos) = parseVarInt(txBytes, pos);
// if dummy 0x00 is present this is a witness transaction
if(n_inputs == 0x00){
(n_inputs, pos) = parseVarInt(txBytes, pos); // flag
require(n_inputs != 0x00, "#SyscoinSuperblocks skipInputs(): Unexpected dummy/flag");
// after dummy/flag the real var int comes for txins
(n_inputs, pos) = parseVarInt(txBytes, pos);
}
require(n_inputs < 100, "#SyscoinSuperblocks skipInputs(): Incorrect size of n_inputs");
for (uint i = 0; i < n_inputs; i++) {
pos += 36; // skip outpoint
(script_len, pos) = parseVarInt(txBytes, pos);
pos += script_len + 4; // skip sig_script, seq
}
return pos;
}
// @dev - Checks whether the transaction given by `_txBytes` is in the block identified by `_txBlockHeaderBytes`.
// First it guards against a Merkle tree collision attack by raising an error if the transaction is exactly 64 bytes long,
// then it calls helperVerifyHash to do the actual check.
//
// @param _txBytes - transaction bytes
// @param _txIndex - transaction's index within the block
// @param _siblings - transaction's Merkle siblings
// @param _txBlockHeaderBytes - block header containing transaction
// @param _txsuperblockHash - superblock containing block header
// @return - SHA-256 hash of _txBytes if the transaction is in the block, 0 otherwise
function verifyTx(
bytes memory _txBytes,
uint _txIndex,
uint[] memory _siblings,
bytes memory _txBlockHeaderBytes,
bytes32 _txsuperblockHash
) private returns (uint) {
uint txHash = dblShaFlip(_txBytes);
if (_txBytes.length == 64) { // todo: is check 32 also needed?
emit VerifyTransaction(bytes32(txHash), ERR_TX_64BYTE);
return 0;
}
if (helperVerifyHash(txHash, _txIndex, _siblings, _txBlockHeaderBytes, _txsuperblockHash) == 1) {
return txHash;
} else {
// log is done via helperVerifyHash
return 0;
}
}
// @dev - Bitcoin-way of hashing
// @param _dataBytes - raw data to be hashed
// @return - result of applying SHA-256 twice to raw data and then flipping the bytes
function dblShaFlip(bytes memory _dataBytes) public pure returns (uint) {
return flip32Bytes(uint(sha256(abi.encodePacked(sha256(abi.encodePacked(_dataBytes))))));
}
// @dev - extract Merkle root field from a raw Syscoin block header
//
// @param _blockHeader - Syscoin block header bytes
// @param pos - where to start reading root from
// @return - block's Merkle root in big endian format
function getHeaderMerkleRoot(bytes memory _blockHeader) public pure returns (uint) {
uint merkle;
assembly {
merkle := mload(add(add(_blockHeader, 32), 0x24))
}
return flip32Bytes(merkle);
}
// @dev - Checks whether the transaction identified by `_txHash` is in the block identified by `_blockHeaderBytes`
// and whether the block is in the Syscoin main chain. Transaction check is done via Merkle proof.
// Note: no verification is performed to prevent txHash from just being an
// internal hash in the Merkle tree. Thus this helper method should NOT be used
// directly and is intended to be private.
//
// @param _txHash - transaction hash
// @param _txIndex - transaction's index within the block
// @param _siblings - transaction's Merkle siblings
// @param _blockHeaderBytes - block header containing transaction
// @param _txsuperblockHash - superblock containing block header
// @return - 1 if the transaction is in the block and the block is in the main chain,
// 20020 (ERR_CONFIRMATIONS) if the block is not in the main chain,
// 20050 (ERR_MERKLE_ROOT) if the block is in the main chain but the Merkle proof fails.
function helperVerifyHash(
uint256 _txHash,
uint _txIndex,
uint[] memory _siblings,
bytes memory _blockHeaderBytes,
bytes32 _txsuperblockHash
) private returns (uint) {
if (!isApproved(_txsuperblockHash)) {
emit VerifyTransaction(bytes32(_txHash), ERR_CHAIN);
return (ERR_CHAIN);
}
// Verify tx Merkle root
uint merkle = getHeaderMerkleRoot(_blockHeaderBytes);
if (computeMerkle(_txHash, _txIndex, _siblings) != merkle) {
emit VerifyTransaction(bytes32(_txHash), ERR_MERKLE_ROOT);
return (ERR_MERKLE_ROOT);
}
return (1);
}
// @dev - Calculate superblock hash from superblock data
//
// @param _blocksMerkleRoot Root of the merkle tree of blocks contained in a superblock
// @param _timestamp Timestamp of the last block in the superblock
// @param _mtpTimestamp Median Timestamp of the last block in the superblock
// @param _lastHash Hash of the last block in the superblock
// @param _lastBits Difficulty bits of the last block in the superblock bits
// @param _parentId Id of the parent superblock
// @return Superblock id
function calcSuperblockHash(
bytes32 _blocksMerkleRoot,
uint _timestamp,
uint _mtpTimestamp,
bytes32 _lastHash,
uint32 _lastBits,
bytes32 _parentId
) public pure returns (bytes32) {
return keccak256(abi.encodePacked(
_blocksMerkleRoot,
_timestamp,
_mtpTimestamp,
_lastHash,
_lastBits,
_parentId
));
}
// @dev - Returns the confirmed superblock with the most accumulated work
//
// @return Best superblock hash
function getBestSuperblock() external view returns (bytes32) {
return bestSuperblock;
}
// @dev - Returns the superblock data for the supplied superblock hash
//
function getSuperblock(bytes32 superblockHash) external view returns (
bytes32 _blocksMerkleRoot,
uint _timestamp,
uint _mtpTimestamp,
bytes32 _lastHash,
uint32 _lastBits,
bytes32 _parentId,
address _submitter,
Status _status,
uint32 _height
) {
SuperblockInfo storage superblock = superblocks[superblockHash];
return (
superblock.blocksMerkleRoot,
superblock.timestamp,
superblock.mtpTimestamp,
superblock.lastHash,
superblock.lastBits,
superblock.parentId,
superblock.submitter,
superblock.status,
superblock.height
);
}
// @dev - Returns superblock height
function getSuperblockHeight(bytes32 superblockHash) public view returns (uint32) {
return superblocks[superblockHash].height;
}
// @dev - Return superblock timestamp
function getSuperblockTimestamp(bytes32 _superblockHash) external view returns (uint) {
return superblocks[_superblockHash].timestamp;
}
// @dev - Return superblock median timestamp
function getSuperblockMedianTimestamp(bytes32 _superblockHash) external view returns (uint) {
return superblocks[_superblockHash].mtpTimestamp;
}
// @dev - Return superblock parent
function getSuperblockParentId(bytes32 _superblockHash) external view returns (bytes32) {
return superblocks[_superblockHash].parentId;
}
// @dev - Return superblock status
function getSuperblockStatus(bytes32 _superblockHash) public view returns (Status) {
return superblocks[_superblockHash].status;
}
function isApproved(bytes32 _superblockHash) private view returns (bool) {
return (getSuperblockStatus(_superblockHash) == Status.Approved);
}
function getChainHeight() public view returns (uint) {
return superblocks[bestSuperblock].height;
}
// @dev - return superblock hash at a given height in superblock main chain
//
// @param _height - superblock height
// @return - hash corresponding to block of height _height
function getSuperblockAt(uint _height) external view returns (bytes32) {
bytes32 superblockHash = bestSuperblock;
while (getSuperblockHeight(superblockHash) > _height) {
superblockHash = superblocks[superblockHash].parentId;
}
return superblockHash;
}
}
| - Confirm a proposed superblock An unchallenged superblock can be confirmed after a timeout. A challenged superblock is confirmed if it has enough descendants in the main chain. _superblockHash Id of the superblock to confirm _validator Address requesting superblock confirmation return Error code and superblockHash | function confirm(bytes32 _superblockHash, address _validator) external returns (uint) {
if (msg.sender != trustedClaimManager) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_NOT_CLAIMMANAGER);
return ERR_SUPERBLOCK_NOT_CLAIMMANAGER;
}
SuperblockInfo storage superblock = superblocks[_superblockHash];
if (superblock.status != Status.New && superblock.status != Status.SemiApproved) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_STATUS);
return ERR_SUPERBLOCK_BAD_STATUS;
}
if (superblock.height <= getChainHeight()) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_BLOCKHEIGHT);
return ERR_SUPERBLOCK_BAD_BLOCKHEIGHT;
}
SuperblockInfo storage parent = superblocks[superblock.parentId];
if (parent.status != Status.Approved) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_PARENT);
return ERR_SUPERBLOCK_BAD_PARENT;
}
superblock.status = Status.Approved;
bestSuperblock = _superblockHash;
emit ApprovedSuperblock(_superblockHash, _validator);
return ERR_SUPERBLOCK_OK;
}
| 6,418,216 |
./full_match/1/0xB0A1Cd3b31A8e3bbBaba15fEDdB88ABD932a677d/sources/contracts/mixins/nftMarket/NFTMarketBuyPrice.sol | Process the purchase of an NFT at the current buy price. The caller must confirm that the seller != address(0) before calling this function./ Remove the buy now price Cancel the buyer's offer if there is one in order to free up their FETH balance even if they don't need the FETH for this specific purchase. Transfer the NFT to the buyer. The seller was already authorized when the buyPrice was set originally set. Distribute revenue for this sale. | function _buy(address nftContract, uint256 tokenId, address payable referrer) private nonReentrant {
BuyPrice memory buyPrice = nftContractToTokenIdToBuyPrice[nftContract][tokenId];
delete nftContractToTokenIdToBuyPrice[nftContract][tokenId];
_cancelSendersOffer(nftContract, tokenId);
_tryUseFETHBalance(buyPrice.price, true);
address sender = _msgSender();
(
address payable sellerReferrerPaymentAddress,
uint16 sellerReferrerTakeRateInBasisPoints
) = _getExhibitionForPayment(nftContract, tokenId);
_transferFromEscrow(nftContract, tokenId, sender, address(0));
(uint256 totalFees, uint256 creatorRev, uint256 sellerRev) = _distributeFunds(
nftContract,
tokenId,
buyPrice.seller,
buyPrice.price,
referrer,
sellerReferrerPaymentAddress,
sellerReferrerTakeRateInBasisPoints
);
emit BuyPriceAccepted(nftContract, tokenId, buyPrice.seller, sender, totalFees, creatorRev, sellerRev);
}
| 8,356,976 |
./partial_match/1/0xf67afd75433fCcca272c3373592B4a082A7b9f77/sources/MarketUtilityV2_1.sol | Calculate the option price for given params params 0 _option 1 neutralMinValue 2 neutralMaxValue 3 startTime 4 expireTime 5 totalStakedETH 6 totalStakedToken 7 ethStakedOnOption 8 plotStakedOnOption/ | function calculateOptionPrice(uint[] memory params, address marketFeedAddress) public view returns(uint _optionPrice) {
uint _totalStaked = params[5].add(getAssetValueETH(plotToken, params[6]));
uint _assetStakedOnOption = params[7]
.add(
(getAssetValueETH(plotToken, params[8])));
_optionPrice = 0;
uint currentPriceOption = 0;
uint256 currentPrice = getAssetPriceUSD(
marketFeedAddress
);
uint stakeWeightage = STAKE_WEIGHTAGE;
uint predictionWeightage = 100 - stakeWeightage;
uint predictionTime = params[4].sub(params[3]);
uint minTimeElapsed = (predictionTime).div(minTimeElapsedDivisor);
if(now > params[4]) {
return 0;
}
if(_totalStaked > STAKE_WEIGHTAGE_MIN_AMOUNT) {
_optionPrice = (_assetStakedOnOption).mul(1000000).div(_totalStaked.mul(stakeWeightage));
}
uint maxDistance;
if(currentPrice < params[1]) {
currentPriceOption = 1;
maxDistance = 2;
currentPriceOption = 3;
maxDistance = 2;
currentPriceOption = 2;
maxDistance = 1;
}
uint distance = _getAbsoluteDifference(currentPriceOption, params[0]);
uint timeElapsed = now > params[3] ? now.sub(params[3]) : 0;
timeElapsed = timeElapsed > minTimeElapsed ? timeElapsed: minTimeElapsed;
_optionPrice = _optionPrice.add((((maxDistance+1).sub(distance)).mul(1000000).mul(timeElapsed)).div((maxDistance+1).mul(predictionWeightage).mul(predictionTime)));
_optionPrice = _optionPrice.div(100);
} else if(currentPrice > params[2]) {
} else {
}
| 2,884,592 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./TestFramework.sol";
contract TestCrowdfunding {
event PrintEvent(string msg);
// Adjust this to change the test code's initial balance
uint public initialBalance = 100000000 wei;
uint256 constant public investorInitialBalance = 10000 wei;
MockTimer private timer;
Crowdfunding private crowdfunding;
FounderCrowdfunding private CrowdfundingCreator;
Investor private alice;
Investor private bob;
//can receive money
receive() external payable {}
fallback() external payable {}
constructor() {}
function setupContracts() public {
timer = new MockTimer(0);
CrowdfundingCreator = new FounderCrowdfunding();
crowdfunding = new Crowdfunding(
address(CrowdfundingCreator),
timer,
1000 wei, // 1000 wei
10 // at day 10
);
CrowdfundingCreator.setCrowdfunding(crowdfunding);
bob = createInvestor(crowdfunding);
alice = createInvestor(crowdfunding);
}
function createInvestor(Crowdfunding _crowdfunding) internal returns (Investor) {
Investor investor = new Investor(_crowdfunding);
payable(investor).transfer(investorInitialBalance);
return investor;
}
modifier setup {
setupContracts();
_;
}
function testCreateCrowdfundingContracts() public{}
// Investments tests
function testInvest() public setup {
timer.setTime(2); // Still not finished
Assert.isTrue(bob.invest(100 wei), "Valid investment should pass.");
Assert.isTrue(address(bob).balance == investorInitialBalance - 100 wei, "Investor balance should be reduced by investment value.");
Assert.isTrue(crowdfunding.investments(address(bob)) == 100 wei, "All investments should be there");
}
function testInvestAfterEnd() public setup {
timer.setTime(20); // Finished
Assert.isFalse(bob.invest(100 wei), "Investment should not be made after crowdfunding has finished.");
Assert.isTrue(address(bob).balance == investorInitialBalance, "Investor should have all of its funds.");
}
function testInvestMultipleTimes() public setup {
bob.invest(100 wei);
bob.invest(100 wei);
bob.invest(100 wei);
Assert.isTrue(address(bob).balance == investorInitialBalance - 300 wei, "Investor should be able to invest multiple times.");
Assert.isTrue(crowdfunding.investments(address(bob)) == 300 wei, "All investments should be there");
}
// Claim tests
function testClaimWhenGoalNotReachedAndNotFinished() public setup {
timer.setTime(2); // Still not finished
require(bob.invest(100 wei), "Investor must be able to invest");
require(alice.invest(100 wei), "Investor must be able to invest");
Assert.isFalse(CrowdfundingCreator.claimFunds(), "Investments claim should not be able before campaign is active.");
Assert.isTrue(address(CrowdfundingCreator).balance == 0, "No investments should be claimed.");
}
function testClaimWhenGoalNotReachedAndFinished() public setup { // Claim not possible
require(bob.invest(100 wei), "Investor must be able to invest");
require(alice.invest(100 wei), "Investor must be able to invest");
timer.setTime(20); // Finished
Assert.isFalse(CrowdfundingCreator.claimFunds(), "Can not claim funds when goal not reached.");
Assert.isTrue(address(CrowdfundingCreator).balance == 0, "No investments should be claimed.");
}
function testNonOwnerClaimWhenGoalReachedAndFinished() public setup { // Claim not possible
require(bob.invest(500 wei));
require(alice.invest(500 wei)); // Goal Reached
timer.setTime(20); // Finished
Assert.isFalse(bob.claimFunds(), "Non Owner can not claim funds.");
Assert.isTrue(address(bob).balance == investorInitialBalance - 500 wei, "Funds should not be claimed.");
Assert.isTrue(address(crowdfunding).balance == 1000 wei, "Funds should not be claimed.");
}
function testClaimWhenGoalReachedAndNotFinished() public setup { // Claim not possible
require(bob.invest(500 wei));
require(alice.invest(500 wei)); // Goal Reached
timer.setTime(5); // Finished
Assert.isFalse(CrowdfundingCreator.claimFunds(), "Investments claim should not be able before campaign is active.");
Assert.isTrue(address(CrowdfundingCreator).balance == 0, "No investments should be claimed.");
}
function testClaimWhenGoalReachedAndFinished() public setup { // Claim possible
require(bob.invest(500 wei));
require(alice.invest(500 wei)); // Goal Reached
timer.setTime(20); // Finished
Assert.isTrue(CrowdfundingCreator.claimFunds(), "Crowdfunding creator should be able to claim funds.");
Assert.isTrue(address(CrowdfundingCreator).balance == 1000, "Funds should be claimed");
Assert.isTrue(address(crowdfunding).balance == 0, "No funds should be a part of crowdfunding after they were claimed.");
}
// Refund tests
function testRefundGoalNotReachedAndNotFinished() public setup { // Refund not possible
timer.setTime(2); // Still not finished
Assert.isTrue(bob.invest(100 wei), "Investor must be able to invest.");
Assert.isFalse(bob.refund(), "Investor should not be able to refund before campaign finish.");
Assert.isTrue(address(bob).balance == investorInitialBalance - 100 wei, "Investor shouldn't be able to get refund.");
}
function testRefundWhenGoalReachedButNotFinished() public setup { // Refund not possible
bob.invest(500 wei);
alice.invest(500 wei);
timer.setTime(5); // Not yet finished
Assert.isFalse(bob.refund(), "Investor should not be able to refund before campaign finish and goal reached.");
Assert.isTrue(address(bob).balance == investorInitialBalance - 500 wei, "Investor shouldn't be able to get refund.");
Assert.isFalse(alice.refund(), "Investor should not be able to refund before campaign finish and goal reached.");
Assert.isTrue(address(alice).balance == investorInitialBalance - 500 wei, "Investor shouldn't be able to get refund.");
}
function testRefundWhenGoalNotReachedButFinished() public setup { // Refund possible
bob.invest(500 wei); // Goal not reached
timer.setTime(20); // Not yet finished
Assert.isTrue(bob.refund(), "Investor must be able to refund if goal not reached.");
Assert.isTrue(address(bob).balance == investorInitialBalance, "Investor should be refunded.");
}
function testRefundWhenGoalReachedAndFinished() public setup { // Refund not possible
bob.invest(500 wei);
alice.invest(500 wei);
timer.setTime(20); // Passed
Assert.isFalse(bob.refund(), "Investor should not be able to refund before campaign finish and goal reached.");
Assert.isTrue(address(bob).balance == investorInitialBalance - 500 wei, "Investor shouldn't be able to get refund.");
Assert.isFalse(alice.refund(), "Investor should not be able to refund before campaign finish and goal reached.");
Assert.isTrue(address(alice).balance == investorInitialBalance - 500 wei, "Investor shouldn't be able to get refund.");
}
} | Claim not possible | function testClaimWhenGoalNotReachedAndFinished() public setup { | 5,398,216 |
./full_match/1/0x5bC926B2A5FcF521B7d1cfD4d0BC265eF00AB2F1/sources/contracts/strategies/aps/curve/convex/stakingFraxbp/StakingFraxCurveConvexApsStratBaseV2.sol | Returns true if withdraw success and false if fail. Withdraw failed when user removingCrvLps < requiredCrvLPs (wrong minAmounts) return Returns true if withdraw success and false if fail. withdrawer - address of user that deposit funds userRatioOfCrvLps - user's Ratio of ZLP for withdraw tokenAmount - amount of stablecoin that user want minimum receive/ | function withdraw(
address withdrawer,
uint256 tokenAmount
) external virtual onlyZunami returns (bool) {
require(userRatioOfCrvLps > 0 && userRatioOfCrvLps <= 1e18, 'Wrong lp Ratio');
(bool success, uint256 removingCrvLps) = calcCrvLps(
userRatioOfCrvLps,
tokenAmount
);
if (!success) {
return false;
}
uint256 prevBalance = _config.token.balanceOf(address(this));
removeCrvLps(removingCrvLps, tokenAmount);
transferAllTokensOut(withdrawer, prevBalance);
return true;
}
| 2,921,777 |
./full_match/1/0x402993515350c973f1D44FC8762644E3806cB9bC/sources/contracts/token/TokenUtils.sol | Returns the address of the WNT token. dataStore DataStore contract instance where the address of the WNT token is stored. return The address of the WNT token./ | function wnt(DataStore dataStore) internal view returns (address) {
return dataStore.getAddress(Keys.WNT);
}
| 16,543,059 |
./full_match/23295/0xFfdb1c4aCe237B10ef5Bd83ec2e6E24D2784225c/sources/contracts/Riddle.sol | Register new coupon for the riddle associated with the private key. | function addCoupon(string memory coupon, string memory privKey) external {
require(_owner == msg.sender, errForbidden);
require(_coupons[coupon] == 0, errCouponExists);
_awardedPrivKeys.push(false);
_privKeys.push(privKey);
_coupons[coupon] = _privKeys.length;
}
| 7,103,290 |
./full_match/1/0x0bC24E61DAAd6293A1b3b53a7D01086BfF0Ea6e5/sources/contracts/FeeManager/FeeManagerHelper.sol | Updates bad debt of a postion. Combines preparation of all collaterals and borrows for passed _nftId with _updateUserBadDebt()./ | function updatePositionCurrentBadDebt(
uint256 _nftId
)
public
{
_prepareCollaterals(
_nftId
);
_prepareBorrows(
_nftId
);
_updateUserBadDebt(
_nftId
);
}
| 4,818,635 |
./partial_match/5/0xA109b34B1974C1f6BA554607F46E202926728E14/sources/src/utils/DoubleLinkedList.sol | Returns the tail item id of the list list Linked list which contains the item return _ Id of the tail item | function getTail(List storage list) internal view returns (uint256) {
return list.items[0].prev;
}
| 16,850,997 |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity =0.8.13 >=0.8.0;
////// src/interfaces/IJob.sol
// Copyright (C) 2021 Dai Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
/* pragma solidity >=0.8.0; */
/// @title Maker Keeper Network Job
/// @notice A job represents an independant unit of work that can be done by a keeper
interface IJob {
/// @notice Executes this unit of work
/// @dev Should revert iff workable() returns canWork of false
/// @param network The name of the external keeper network
/// @param args Custom arguments supplied to the job, should be copied from workable response
function work(bytes32 network, bytes calldata args) external;
/// @notice Ask this job if it has a unit of work available
/// @dev This should never revert, only return false if nothing is available
/// @dev This should normally be a view, but sometimes that's not possible
/// @param network The name of the external keeper network
/// @return canWork Returns true if a unit of work is available
/// @return args The custom arguments to be provided to work() or an error string if canWork is false
function workable(bytes32 network) external returns (bool canWork, bytes memory args);
}
////// src/ClipperMomJob.sol
// Copyright (C) 2022 Dai Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
/* pragma solidity 0.8.13; */
/* import {IJob} from "./interfaces/IJob.sol"; */
interface SequencerLike_3 {
function isMaster(bytes32 network) external view returns (bool);
}
interface IlkRegistryLike_2 {
function list() external view returns (bytes32[] memory);
function info(bytes32 ilk) external view returns (
string memory name,
string memory symbol,
uint256 class,
uint256 dec,
address gem,
address pip,
address join,
address xlip
);
}
interface ClipperMomLike {
function tripBreaker(address clip) external;
}
/// @title Will trigger a clipper to shutdown if oracle price drops too quickly
contract ClipperMomJob is IJob {
SequencerLike_3 public immutable sequencer;
IlkRegistryLike_2 public immutable ilkRegistry;
ClipperMomLike public immutable clipperMom;
// --- Errors ---
error NotMaster(bytes32 network);
// --- Events ---
event Work(bytes32 indexed network, address indexed clip);
constructor(address _sequencer, address _ilkRegistry, address _clipperMom) {
sequencer = SequencerLike_3(_sequencer);
ilkRegistry = IlkRegistryLike_2(_ilkRegistry);
clipperMom = ClipperMomLike(_clipperMom);
}
function work(bytes32 network, bytes calldata args) external override {
if (!sequencer.isMaster(network)) revert NotMaster(network);
address clip = abi.decode(args, (address));
clipperMom.tripBreaker(clip);
emit Work(network, clip);
}
function workable(bytes32 network) external override returns (bool, bytes memory) {
if (!sequencer.isMaster(network)) return (false, bytes("Network is not master"));
bytes32[] memory ilks = ilkRegistry.list();
for (uint256 i = 0; i < ilks.length; i++) {
(,, uint256 class,,,,, address clip) = ilkRegistry.info(ilks[i]);
if (class != 1) continue;
if (clip == address(0)) continue;
// We cannot retrieve oracle prices (whitelist-only), so we have to just try and run the trip breaker
try clipperMom.tripBreaker(clip) {
// Found a valid trip
return (true, abi.encode(clip));
} catch {
// No valid trip -- carry on
}
}
return (false, bytes("No ilks ready"));
}
} | We cannot retrieve oracle prices (whitelist-only), so we have to just try and run the trip breaker Found a valid trip No valid trip -- carry on | function workable(bytes32 network) external override returns (bool, bytes memory) {
if (!sequencer.isMaster(network)) return (false, bytes("Network is not master"));
bytes32[] memory ilks = ilkRegistry.list();
for (uint256 i = 0; i < ilks.length; i++) {
(,, uint256 class,,,,, address clip) = ilkRegistry.info(ilks[i]);
if (class != 1) continue;
if (clip == address(0)) continue;
try clipperMom.tripBreaker(clip) {
return (true, abi.encode(clip));
}
}
return (false, bytes("No ilks ready"));
}
| 6,856,647 |
./full_match/80001/0x4319Eb408B6eA5f7D776E90401e9D6e6e26b4B66/sources/contracts/SkyGenerator.sol | function getLayer(string memory content, string memory style, string memory class) external view returns (string memory layer); | interface ISvgUtilsGenerator {
function getSvg( string memory content, string memory style) external view returns (string memory svg);
function getSymbol(string memory content, string memory class, string memory id ) external pure returns (string memory symbol);
function getGradient(string memory id, string[5] memory colors, string memory x1, string memory x2, string memory y1, string memory y2 ) external view returns (string memory);
}
| 5,592,237 |
/**
*Submitted for verification at Etherscan.io on 2020-01-30
*/
// File: contracts/math/SafeMath.sol
pragma solidity 0.5.12;
/// @title SafeMath
/// @dev Math operations with safety checks that throw on error
library SafeMath {
/// @dev Add two integers
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
//assert(c >= a);
return c;
}
/// @dev Subtract two integers
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
/// @dev Multiply tow integers
function mul(uint a, uint b) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
assert(c / a == b);
return c;
}
/// @dev Floor divide two integers
function div(uint a, uint b) internal pure returns (uint) {
return a / b;
}
}
// File: contracts/ownership/Ownable.sol
pragma solidity 0.5.12;
/// @title Ownable
/// @dev Provide a simple access control with a single authority: the owner
contract Ownable {
// Ethereum address of current owner
address public owner;
// Ethereum address of the next owner
// (has to claim ownership first to become effective owner)
address public newOwner;
// @dev Log event on ownership transferred
// @param previousOwner Ethereum address of previous owner
// @param newOwner Ethereum address of new owner
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/// @dev Forbid call by anyone but owner
modifier onlyOwner() {
require(msg.sender == owner, "Restricted to owner");
_;
}
/// @dev Deployer account becomes initial owner
constructor() public {
owner = msg.sender;
}
/// @dev Transfer ownership to a new Ethereum account (safe method)
/// Note: the new owner has to claim his ownership to become effective owner.
/// @param _newOwner Ethereum address to transfer ownership to
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0x0), "New owner is zero");
newOwner = _newOwner;
}
/// @dev Transfer ownership to a new Ethereum account (unsafe method)
/// Note: It's strongly recommended to use the safe variant via transferOwnership
/// and claimOwnership, to prevent accidental transfers to a wrong address.
/// @param _newOwner Ethereum address to transfer ownership to
function transferOwnershipUnsafe(address _newOwner) public onlyOwner {
require(_newOwner != address(0x0), "New owner is zero");
_transferOwnership(_newOwner);
}
/// @dev Become effective owner (if dedicated so by previous owner)
function claimOwnership() public {
require(msg.sender == newOwner, "Restricted to new owner");
_transferOwnership(msg.sender);
}
/// @dev Transfer ownership (internal method)
/// @param _newOwner Ethereum address to transfer ownership to
function _transferOwnership(address _newOwner) private {
if (_newOwner != owner) {
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
newOwner = address(0x0);
}
}
// File: contracts/whitelist/Whitelist.sol
pragma solidity 0.5.12;
/// @title Whitelist
/// @author STOKR
contract Whitelist is Ownable {
// Set of admins
mapping(address => bool) public admins;
// Set of Whitelisted addresses
mapping(address => bool) public isWhitelisted;
/// @dev Log entry on admin added to set
/// @param admin An Ethereum address
event AdminAdded(address indexed admin);
/// @dev Log entry on admin removed from set
/// @param admin An Ethereum address
event AdminRemoved(address indexed admin);
/// @dev Log entry on investor added set
/// @param admin An Ethereum address
/// @param investor An Ethereum address
event InvestorAdded(address indexed admin, address indexed investor);
/// @dev Log entry on investor removed from set
/// @param admin An Ethereum address
/// @param investor An Ethereum address
event InvestorRemoved(address indexed admin, address indexed investor);
/// @dev Only admin
modifier onlyAdmin() {
require(admins[msg.sender], "Restricted to whitelist admin");
_;
}
/// @dev Add admin to set
/// @param _admin An Ethereum address
function addAdmin(address _admin) public onlyOwner {
require(_admin != address(0x0), "Whitelist admin is zero");
if (!admins[_admin]) {
admins[_admin] = true;
emit AdminAdded(_admin);
}
}
/// @dev Remove admin from set
/// @param _admin An Ethereum address
function removeAdmin(address _admin) public onlyOwner {
require(_admin != address(0x0), "Whitelist admin is zero"); // Necessary?
if (admins[_admin]) {
admins[_admin] = false;
emit AdminRemoved(_admin);
}
}
/// @dev Add investor to set of whitelisted addresses
/// @param _investors A list where each entry is an Ethereum address
function addToWhitelist(address[] calldata _investors) external onlyAdmin {
for (uint256 i = 0; i < _investors.length; i++) {
if (!isWhitelisted[_investors[i]]) {
isWhitelisted[_investors[i]] = true;
emit InvestorAdded(msg.sender, _investors[i]);
}
}
}
/// @dev Remove investor from set of whitelisted addresses
/// @param _investors A list where each entry is an Ethereum address
function removeFromWhitelist(address[] calldata _investors) external onlyAdmin {
for (uint256 i = 0; i < _investors.length; i++) {
if (isWhitelisted[_investors[i]]) {
isWhitelisted[_investors[i]] = false;
emit InvestorRemoved(msg.sender, _investors[i]);
}
}
}
}
// File: contracts/whitelist/Whitelisted.sol
pragma solidity 0.5.12;
/// @title Whitelisted
/// @author STOKR
contract Whitelisted is Ownable {
Whitelist public whitelist;
/// @dev Log entry on change of whitelist contract instance
/// @param previous Ethereum address of previous whitelist
/// @param current Ethereum address of new whitelist
event WhitelistChange(address indexed previous, address indexed current);
/// @dev Ensure only whitelisted addresses can call
modifier onlyWhitelisted(address _address) {
require(whitelist.isWhitelisted(_address), "Address is not whitelisted");
_;
}
/// @dev Constructor
/// @param _whitelist address of whitelist contract
constructor(Whitelist _whitelist) public {
setWhitelist(_whitelist);
}
/// @dev Set the address of whitelist
/// @param _newWhitelist An Ethereum address
function setWhitelist(Whitelist _newWhitelist) public onlyOwner {
require(address(_newWhitelist) != address(0x0), "Whitelist address is zero");
if (address(_newWhitelist) != address(whitelist)) {
emit WhitelistChange(address(whitelist), address(_newWhitelist));
whitelist = Whitelist(_newWhitelist);
}
}
}
// File: contracts/token/ERC20.sol
pragma solidity 0.5.12;
/// @title ERC20 interface
/// @dev see https://github.com/ethereum/EIPs/issues/20
interface ERC20 {
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
function totalSupply() external view returns (uint);
function balanceOf(address _owner) external view returns (uint);
function allowance(address _owner, address _spender) external view returns (uint);
function approve(address _spender, uint _value) external returns (bool);
function transfer(address _to, uint _value) external returns (bool);
function transferFrom(address _from, address _to, uint _value) external returns (bool);
}
// File: contracts/token/ProfitSharing.sol
pragma solidity 0.5.12;
/// @title ProfitSharing
/// @author STOKR
contract ProfitSharing is Ownable {
using SafeMath for uint;
// An InvestorAccount object keeps track of the investor's
// - balance: amount of tokens he/she holds (always up-to-date)
// - profitShare: amount of wei this token owed him/her at the last update
// - lastTotalProfits: determines when his/her profitShare was updated
// Note, this construction requires:
// - totalProfits to never decrease
// - totalSupply to be fixed
// - profitShare of all involved parties to get updated prior to any token transfer
// - lastTotalProfits to be set to current totalProfits upon profitShare update
struct InvestorAccount {
uint balance; // token balance
uint lastTotalProfits; // totalProfits [wei] at the time of last profit share update
uint profitShare; // profit share [wei] of last update
}
// Investor account database
mapping(address => InvestorAccount) public accounts;
// Authority who is allowed to deposit profits [wei] on this
address public profitDepositor;
// Authority who is allowed to distribute profit shares [wei] to investors
// (so, that they don't need to withdraw it by themselves)
address public profitDistributor;
// Amount of total profits [wei] stored to this token
// In contrast to the wei balance (which may be reduced due to profit share withdrawal)
// this value will never decrease
uint public totalProfits;
// As long as the total supply isn't fixed, i.e. new tokens can appear out of thin air,
// the investors' profit shares aren't determined
bool public totalSupplyIsFixed;
// Total amount of tokens
uint internal totalSupply_;
/// @dev Log entry on change of profit deposit authority
/// @param previous Ethereum address of previous profit depositor
/// @param current Ethereum address of new profit depositor
event ProfitDepositorChange(
address indexed previous,
address indexed current
);
/// @dev Log entry on change of profit distribution authority
/// @param previous Ethereum address of previous profit distributor
/// @param current Ethereum address of new profit distributor
event ProfitDistributorChange(
address indexed previous,
address indexed current
);
/// @dev Log entry on profit deposit
/// @param depositor Profit depositor's address
/// @param amount Deposited profits in wei
event ProfitDeposit(
address indexed depositor,
uint amount
);
/// @dev Log entry on profit share update
/// @param investor Investor's address
/// @param amount New wei amount the token owes the investor
event ProfitShareUpdate(
address indexed investor,
uint amount
);
/// @dev Log entry on profit withdrawal
/// @param investor Investor's address
/// @param amount Wei amount the investor withdrew from this token
event ProfitShareWithdrawal(
address indexed investor,
address indexed beneficiary,
uint amount
);
/// @dev Restrict operation to profit deposit authority only
modifier onlyProfitDepositor() {
require(msg.sender == profitDepositor, "Restricted to profit depositor");
_;
}
/// @dev Restrict operation to profit distribution authority only
modifier onlyProfitDistributor() {
require(msg.sender == profitDistributor, "Restricted to profit distributor");
_;
}
/// @dev Restrict operation to when total supply doesn't change anymore
modifier onlyWhenTotalSupplyIsFixed() {
require(totalSupplyIsFixed, "Total supply may change");
_;
}
/// @dev Constructor
/// @param _profitDepositor Profit deposit authority
constructor(address _profitDepositor, address _profitDistributor) public {
setProfitDepositor(_profitDepositor);
setProfitDistributor(_profitDistributor);
}
/// @dev Profit deposit if possible via fallback function
function () external payable {
require(msg.data.length == 0, "Fallback call with data");
depositProfit();
}
/// @dev Change profit depositor
/// @param _newProfitDepositor An Ethereum address
function setProfitDepositor(address _newProfitDepositor) public onlyOwner {
require(_newProfitDepositor != address(0x0), "New profit depositor is zero");
if (_newProfitDepositor != profitDepositor) {
emit ProfitDepositorChange(profitDepositor, _newProfitDepositor);
profitDepositor = _newProfitDepositor;
}
}
/// @dev Change profit distributor
/// @param _newProfitDistributor An Ethereum address
function setProfitDistributor(address _newProfitDistributor) public onlyOwner {
require(_newProfitDistributor != address(0x0), "New profit distributor is zero");
if (_newProfitDistributor != profitDistributor) {
emit ProfitDistributorChange(profitDistributor, _newProfitDistributor);
profitDistributor = _newProfitDistributor;
}
}
/// @dev Deposit profit
function depositProfit() public payable onlyProfitDepositor onlyWhenTotalSupplyIsFixed {
require(totalSupply_ > 0, "Total supply is zero");
totalProfits = totalProfits.add(msg.value);
emit ProfitDeposit(msg.sender, msg.value);
}
/// @dev Profit share owing
/// @param _investor An Ethereum address
/// @return A positive number
function profitShareOwing(address _investor) public view returns (uint) {
if (!totalSupplyIsFixed || totalSupply_ == 0) {
return 0;
}
InvestorAccount memory account = accounts[_investor];
return totalProfits.sub(account.lastTotalProfits)
.mul(account.balance)
.div(totalSupply_)
.add(account.profitShare);
}
/// @dev Update profit share
/// @param _investor An Ethereum address
function updateProfitShare(address _investor) public onlyWhenTotalSupplyIsFixed {
uint newProfitShare = profitShareOwing(_investor);
accounts[_investor].lastTotalProfits = totalProfits;
accounts[_investor].profitShare = newProfitShare;
emit ProfitShareUpdate(_investor, newProfitShare);
}
/// @dev Withdraw profit share
function withdrawProfitShare() public {
_withdrawProfitShare(msg.sender, msg.sender);
}
function withdrawProfitShareTo(address payable _beneficiary) public {
_withdrawProfitShare(msg.sender, _beneficiary);
}
/// @dev Withdraw profit share
function withdrawProfitShares(address payable[] calldata _investors)
external
onlyProfitDistributor
{
for (uint i = 0; i < _investors.length; ++i) {
_withdrawProfitShare(_investors[i], _investors[i]);
}
}
/// @dev Withdraw profit share
function _withdrawProfitShare(address _investor, address payable _beneficiary) internal {
updateProfitShare(_investor);
uint withdrawnProfitShare = accounts[_investor].profitShare;
accounts[_investor].profitShare = 0;
_beneficiary.transfer(withdrawnProfitShare);
emit ProfitShareWithdrawal(_investor, _beneficiary, withdrawnProfitShare);
}
}
// File: contracts/token/MintableToken.sol
pragma solidity 0.5.12;
/// @title MintableToken
/// @author STOKR
/// @dev Extension of the ERC20 compliant ProfitSharing Token
/// that allows the creation of tokens via minting for a
/// limited time period (until minting gets finished).
contract MintableToken is ERC20, ProfitSharing, Whitelisted {
address public minter;
uint public numberOfInvestors = 0;
/// @dev Log entry on mint
/// @param to Beneficiary who received the newly minted tokens
/// @param amount The amount of minted token units
event Minted(address indexed to, uint amount);
/// @dev Log entry on mint finished
event MintFinished();
/// @dev Restrict an operation to be callable only by the minter
modifier onlyMinter() {
require(msg.sender == minter, "Restricted to minter");
_;
}
/// @dev Restrict an operation to be executable only while minting was not finished
modifier canMint() {
require(!totalSupplyIsFixed, "Total supply has been fixed");
_;
}
/// @dev Set minter authority
/// @param _minter Ethereum address of minter authority
function setMinter(address _minter) public onlyOwner {
require(minter == address(0x0), "Minter has already been set");
require(_minter != address(0x0), "Minter is zero");
minter = _minter;
}
/// @dev Mint tokens, i.e. create tokens out of thin air
/// @param _to Beneficiary who will receive the newly minted tokens
/// @param _amount The amount of minted token units
function mint(address _to, uint _amount) public onlyMinter canMint onlyWhitelisted(_to) {
if (accounts[_to].balance == 0) {
numberOfInvestors++;
}
totalSupply_ = totalSupply_.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
accounts[_to].balance = accounts[_to].balance.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
emit Minted(_to, _amount);
emit Transfer(address(0x0), _to, _amount);
}
/// @dev Finish minting -- this should be irreversible
function finishMinting() public onlyMinter canMint {
totalSupplyIsFixed = true;
emit MintFinished();
}
}
// File: contracts/crowdsale/RateSourceInterface.sol
pragma solidity 0.5.12;
/// @title RateSource
/// @author STOKR
interface RateSource {
/// @dev The current price of an Ether in EUR cents
/// @return Current ether rate
function etherRate() external view returns (uint);
}
// File: contracts/crowdsale/MintingCrowdsale.sol
pragma solidity 0.5.12;
/// @title MintingCrowdsale
/// @author STOKR
contract MintingCrowdsale is Ownable {
using SafeMath for uint;
// Maximum Time of offering period after extension
uint constant MAXOFFERINGPERIOD = 80 days;
// Ether rate oracle contract providing the price of an Ether in EUR cents
RateSource public rateSource;
// The token to be sold
// In the following, the term "token unit" always refers to the smallest
// and non-divisible quantum. Thus, token unit amounts are always integers.
// One token is expected to consist of 10^18 token units.
MintableToken public token;
// Token amounts in token units
// The public and the private sale are both capped (i.e. two distinct token pools)
// The tokenRemaining variables keep track of how many token units are available
// for the respective type of sale
uint public tokenCapOfPublicSale;
uint public tokenCapOfPrivateSale;
uint public tokenRemainingForPublicSale;
uint public tokenRemainingForPrivateSale;
// Prices are in Euro cents (i.e. 1/100 EUR)
uint public tokenPrice;
// The minimum amount of tokens a purchaser has to buy via one transaction
uint public tokenPurchaseMinimum;
// The maximum total amount of tokens a purchaser may buy during start phase
uint public tokenPurchaseLimit;
// Total token purchased by investor (while purchase amount is limited)
mapping(address => uint) public tokenPurchased;
// Public sale period
uint public openingTime;
uint public closingTime;
uint public limitEndTime;
// Ethereum address where invested funds will be transferred to
address payable public companyWallet;
// Amount and receiver of reserved tokens
uint public tokenReservePerMill;
address public reserveAccount;
// Wether this crowdsale was finalized or not
bool public isFinalized = false;
/// @dev Log entry upon token distribution event
/// @param beneficiary Ethereum address of token recipient
/// @param amount Number of token units
/// @param isPublicSale Whether the distribution was via public sale
event TokenDistribution(address indexed beneficiary, uint amount, bool isPublicSale);
/// @dev Log entry upon token purchase event
/// @param buyer Ethereum address of token purchaser
/// @param value Worth in wei of purchased token amount
/// @param amount Number of token units
event TokenPurchase(address indexed buyer, uint value, uint amount);
/// @dev Log entry upon rate change event
/// @param previous Previous closing time of sale
/// @param current Current closing time of sale
event ClosingTimeChange(uint previous, uint current);
/// @dev Log entry upon finalization event
event Finalization();
/// @dev Constructor
/// @param _rateSource Ether rate oracle contract
/// @param _token The token to be sold
/// @param _tokenCapOfPublicSale Maximum number of token units to mint in public sale
/// @param _tokenCapOfPrivateSale Maximum number of token units to mint in private sale
/// @param _tokenPurchaseMinimum Minimum amount of tokens an investor has to buy at once
/// @param _tokenPurchaseLimit Maximum total token amounts individually buyable in limit phase
/// @param _tokenPrice Price of a token in EUR cent
/// @param _openingTime Block (Unix) timestamp of sale opening time
/// @param _closingTime Block (Unix) timestamp of sale closing time
/// @param _limitEndTime Block (Unix) timestamp until token purchases are limited
/// @param _companyWallet Ethereum account who will receive sent ether
/// @param _tokenReservePerMill Per mill amount of sold tokens to mint for reserve account
/// @param _reserveAccount Ethereum address of reserve tokens recipient
constructor(
RateSource _rateSource,
MintableToken _token,
uint _tokenCapOfPublicSale,
uint _tokenCapOfPrivateSale,
uint _tokenPurchaseMinimum,
uint _tokenPurchaseLimit,
uint _tokenReservePerMill,
uint _tokenPrice,
uint _openingTime,
uint _closingTime,
uint _limitEndTime,
address payable _companyWallet,
address _reserveAccount
)
public
{
require(address(_rateSource) != address(0x0), "Rate source is zero");
require(address(_token) != address(0x0), "Token address is zero");
require(_token.minter() == address(0x0), "Token has another minter");
require(_tokenCapOfPublicSale > 0, "Cap of public sale is zero");
require(_tokenCapOfPrivateSale > 0, "Cap of private sale is zero");
require(_tokenPurchaseMinimum <= _tokenCapOfPublicSale
&& _tokenPurchaseMinimum <= _tokenCapOfPrivateSale,
"Purchase minimum exceeds cap");
require(_tokenPrice > 0, "Token price is zero");
require(_openingTime >= now, "Opening lies in the past");
require(_closingTime >= _openingTime, "Closing lies before opening");
require(_companyWallet != address(0x0), "Company wallet is zero");
require(_reserveAccount != address(0x0), "Reserve account is zero");
// Note: There are no time related requirements regarding limitEndTime.
// If it's below openingTime, token purchases will never be limited.
// If it's above closingTime, token purchases will always be limited.
if (_limitEndTime > _openingTime) {
// But, if there's a purchase limitation phase, the limit must be at
// least the purchase minimum or above to make purchases possible.
require(_tokenPurchaseLimit >= _tokenPurchaseMinimum,
"Purchase limit is below minimum");
}
// Utilize safe math to ensure the sum of three token pools does't overflow
_tokenCapOfPublicSale.add(_tokenCapOfPrivateSale).mul(_tokenReservePerMill);
rateSource = _rateSource;
token = _token;
tokenCapOfPublicSale = _tokenCapOfPublicSale;
tokenCapOfPrivateSale = _tokenCapOfPrivateSale;
tokenPurchaseMinimum = _tokenPurchaseMinimum;
tokenPurchaseLimit= _tokenPurchaseLimit;
tokenReservePerMill = _tokenReservePerMill;
tokenPrice = _tokenPrice;
openingTime = _openingTime;
closingTime = _closingTime;
limitEndTime = _limitEndTime;
companyWallet = _companyWallet;
reserveAccount = _reserveAccount;
tokenRemainingForPublicSale = _tokenCapOfPublicSale;
tokenRemainingForPrivateSale = _tokenCapOfPrivateSale;
}
/// @dev Fallback function: buys tokens
function () external payable {
require(msg.data.length == 0, "Fallback call with data");
buyTokens();
}
/// @dev Distribute tokens purchased off-chain via public sale
/// Note: additional requirements are enforced in internal function.
/// @param beneficiaries List of recipients' Ethereum addresses
/// @param amounts List of token units each recipient will receive
function distributeTokensViaPublicSale(
address[] memory beneficiaries,
uint[] memory amounts
)
public
{
tokenRemainingForPublicSale =
distributeTokens(tokenRemainingForPublicSale, beneficiaries, amounts, true);
}
/// @dev Distribute tokens purchased off-chain via private sale
/// Note: additional requirements are enforced in internal function.
/// @param beneficiaries List of recipients' Ethereum addresses
/// @param amounts List of token units each recipient will receive
function distributeTokensViaPrivateSale(
address[] memory beneficiaries,
uint[] memory amounts
)
public
{
tokenRemainingForPrivateSale =
distributeTokens(tokenRemainingForPrivateSale, beneficiaries, amounts, false);
}
/// @dev Check whether the sale has closed
/// @return True iff sale closing time has passed
function hasClosed() public view returns (bool) {
return now >= closingTime;
}
/// @dev Check wether the sale is open
/// @return True iff sale opening time has passed and sale is not closed yet
function isOpen() public view returns (bool) {
return now >= openingTime && !hasClosed();
}
/// @dev Determine the remaining open time of sale
/// @return Time in seconds until sale gets closed, or 0 if sale was closed
function timeRemaining() public view returns (uint) {
if (hasClosed()) {
return 0;
}
return closingTime - now;
}
/// @dev Determine the amount of sold tokens (off-chain and on-chain)
/// @return Token units amount
function tokenSold() public view returns (uint) {
return (tokenCapOfPublicSale - tokenRemainingForPublicSale)
+ (tokenCapOfPrivateSale - tokenRemainingForPrivateSale);
}
/// @dev Purchase tokens
function buyTokens() public payable {
require(isOpen(), "Sale is not open");
uint etherRate = rateSource.etherRate();
require(etherRate > 0, "Ether rate is zero");
// Units: [1e-18*ether] * [cent/ether] / [cent/token] => [1e-18*token]
uint amount = msg.value.mul(etherRate).div(tokenPrice);
require(amount <= tokenRemainingForPublicSale, "Not enough tokens available");
require(amount >= tokenPurchaseMinimum, "Investment is too low");
// Is the total amount an investor can purchase with Ether limited?
if (now < limitEndTime) {
uint purchased = tokenPurchased[msg.sender].add(amount);
require(purchased <= tokenPurchaseLimit, "Purchase limit reached");
tokenPurchased[msg.sender] = purchased;
}
tokenRemainingForPublicSale = tokenRemainingForPublicSale.sub(amount);
token.mint(msg.sender, amount);
forwardFunds();
emit TokenPurchase(msg.sender, msg.value, amount);
}
/// @dev Extend the offering period of the crowd sale.
/// @param _newClosingTime new closingTime of the crowdsale
function changeClosingTime(uint _newClosingTime) public onlyOwner {
require(!hasClosed(), "Sale has already ended");
require(_newClosingTime > now, "ClosingTime not in the future");
require(_newClosingTime > openingTime, "New offering is zero");
require(_newClosingTime - openingTime <= MAXOFFERINGPERIOD, "New offering too long");
emit ClosingTimeChange(closingTime, _newClosingTime);
closingTime = _newClosingTime;
}
/// @dev Finalize, i.e. end token minting phase and enable token transfers
function finalize() public onlyOwner {
require(!isFinalized, "Sale has already been finalized");
require(hasClosed(), "Sale has not closed");
if (tokenReservePerMill > 0) {
token.mint(reserveAccount, tokenSold().mul(tokenReservePerMill).div(1000));
}
token.finishMinting();
isFinalized = true;
emit Finalization();
}
/// @dev Distribute tokens purchased off-chain (in Euro) to investors
/// @param tokenRemaining Token units available for sale
/// @param beneficiaries Ethereum addresses of purchasers
/// @param amounts Token unit amounts to deliver to each investor
/// @return Token units available for sale after distribution
function distributeTokens(
uint tokenRemaining,
address[] memory beneficiaries,
uint[] memory amounts,
bool isPublicSale
)
internal
onlyOwner
returns (uint)
{
require(!isFinalized, "Sale has been finalized");
require(beneficiaries.length == amounts.length, "Lengths are different");
for (uint i = 0; i < beneficiaries.length; ++i) {
address beneficiary = beneficiaries[i];
uint amount = amounts[i];
require(amount <= tokenRemaining, "Not enough tokens available");
tokenRemaining = tokenRemaining.sub(amount);
token.mint(beneficiary, amount);
emit TokenDistribution(beneficiary, amount, isPublicSale);
}
return tokenRemaining;
}
/// @dev Forward invested ether to company wallet
function forwardFunds() internal {
companyWallet.transfer(address(this).balance);
}
}
// File: contracts/token/TokenRecoverable.sol
pragma solidity 0.5.12;
/// @title TokenRecoverable
/// @author STOKR
contract TokenRecoverable is Ownable {
// Address that can do the TokenRecovery
address public tokenRecoverer;
/// @dev Event emitted when the TokenRecoverer changes
/// @param previous Ethereum address of previous token recoverer
/// @param current Ethereum address of new token recoverer
event TokenRecovererChange(address indexed previous, address indexed current);
/// @dev Event emitted in case of a TokenRecovery
/// @param oldAddress Ethereum address of old account
/// @param newAddress Ethereum address of new account
event TokenRecovery(address indexed oldAddress, address indexed newAddress);
/// @dev Restrict operation to token recoverer
modifier onlyTokenRecoverer() {
require(msg.sender == tokenRecoverer, "Restricted to token recoverer");
_;
}
/// @dev Constructor
/// @param _tokenRecoverer Ethereum address of token recoverer
constructor(address _tokenRecoverer) public {
setTokenRecoverer(_tokenRecoverer);
}
/// @dev Set token recoverer
/// @param _newTokenRecoverer Ethereum address of new token recoverer
function setTokenRecoverer(address _newTokenRecoverer) public onlyOwner {
require(_newTokenRecoverer != address(0x0), "New token recoverer is zero");
if (_newTokenRecoverer != tokenRecoverer) {
emit TokenRecovererChange(tokenRecoverer, _newTokenRecoverer);
tokenRecoverer = _newTokenRecoverer;
}
}
/// @dev Recover token
/// @param _oldAddress address
/// @param _newAddress address
function recoverToken(address _oldAddress, address _newAddress) public;
}
// File: contracts/token/StokrToken.sol
pragma solidity 0.5.12;
/// @title StokrToken
/// @author Stokr
contract StokrToken is MintableToken, TokenRecoverable {
string public name;
string public symbol;
uint8 public constant decimals = 18;
mapping(address => mapping(address => uint)) internal allowance_;
/// @dev Log entry on self destruction of the token
event TokenDestroyed();
/// @dev Constructor
/// @param _whitelist Ethereum address of whitelist contract
/// @param _tokenRecoverer Ethereum address of token recoverer
constructor(
string memory _name,
string memory _symbol,
Whitelist _whitelist,
address _profitDepositor,
address _profitDistributor,
address _tokenRecoverer
)
public
Whitelisted(_whitelist)
ProfitSharing(_profitDepositor, _profitDistributor)
TokenRecoverable(_tokenRecoverer)
{
name = _name;
symbol = _symbol;
}
/// @dev Self destruct can only be called by crowdsale contract in case the goal wasn't reached
function destruct() public onlyMinter {
emit TokenDestroyed();
selfdestruct(address(uint160(owner)));
}
/// @dev Recover token
/// @param _oldAddress address of old account
/// @param _newAddress address of new account
function recoverToken(address _oldAddress, address _newAddress)
public
onlyTokenRecoverer
onlyWhitelisted(_newAddress)
{
// Ensure that new address is *not* an existing account.
// Check for account.profitShare is not needed because of following implication:
// (account.lastTotalProfits == 0) ==> (account.profitShare == 0)
require(accounts[_newAddress].balance == 0 && accounts[_newAddress].lastTotalProfits == 0,
"New address exists already");
updateProfitShare(_oldAddress);
accounts[_newAddress] = accounts[_oldAddress];
delete accounts[_oldAddress];
emit TokenRecovery(_oldAddress, _newAddress);
emit Transfer(_oldAddress, _newAddress, accounts[_newAddress].balance);
}
/// @dev Total supply of this token
/// @return Token amount
function totalSupply() public view returns (uint) {
return totalSupply_;
}
/// @dev Token balance
/// @param _investor Ethereum address of token holder
/// @return Token amount
function balanceOf(address _investor) public view returns (uint) {
return accounts[_investor].balance;
}
/// @dev Allowed token amount a third party trustee may transfer
/// @param _investor Ethereum address of token holder
/// @param _spender Ethereum address of third party
/// @return Allowed token amount
function allowance(address _investor, address _spender) public view returns (uint) {
return allowance_[_investor][_spender];
}
/// @dev Approve a third party trustee to transfer tokens
/// Note: additional requirements are enforced within internal function.
/// @param _spender Ethereum address of third party
/// @param _value Maximum token amount that is allowed to get transferred
/// @return Always true
function approve(address _spender, uint _value) public returns (bool) {
return _approve(msg.sender, _spender, _value);
}
/// @dev Increase the amount of tokens a third party trustee may transfer
/// Note: additional requirements are enforces within internal function.
/// @param _spender Ethereum address of third party
/// @param _amount Additional token amount that is allowed to get transferred
/// @return Always true
function increaseAllowance(address _spender, uint _amount) public returns (bool) {
require(allowance_[msg.sender][_spender] + _amount >= _amount, "Allowance overflow");
return _approve(msg.sender, _spender, allowance_[msg.sender][_spender].add(_amount));
}
/// @dev Decrease the amount of tokens a third party trustee may transfer
/// Note: additional requirements are enforces within internal function.
/// @param _spender Ethereum address of third party
/// @param _amount Reduced token amount that is allowed to get transferred
/// @return Always true
function decreaseAllowance(address _spender, uint _amount) public returns (bool) {
require(_amount <= allowance_[msg.sender][_spender], "Amount exceeds allowance");
return _approve(msg.sender, _spender, allowance_[msg.sender][_spender].sub(_amount));
}
/// @dev Check if a token transfer is possible
/// @param _from Ethereum address of token sender
/// @param _to Ethereum address of token recipient
/// @param _value Token amount to transfer
/// @return True iff a transfer with given pramaters would succeed
function canTransfer(address _from, address _to, uint _value)
public view returns (bool)
{
return totalSupplyIsFixed
&& _from != address(0x0)
&& _to != address(0x0)
&& _value <= accounts[_from].balance
&& whitelist.isWhitelisted(_from)
&& whitelist.isWhitelisted(_to);
}
/// @dev Check if a token transfer by third party is possible
/// @param _spender Ethereum address of third party trustee
/// @param _from Ethereum address of token holder
/// @param _to Ethereum address of token recipient
/// @param _value Token amount to transfer
/// @return True iff a transfer with given pramaters would succeed
function canTransferFrom(address _spender, address _from, address _to, uint _value)
public view returns (bool)
{
return canTransfer(_from, _to, _value) && _value <= allowance_[_from][_spender];
}
/// @dev Token transfer
/// Note: additional requirements are enforces within internal function.
/// @param _to Ethereum address of token recipient
/// @param _value Token amount to transfer
/// @return Always true
function transfer(address _to, uint _value) public returns (bool) {
return _transfer(msg.sender, _to, _value);
}
/// @dev Token transfer by a third party
/// Note: additional requirements are enforces within internal function.
/// @param _from Ethereum address of token holder
/// @param _to Ethereum address of token recipient
/// @param _value Token amount to transfer
/// @return Always true
function transferFrom(address _from, address _to, uint _value) public returns (bool) {
require(_value <= allowance_[_from][msg.sender], "Amount exceeds allowance");
return _approve(_from, msg.sender, allowance_[_from][msg.sender].sub(_value))
&& _transfer(_from, _to, _value);
}
/// @dev Approve a third party trustee to transfer tokens (internal implementation)
/// @param _from Ethereum address of token holder
/// @param _spender Ethereum address of third party
/// @param _value Maximum token amount the trustee is allowed to transfer
/// @return Always true
function _approve(address _from, address _spender, uint _value)
internal
onlyWhitelisted(_from)
onlyWhenTotalSupplyIsFixed
returns (bool)
{
allowance_[_from][_spender] = _value;
emit Approval(_from, _spender, _value);
return true;
}
/// @dev Token transfer (internal implementation)
/// @param _from Ethereum address of token sender
/// @param _to Ethereum address of token recipient
/// @param _value Token amount to transfer
/// @return Always true
function _transfer(address _from, address _to, uint _value)
internal
onlyWhitelisted(_from)
onlyWhitelisted(_to)
onlyWhenTotalSupplyIsFixed
returns (bool)
{
require(_to != address(0x0), "Recipient is zero");
require(_value <= accounts[_from].balance, "Amount exceeds balance");
updateProfitShare(_from);
updateProfitShare(_to);
accounts[_from].balance = accounts[_from].balance.sub(_value);
accounts[_to].balance = accounts[_to].balance.add(_value);
emit Transfer(_from, _to, _value);
return true;
}
}
// File: contracts/crowdsale/StokrCrowdsale.sol
pragma solidity 0.5.12;
/// @title StokrCrowdsale
/// @author STOKR
contract StokrCrowdsale is MintingCrowdsale {
// Soft cap in token units
uint public tokenGoal;
// As long as the goal is not reached funds of purchases are held back
// and investments are assigned to investors here to enable a refunding
// if the goal is missed upon finalization
mapping(address => uint) public investments;
// Log entry upon investor refund event
event InvestorRefund(address indexed investor, uint value);
/// @dev Constructor
/// @param _token The token
/// @param _tokenCapOfPublicSale Available token units for public sale
/// @param _tokenCapOfPrivateSale Available token units for private sale
/// @param _tokenGoal Minimum number of sold token units to be successful
/// @param _tokenPurchaseMinimum Minimum amount of tokens an investor has to buy at once
/// @param _tokenPurchaseLimit Maximum total token amounts individually buyable in limit phase
/// @param _tokenReservePerMill Additional reserve tokens in per mill of sold tokens
/// @param _tokenPrice Price of a token in EUR cent
/// @param _rateSource Ethereum address of ether rate setting authority
/// @param _openingTime Block (Unix) timestamp of sale opening time
/// @param _closingTime Block (Unix) timestamp of sale closing time
/// @param _limitEndTime Block (Unix) timestamp until token purchases are limited
/// @param _companyWallet Ethereum account who will receive sent ether
/// @param _reserveAccount An address
constructor(
RateSource _rateSource,
StokrToken _token,
uint _tokenCapOfPublicSale,
uint _tokenCapOfPrivateSale,
uint _tokenGoal,
uint _tokenPurchaseMinimum,
uint _tokenPurchaseLimit,
uint _tokenReservePerMill,
uint _tokenPrice,
uint _openingTime,
uint _closingTime,
uint _limitEndTime,
address payable _companyWallet,
address _reserveAccount
)
public
MintingCrowdsale(
_rateSource,
_token,
_tokenCapOfPublicSale,
_tokenCapOfPrivateSale,
_tokenPurchaseMinimum,
_tokenPurchaseLimit,
_tokenReservePerMill,
_tokenPrice,
_openingTime,
_closingTime,
_limitEndTime,
_companyWallet,
_reserveAccount
)
{
require(
_tokenGoal <= _tokenCapOfPublicSale + _tokenCapOfPrivateSale,
"Goal is not attainable"
);
tokenGoal = _tokenGoal;
}
/// @dev Wether the goal of sold tokens was reached or not
/// @return True if the sale can be considered successful
function goalReached() public view returns (bool) {
return tokenSold() >= tokenGoal;
}
/// @dev Investors can claim refunds here if crowdsale was unsuccessful
function distributeRefunds(address payable[] calldata _investors) external {
for (uint i = 0; i < _investors.length; ++i) {
refundInvestor(_investors[i]);
}
}
/// @dev Investors can claim refunds here if crowdsale was unsuccessful
function claimRefund() public {
refundInvestor(msg.sender);
}
/// @dev Overwritten. Kill the token if goal was missed
function finalize() public onlyOwner {
super.finalize();
if (!goalReached()) {
StokrToken(address(token)).destruct();
}
}
function distributeTokensViaPublicSale(
address[] memory beneficiaries,
uint[] memory amounts
)
public
{
super.distributeTokensViaPublicSale(beneficiaries, amounts);
// The goal may get reached due to token distribution,
// so forward any accumulated funds to the company wallet.
forwardFunds();
}
function distributeTokensViaPrivateSale(
address[] memory beneficiaries,
uint[] memory amounts
)
public
{
super.distributeTokensViaPrivateSale(beneficiaries, amounts);
// The goal may get reached due to token distribution,
// so forward any accumulated funds to the company wallet.
forwardFunds();
}
/// @dev Overwritten. Funds are held back until goal was reached
function forwardFunds() internal {
if (goalReached()) {
super.forwardFunds();
}
else {
investments[msg.sender] = investments[msg.sender].add(msg.value);
}
}
/// @dev Refund an investor if the sale was not successful
/// @param _investor Ethereum address of investor
function refundInvestor(address payable _investor) internal {
require(isFinalized, "Sale has not been finalized");
require(!goalReached(), "Goal was reached");
uint investment = investments[_investor];
if (investment > 0) {
investments[_investor] = 0;
_investor.transfer(investment);
emit InvestorRefund(_investor, investment);
}
}
} | Change profit distributor _newProfitDistributor An Ethereum address | function setProfitDistributor(address _newProfitDistributor) public onlyOwner {
require(_newProfitDistributor != address(0x0), "New profit distributor is zero");
if (_newProfitDistributor != profitDistributor) {
emit ProfitDistributorChange(profitDistributor, _newProfitDistributor);
profitDistributor = _newProfitDistributor;
}
}
| 1,786,956 |
./partial_match/1/0x2368A152a54d8105E81a784eB3998Bb7Cf9d08fc/sources/CultTsuka.sol | exclude from paying fees or having max transaction amount | constructor() ERC20("Cult Tsuka", "CULTSU") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), ETH);
excludeFromMaxTransaction(address(uniswapV2Pair), true);
uint256 _buyDevFee = 4;
uint256 _buyLiquidityFee = 0;
uint256 _sellDevFee = 4;
uint256 _sellLiquidityFee = 0;
uint256 totalSupply = 100_000_000_000 * 1e18;
buyDevFee = _buyDevFee;
buyLiquidityFee = _buyLiquidityFee;
buyTotalFees = buyDevFee + buyLiquidityFee;
sellDevFee = _sellDevFee;
sellLiquidityFee = _sellLiquidityFee;
sellTotalFees = sellDevFee + sellLiquidityFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 15,649,832 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title BulldogTestyClubSeason1 contract, the only certificate that can be used to mint BulldogTestyClub
* @dev Extends ERC20 Standard basic implementation
*/
contract BulldogTestyClubSeason1 is ERC20 , Ownable{
address public bulldogTestyClub;
mapping(address => uint8) private whitelistMemberUsed;
event AddWhitelisted(address indexed member);
struct TimeRange {
uint startTime;
uint endTime;
}
TimeRange public timeRange;
constructor(
string memory _name,
string memory _symbol,
address _bulldogTestyClub
) ERC20(_name,_symbol) public {
bulldogTestyClub = _bulldogTestyClub;
_setupDecimals(0);
}
/**
* @notice add some members address
* @param _members whitelisted address of member
*/
function addWhitelistMember(address[] memory _members) external onlyOwner {
for(uint16 i = 0; i < _members.length; i++){
if(whitelistMemberUsed[_members[i]] == 0){
whitelistMemberUsed[_members[i]] = 1;
}
}
}
function getWhitelistMemberUsed(address _member) external view returns (uint8) {
return whitelistMemberUsed[_member];
}
/**
* @notice burn amount btcs1, only bulldogTestyClub can execute
* @param account btcs1's owner
* @param amount btcs1 amount
*/
function burn(address account, uint256 amount) external {
require(msg.sender == bulldogTestyClub);
_burn(account,amount);
}
/**
* @notice Within the set time range, member users can mint a token
*/
function mint() external {
require(now >= timeRange.startTime && now <= timeRange.endTime,"now is not in allow time range");
require(whitelistMemberUsed[msg.sender] == 1,"member is illegal");
_mint(msg.sender, 1);
whitelistMemberUsed[msg.sender] = whitelistMemberUsed[msg.sender]+1;
}
function setTimeRange(TimeRange memory _timeRange) external onlyOwner {
timeRange.startTime = _timeRange.startTime;
timeRange.endTime = _timeRange.endTime;
}
function nowTime() external view returns(uint) {
return now;
}
} | add some members address _members whitelisted address of member/ | function addWhitelistMember(address[] memory _members) external onlyOwner {
for(uint16 i = 0; i < _members.length; i++){
if(whitelistMemberUsed[_members[i]] == 0){
whitelistMemberUsed[_members[i]] = 1;
}
}
}
| 12,906,483 |
./partial_match/42/0xB4AaD2d9E581FeE9444383Bc9493aDF870C59999/sources/XPool.sol | Swap Fees: 0.1%, 0.3%, 1%, 3%, 10% | function setSwapFee(uint256 swapFee) external _logs_ _lock_ {
require(!_finalized, "ERR_IS_FINALIZED");
require(msg.sender == _controller, "ERR_NOT_CONTROLLER");
require(swapFee >= MIN_FEE, "ERR_MIN_FEE");
require(swapFee <= MAX_FEE, "ERR_MAX_FEE");
bool found = false;
for (uint256 i = 0; i < SWAP_FEES.length; i++) {
if (swapFee == SWAP_FEES[i]) {
found = true;
break;
}
}
require(found, "ERR_INVALID_SWAP_FEE");
_swapFee = swapFee;
}
| 3,332,523 |
./full_match/97/0xE458c15664880D36F52BF0a7fcBD538011935C4b/sources/project_/contracts/lp-token-staker/STRFTokenLocker.sol | Withdraw locked tokens First withdraws unlocked tokens, then locked tokens. Withdrawing locked tokens incurs a 50% penalty. | function withdraw(uint256 amount) external tokenSet {
require(amount > 0, "STRFTokenLocker: cannot withdraw 0");
uint256 unlockedAmount;
uint256 penaltyAmount;
(unlockedAmount, penaltyAmount) = getWithdrawableBalance(msg.sender);
bool penaltyFlag = false;
require(unlockedAmount + penaltyAmount >= amount, "STRFTokenLocker: insufficient balance");
uint256 remaining = amount;
_balances[msg.sender] = _balances[msg.sender] - amount;
for (uint i = 0; ; i++) {
if (_userLocks[msg.sender][i].amount == 0)
{
continue;
if (!penaltyFlag) {
penaltyFlag = true;
_balances[msg.sender] = _balances[msg.sender] - remaining;
_STRFToken.safeTransfer(_treasury, remaining);
remaining = remaining * 2;
}
}
if (remaining <= _userLocks[msg.sender][i].amount) {
_userLocks[msg.sender][i].amount = _userLocks[msg.sender][i].amount - remaining;
if (_userLocks[msg.sender][i].amount == 0) {
delete _userLocks[msg.sender][i];
}
break;
remaining = remaining - _userLocks[msg.sender][i].amount;
delete _userLocks[msg.sender][i];
}
}
_STRFToken.safeTransfer(msg.sender, amount);
emit Withdraw(msg.sender, amount);
}
| 5,020,198 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ========================== FraxLendingAMO ==========================
// ====================================================================
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Reviewer(s) / Contributor(s)
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
import "../Math/SafeMath.sol";
import "../FXS/FXS.sol";
import "../Frax/Frax.sol";
import "../ERC20/ERC20.sol";
import "../ERC20/Variants/Comp.sol";
import "../Oracle/UniswapPairOracle.sol";
import "../Governance/AccessControl.sol";
import "../Frax/Pools/FraxPool.sol";
import "./cream/ICREAM_crFRAX.sol";
import "./finnexus/IFNX_CFNX.sol";
import "./finnexus/IFNX_FPT_FRAX.sol";
import "./finnexus/IFNX_FPT_B.sol";
import "./finnexus/IFNX_IntegratedStake.sol";
import "./finnexus/IFNX_MinePool.sol";
import "./finnexus/IFNX_TokenConverter.sol";
import "./finnexus/IFNX_ManagerProxy.sol";
import "./finnexus/IFNX_Oracle.sol";
contract FraxLendingAMO is AccessControl {
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
ERC20 private collateral_token;
FRAXShares private FXS;
FRAXStablecoin private FRAX;
FraxPool private pool;
// Cream
ICREAM_crFRAX private crFRAX = ICREAM_crFRAX(0xb092b4601850E23903A42EaCBc9D8A0EeC26A4d5);
// FinNexus
// More addresses: https://github.com/FinNexus/FinNexus-Documentation/blob/master/content/developers/smart-contracts.md
IFNX_FPT_FRAX private fnxFPT_FRAX = IFNX_FPT_FRAX(0x39ad661bA8a7C9D3A7E4808fb9f9D5223E22F763);
IFNX_FPT_B private fnxFPT_B = IFNX_FPT_B(0x7E605Fb638983A448096D82fFD2958ba012F30Cd);
IFNX_IntegratedStake private fnxIntegratedStake = IFNX_IntegratedStake(0x23e54F9bBe26eD55F93F19541bC30AAc2D5569b2);
IFNX_MinePool private fnxMinePool = IFNX_MinePool(0x4e6005396F80a737cE80d50B2162C0a7296c9620);
IFNX_TokenConverter private fnxTokenConverter = IFNX_TokenConverter(0x955282b82440F8F69E901380BeF2b603Fba96F3b);
IFNX_ManagerProxy private fnxManagerProxy = IFNX_ManagerProxy(0xa2904Fd151C9d9D634dFA8ECd856E6B9517F9785);
IFNX_Oracle private fnxOracle = IFNX_Oracle(0x43BD92bF3Bb25EBB3BdC2524CBd6156E3Fdd41F3);
// Reward Tokens
IFNX_CFNX private CFNX = IFNX_CFNX(0x9d7beb4265817a4923FAD9Ca9EF8af138499615d);
ERC20 private FNX = ERC20(0xeF9Cd7882c067686691B6fF49e650b43AFBBCC6B);
address public collateral_address;
address public pool_address;
address public owner_address;
address public timelock_address;
address public custodian_address;
uint256 public immutable missing_decimals;
uint256 private constant PRICE_PRECISION = 1e6;
// Max amount of FRAX this contract mint
uint256 public mint_cap = uint256(100000e18);
// Minimum collateral ratio needed for new FRAX minting
uint256 public min_cr = 850000;
// Amount the contract borrowed
uint256 public minted_sum_historical = 0;
uint256 public burned_sum_historical = 0;
// Allowed strategies (can eventually be made into an array)
bool public allow_cream = true;
bool public allow_finnexus = true;
/* ========== CONSTRUCTOR ========== */
constructor(
address _frax_contract_address,
address _fxs_contract_address,
address _pool_address,
address _collateral_address,
address _owner_address,
address _custodian_address,
address _timelock_address
) public {
FRAX = FRAXStablecoin(_frax_contract_address);
FXS = FRAXShares(_fxs_contract_address);
pool_address = _pool_address;
pool = FraxPool(_pool_address);
collateral_address = _collateral_address;
collateral_token = ERC20(_collateral_address);
timelock_address = _timelock_address;
owner_address = _owner_address;
custodian_address = _custodian_address;
missing_decimals = uint(18).sub(collateral_token.decimals());
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
/* ========== MODIFIERS ========== */
modifier onlyByOwnerOrGovernance() {
require(msg.sender == timelock_address || msg.sender == owner_address, "You are not the owner or the governance timelock");
_;
}
modifier onlyCustodian() {
require(msg.sender == custodian_address, "You are not the rewards custodian");
_;
}
/* ========== VIEWS ========== */
function showAllocations() external view returns (uint256[10] memory allocations) {
// IMPORTANT
// Should ONLY be used externally, because it may fail if any one of the functions below fail
// All numbers given are in FRAX unless otherwise stated
allocations[0] = FRAX.balanceOf(address(this)); // Unallocated FRAX
allocations[1] = (crFRAX.balanceOf(address(this)).mul(crFRAX.exchangeRateStored()).div(1e18)); // Cream
allocations[2] = (fnxMinePool.getUserFPTABalance(address(this))).mul(1e8).div(fnxManagerProxy.getTokenNetworth()); // Staked FPT-FRAX
allocations[3] = (fnxFPT_FRAX.balanceOf(address(this))).mul(1e8).div(fnxManagerProxy.getTokenNetworth()); // Free FPT-FRAX
allocations[4] = fnxTokenConverter.lockedBalanceOf(address(this)); // Unwinding CFNX
allocations[5] = fnxTokenConverter.getClaimAbleBalance(address(this)); // Claimable Unwound FNX
allocations[6] = FNX.balanceOf(address(this)); // Free FNX
uint256 sum_fnx = allocations[4];
sum_fnx = sum_fnx.add(allocations[5]);
sum_fnx = sum_fnx.add(allocations[6]);
allocations[7] = sum_fnx; // Total FNX possessed in various forms
uint256 sum_frax = allocations[0];
sum_frax = sum_frax.add(allocations[1]);
sum_frax = sum_frax.add(allocations[2]);
sum_frax = sum_frax.add(allocations[3]);
allocations[8] = sum_frax; // Total FRAX possessed in various forms
allocations[9] = collatDollarBalance();
}
function showRewards() external view returns (uint256[1] memory rewards) {
// IMPORTANT
// Should ONLY be used externally, because it may fail if FNX.balanceOf() fails
rewards[0] = FNX.balanceOf(address(this)); // FNX
}
// In FRAX
function mintedBalance() public view returns (uint256){
if (minted_sum_historical > burned_sum_historical) return minted_sum_historical.sub(burned_sum_historical);
else return 0;
}
// In FRAX
function historicalProfit() public view returns (uint256){
if (burned_sum_historical > minted_sum_historical) return burned_sum_historical.sub(minted_sum_historical);
else return 0;
}
/* ========== PUBLIC FUNCTIONS ========== */
// Needed for the Frax contract to not brick
bool public override_collat_balance = false;
uint256 public override_collat_balance_amount;
function collatDollarBalance() public view returns (uint256) {
if(override_collat_balance){
return override_collat_balance_amount;
}
// E18 for dollars, not E6
// Assumes $1 FRAX and $1 USDC
return (mintedBalance()).mul(FRAX.global_collateral_ratio()).div(PRICE_PRECISION);
}
/* ========== RESTRICTED FUNCTIONS ========== */
// This contract is essentially marked as a 'pool' so it can call OnlyPools functions like pool_mint and pool_burn_from
// on the main FRAX contract
function mintFRAXForInvestments(uint256 frax_amount) public onlyByOwnerOrGovernance {
uint256 borrowed_balance = mintedBalance();
// Make sure you aren't minting more than the mint cap
require(borrowed_balance.add(frax_amount) <= mint_cap, "Borrow cap reached");
minted_sum_historical = minted_sum_historical.add(frax_amount);
// Make sure the current CR isn't already too low
require (FRAX.global_collateral_ratio() > min_cr, "Collateral ratio is already too low");
// Make sure the FRAX minting wouldn't push the CR down too much
uint256 current_collateral_E18 = (FRAX.globalCollateralValue()).mul(10 ** missing_decimals);
uint256 cur_frax_supply = FRAX.totalSupply();
uint256 new_frax_supply = cur_frax_supply.add(frax_amount);
uint256 new_cr = (current_collateral_E18.mul(PRICE_PRECISION)).div(new_frax_supply);
require (new_cr > min_cr, "Minting would cause collateral ratio to be too low");
// Mint the frax
FRAX.pool_mint(address(this), frax_amount);
}
// Give USDC profits back
function giveCollatBack(uint256 amount) public onlyByOwnerOrGovernance {
collateral_token.transfer(address(pool), amount);
}
// Burn unneeded or excess FRAX
function burnFRAX(uint256 frax_amount) public onlyByOwnerOrGovernance {
FRAX.burn(frax_amount);
burned_sum_historical = burned_sum_historical.add(frax_amount);
}
// Burn unneeded FXS
function burnFXS(uint256 amount) public onlyByOwnerOrGovernance {
FXS.approve(address(this), amount);
FXS.pool_burn_from(address(this), amount);
}
/* ==================== CREAM ==================== */
// E18
function creamDeposit_FRAX(uint256 FRAX_amount) public onlyByOwnerOrGovernance {
require(allow_cream, 'Cream strategy is disabled');
FRAX.approve(address(crFRAX), FRAX_amount);
require(crFRAX.mint(FRAX_amount) == 0, 'Mint failed');
}
// E18
function creamWithdraw_FRAX(uint256 FRAX_amount) public onlyByOwnerOrGovernance {
require(crFRAX.redeemUnderlying(FRAX_amount) == 0, 'RedeemUnderlying failed');
}
// E8
function creamWithdraw_crFRAX(uint256 crFRAX_amount) public onlyByOwnerOrGovernance {
require(crFRAX.redeem(crFRAX_amount) == 0, 'Redeem failed');
}
/* ==================== FinNexus ==================== */
/* --== Staking ==-- */
function fnxIntegratedStakeFPTs_FRAX_FNX(uint256 FRAX_amount, uint256 FNX_amount, uint256 lock_period) public onlyByOwnerOrGovernance {
require(allow_finnexus, 'FinNexus strategy is disabled');
FRAX.approve(address(fnxIntegratedStake), FRAX_amount);
FNX.approve(address(fnxIntegratedStake), FNX_amount);
address[] memory fpta_tokens = new address[](1);
uint256[] memory fpta_amounts = new uint256[](1);
address[] memory fptb_tokens = new address[](1);
uint256[] memory fptb_amounts = new uint256[](1);
fpta_tokens[0] = address(FRAX);
fpta_amounts[0] = FRAX_amount;
fptb_tokens[0] = address(FNX);
fptb_amounts[0] = FNX_amount;
fnxIntegratedStake.stake(fpta_tokens, fpta_amounts, fptb_tokens, fptb_amounts, lock_period);
}
// FPT-FRAX : FPT-B = 10:1 is the best ratio for staking. You can get it using the prices.
function fnxStakeFRAXForFPT_FRAX(uint256 FRAX_amount, uint256 lock_period) public onlyByOwnerOrGovernance {
require(allow_finnexus, 'FinNexus strategy is disabled');
FRAX.approve(address(fnxIntegratedStake), FRAX_amount);
address[] memory fpta_tokens = new address[](1);
uint256[] memory fpta_amounts = new uint256[](1);
address[] memory fptb_tokens = new address[](0);
uint256[] memory fptb_amounts = new uint256[](0);
fpta_tokens[0] = address(FRAX);
fpta_amounts[0] = FRAX_amount;
fnxIntegratedStake.stake(fpta_tokens, fpta_amounts, fptb_tokens, fptb_amounts, lock_period);
}
/* --== Collect CFNX ==-- */
function fnxCollectCFNX() public onlyByOwnerOrGovernance {
uint256 claimable_cfnx = fnxMinePool.getMinerBalance(address(this), address(CFNX));
fnxMinePool.redeemMinerCoin(address(CFNX), claimable_cfnx);
}
/* --== UnStaking ==-- */
// FPT-FRAX = Staked FRAX
function fnxUnStakeFPT_FRAX(uint256 FPT_FRAX_amount) public onlyByOwnerOrGovernance {
fnxMinePool.unstakeFPTA(FPT_FRAX_amount);
}
// FPT-B = Staked FNX
function fnxUnStakeFPT_B(uint256 FPT_B_amount) public onlyByOwnerOrGovernance {
fnxMinePool.unstakeFPTB(FPT_B_amount);
}
/* --== Unwrapping LP Tokens ==-- */
// FPT-FRAX = Staked FRAX
function fnxUnRedeemFPT_FRAXForFRAX(uint256 FPT_FRAX_amount) public onlyByOwnerOrGovernance {
fnxFPT_FRAX.approve(address(fnxManagerProxy), FPT_FRAX_amount);
fnxManagerProxy.redeemCollateral(FPT_FRAX_amount, address(FRAX));
}
// FPT-B = Staked FNX
function fnxUnStakeFPT_BForFNX(uint256 FPT_B_amount) public onlyByOwnerOrGovernance {
fnxFPT_B.approve(address(fnxManagerProxy), FPT_B_amount);
fnxManagerProxy.redeemCollateral(FPT_B_amount, address(FNX));
}
/* --== Convert CFNX to FNX ==-- */
// Has to be done in batches, since it unlocks over several months
function fnxInputCFNXForUnwinding() public onlyByOwnerOrGovernance {
uint256 cfnx_amount = CFNX.balanceOf(address(this));
CFNX.approve(address(fnxTokenConverter), cfnx_amount);
fnxTokenConverter.inputCfnxForInstallmentPay(cfnx_amount);
}
function fnxClaimFNX_From_CFNX() public onlyByOwnerOrGovernance {
fnxTokenConverter.claimFnxExpiredReward();
}
/* --== Combination Functions ==-- */
function fnxCFNXCollectConvertUnwind() public onlyByOwnerOrGovernance {
fnxCollectCFNX();
fnxInputCFNXForUnwinding();
fnxClaimFNX_From_CFNX();
}
/* ========== Custodian ========== */
function withdrawRewards() public onlyCustodian {
FNX.transfer(custodian_address, FNX.balanceOf(address(this)));
}
/* ========== RESTRICTED GOVERNANCE FUNCTIONS ========== */
function setTimelock(address new_timelock) external onlyByOwnerOrGovernance {
timelock_address = new_timelock;
}
function setOwner(address _owner_address) external onlyByOwnerOrGovernance {
owner_address = _owner_address;
}
function setMiscRewardsCustodian(address _custodian_address) external onlyByOwnerOrGovernance {
custodian_address = _custodian_address;
}
function setPool(address _pool_address) external onlyByOwnerOrGovernance {
pool_address = _pool_address;
pool = FraxPool(_pool_address);
}
function setMintCap(uint256 _mint_cap) external onlyByOwnerOrGovernance {
mint_cap = _mint_cap;
}
function setMinimumCollateralRatio(uint256 _min_cr) external onlyByOwnerOrGovernance {
min_cr = _min_cr;
}
function setAllowedStrategies(bool _cream, bool _finnexus) external onlyByOwnerOrGovernance {
allow_cream = _cream;
allow_finnexus = _finnexus;
}
function setOverrideCollatBalance(bool _state, uint256 _balance) external onlyByOwnerOrGovernance {
override_collat_balance = _state;
override_collat_balance_amount = _balance;
}
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance {
// Can only be triggered by owner or governance, not custodian
// Tokens are sent to the custodian, as a sort of safeguard
ERC20(tokenAddress).transfer(custodian_address, tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
/* ========== EVENTS ========== */
event Recovered(address token, uint256 amount);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
/**
* @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.
*
* _Available since v2.4.0._
*/
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.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
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.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ========================= FRAXShares (FXS) =========================
// ====================================================================
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
// Reviewer(s) / Contributor(s)
// Sam Sun: https://github.com/samczsun
import "../Common/Context.sol";
import "../ERC20/ERC20Custom.sol";
import "../ERC20/IERC20.sol";
import "../Frax/Frax.sol";
import "../Math/SafeMath.sol";
import "../Governance/AccessControl.sol";
contract FRAXShares is ERC20Custom, AccessControl {
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
string public symbol;
string public name;
uint8 public constant decimals = 18;
address public FRAXStablecoinAdd;
uint256 public constant genesis_supply = 100000000e18; // 100M is printed upon genesis
uint256 public FXS_DAO_min; // Minimum FXS required to join DAO groups
address public owner_address;
address public oracle_address;
address public timelock_address; // Governance timelock address
FRAXStablecoin private FRAX;
bool public trackingVotes = true; // Tracking votes (only change if need to disable votes)
// A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
// A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
// The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/* ========== MODIFIERS ========== */
modifier onlyPools() {
require(FRAX.frax_pools(msg.sender) == true, "Only frax pools can mint new FRAX");
_;
}
modifier onlyByOwnerOrGovernance() {
require(msg.sender == owner_address || msg.sender == timelock_address, "You are not an owner or the governance timelock");
_;
}
/* ========== CONSTRUCTOR ========== */
constructor(
string memory _name,
string memory _symbol,
address _oracle_address,
address _owner_address,
address _timelock_address
) public {
name = _name;
symbol = _symbol;
owner_address = _owner_address;
oracle_address = _oracle_address;
timelock_address = _timelock_address;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_mint(owner_address, genesis_supply);
// Do a checkpoint for the owner
_writeCheckpoint(owner_address, 0, 0, uint96(genesis_supply));
}
/* ========== RESTRICTED FUNCTIONS ========== */
function setOracle(address new_oracle) external onlyByOwnerOrGovernance {
oracle_address = new_oracle;
}
function setTimelock(address new_timelock) external onlyByOwnerOrGovernance {
timelock_address = new_timelock;
}
function setFRAXAddress(address frax_contract_address) external onlyByOwnerOrGovernance {
FRAX = FRAXStablecoin(frax_contract_address);
}
function setFXSMinDAO(uint256 min_FXS) external onlyByOwnerOrGovernance {
FXS_DAO_min = min_FXS;
}
function setOwner(address _owner_address) external onlyByOwnerOrGovernance {
owner_address = _owner_address;
}
function mint(address to, uint256 amount) public onlyPools {
_mint(to, amount);
}
// This function is what other frax pools will call to mint new FXS (similar to the FRAX mint)
function pool_mint(address m_address, uint256 m_amount) external onlyPools {
if(trackingVotes){
uint32 srcRepNum = numCheckpoints[address(this)];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0;
uint96 srcRepNew = add96(srcRepOld, uint96(m_amount), "pool_mint new votes overflows");
_writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // mint new votes
trackVotes(address(this), m_address, uint96(m_amount));
}
super._mint(m_address, m_amount);
emit FXSMinted(address(this), m_address, m_amount);
}
// This function is what other frax pools will call to burn FXS
function pool_burn_from(address b_address, uint256 b_amount) external onlyPools {
if(trackingVotes){
trackVotes(b_address, address(this), uint96(b_amount));
uint32 srcRepNum = numCheckpoints[address(this)];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, uint96(b_amount), "pool_burn_from new votes underflows");
_writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // burn votes
}
super._burnFrom(b_address, b_amount);
emit FXSBurned(b_address, address(this), b_amount);
}
function toggleVotes() external onlyByOwnerOrGovernance {
trackingVotes = !trackingVotes;
}
/* ========== OVERRIDDEN PUBLIC FUNCTIONS ========== */
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
if(trackingVotes){
// Transfer votes
trackVotes(_msgSender(), recipient, uint96(amount));
}
_transfer(_msgSender(), recipient, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
if(trackingVotes){
// Transfer votes
trackVotes(sender, recipient, uint96(amount));
}
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/* ========== PUBLIC FUNCTIONS ========== */
/**
* @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 (uint96) {
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) public view returns (uint96) {
require(blockNumber < block.number, "FXS::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;
}
/* ========== INTERNAL FUNCTIONS ========== */
// From compound's _moveDelegates
// Keep track of votes. "Delegates" is a misnomer here
function trackVotes(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "FXS::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "FXS::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address voter, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "FXS::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[voter][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[voter] = nCheckpoints + 1;
}
emit VoterVotesChanged(voter, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
/* ========== EVENTS ========== */
/// @notice An event thats emitted when a voters account's vote balance changes
event VoterVotesChanged(address indexed voter, uint previousBalance, uint newBalance);
// Track FXS burned
event FXSBurned(address indexed from, address indexed to, uint256 amount);
// Track FXS minted
event FXSMinted(address indexed from, address indexed to, uint256 amount);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ======================= FRAXStablecoin (FRAX) ======================
// ====================================================================
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
// Reviewer(s) / Contributor(s)
// Sam Sun: https://github.com/samczsun
import "../Common/Context.sol";
import "../ERC20/IERC20.sol";
import "../ERC20/ERC20Custom.sol";
import "../ERC20/ERC20.sol";
import "../Math/SafeMath.sol";
import "../FXS/FXS.sol";
import "./Pools/FraxPool.sol";
import "../Oracle/UniswapPairOracle.sol";
import "../Oracle/ChainlinkETHUSDPriceConsumer.sol";
import "../Governance/AccessControl.sol";
contract FRAXStablecoin is ERC20Custom, AccessControl {
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
enum PriceChoice { FRAX, FXS }
ChainlinkETHUSDPriceConsumer private eth_usd_pricer;
uint8 private eth_usd_pricer_decimals;
UniswapPairOracle private fraxEthOracle;
UniswapPairOracle private fxsEthOracle;
string public symbol;
string public name;
uint8 public constant decimals = 18;
address public owner_address;
address public creator_address;
address public timelock_address; // Governance timelock address
address public controller_address; // Controller contract to dynamically adjust system parameters automatically
address public fxs_address;
address public frax_eth_oracle_address;
address public fxs_eth_oracle_address;
address public weth_address;
address public eth_usd_consumer_address;
uint256 public constant genesis_supply = 2000000e18; // 2M FRAX (only for testing, genesis supply will be 5k on Mainnet). This is to help with establishing the Uniswap pools, as they need liquidity
// The addresses in this array are added by the oracle and these contracts are able to mint frax
address[] public frax_pools_array;
// Mapping is also used for faster verification
mapping(address => bool) public frax_pools;
// Constants for various precisions
uint256 private constant PRICE_PRECISION = 1e6;
uint256 public global_collateral_ratio; // 6 decimals of precision, e.g. 924102 = 0.924102
uint256 public redemption_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee
uint256 public minting_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee
uint256 public frax_step; // Amount to change the collateralization ratio by upon refreshCollateralRatio()
uint256 public refresh_cooldown; // Seconds to wait before being able to run refreshCollateralRatio() again
uint256 public price_target; // The price of FRAX at which the collateral ratio will respond to; this value is only used for the collateral ratio mechanism and not for minting and redeeming which are hardcoded at $1
uint256 public price_band; // The bound above and below the price target at which the refreshCollateralRatio() will not change the collateral ratio
address public DEFAULT_ADMIN_ADDRESS;
bytes32 public constant COLLATERAL_RATIO_PAUSER = keccak256("COLLATERAL_RATIO_PAUSER");
bool public collateral_ratio_paused = false;
/* ========== MODIFIERS ========== */
modifier onlyCollateralRatioPauser() {
require(hasRole(COLLATERAL_RATIO_PAUSER, msg.sender));
_;
}
modifier onlyPools() {
require(frax_pools[msg.sender] == true, "Only frax pools can call this function");
_;
}
modifier onlyByOwnerOrGovernance() {
require(msg.sender == owner_address || msg.sender == timelock_address || msg.sender == controller_address, "You are not the owner, controller, or the governance timelock");
_;
}
modifier onlyByOwnerGovernanceOrPool() {
require(
msg.sender == owner_address
|| msg.sender == timelock_address
|| frax_pools[msg.sender] == true,
"You are not the owner, the governance timelock, or a pool");
_;
}
/* ========== CONSTRUCTOR ========== */
constructor(
string memory _name,
string memory _symbol,
address _creator_address,
address _timelock_address
) public {
name = _name;
symbol = _symbol;
creator_address = _creator_address;
timelock_address = _timelock_address;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
DEFAULT_ADMIN_ADDRESS = _msgSender();
owner_address = _creator_address;
_mint(creator_address, genesis_supply);
grantRole(COLLATERAL_RATIO_PAUSER, creator_address);
grantRole(COLLATERAL_RATIO_PAUSER, timelock_address);
frax_step = 2500; // 6 decimals of precision, equal to 0.25%
global_collateral_ratio = 1000000; // Frax system starts off fully collateralized (6 decimals of precision)
refresh_cooldown = 3600; // Refresh cooldown period is set to 1 hour (3600 seconds) at genesis
price_target = 1000000; // Collateral ratio will adjust according to the $1 price target at genesis
price_band = 5000; // Collateral ratio will not adjust if between $0.995 and $1.005 at genesis
}
/* ========== VIEWS ========== */
// Choice = 'FRAX' or 'FXS' for now
function oracle_price(PriceChoice choice) internal view returns (uint256) {
// Get the ETH / USD price first, and cut it down to 1e6 precision
uint256 eth_usd_price = uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals);
uint256 price_vs_eth;
if (choice == PriceChoice.FRAX) {
price_vs_eth = uint256(fraxEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FRAX if you put in PRICE_PRECISION WETH
}
else if (choice == PriceChoice.FXS) {
price_vs_eth = uint256(fxsEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FXS if you put in PRICE_PRECISION WETH
}
else revert("INVALID PRICE CHOICE. Needs to be either 0 (FRAX) or 1 (FXS)");
// Will be in 1e6 format
return eth_usd_price.mul(PRICE_PRECISION).div(price_vs_eth);
}
// Returns X FRAX = 1 USD
function frax_price() public view returns (uint256) {
return oracle_price(PriceChoice.FRAX);
}
// Returns X FXS = 1 USD
function fxs_price() public view returns (uint256) {
return oracle_price(PriceChoice.FXS);
}
function eth_usd_price() public view returns (uint256) {
return uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals);
}
// This is needed to avoid costly repeat calls to different getter functions
// It is cheaper gas-wise to just dump everything and only use some of the info
function frax_info() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) {
return (
oracle_price(PriceChoice.FRAX), // frax_price()
oracle_price(PriceChoice.FXS), // fxs_price()
totalSupply(), // totalSupply()
global_collateral_ratio, // global_collateral_ratio()
globalCollateralValue(), // globalCollateralValue
minting_fee, // minting_fee()
redemption_fee, // redemption_fee()
uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals) //eth_usd_price
);
}
// Iterate through all frax pools and calculate all value of collateral in all pools globally
function globalCollateralValue() public view returns (uint256) {
uint256 total_collateral_value_d18 = 0;
for (uint i = 0; i < frax_pools_array.length; i++){
// Exclude null addresses
if (frax_pools_array[i] != address(0)){
total_collateral_value_d18 = total_collateral_value_d18.add(FraxPool(frax_pools_array[i]).collatDollarBalance());
}
}
return total_collateral_value_d18;
}
/* ========== PUBLIC FUNCTIONS ========== */
// There needs to be a time interval that this can be called. Otherwise it can be called multiple times per expansion.
uint256 public last_call_time; // Last time the refreshCollateralRatio function was called
function refreshCollateralRatio() public {
require(collateral_ratio_paused == false, "Collateral Ratio has been paused");
uint256 frax_price_cur = frax_price();
require(block.timestamp - last_call_time >= refresh_cooldown, "Must wait for the refresh cooldown since last refresh");
// Step increments are 0.25% (upon genesis, changable by setFraxStep())
if (frax_price_cur > price_target.add(price_band)) { //decrease collateral ratio
if(global_collateral_ratio <= frax_step){ //if within a step of 0, go to 0
global_collateral_ratio = 0;
} else {
global_collateral_ratio = global_collateral_ratio.sub(frax_step);
}
} else if (frax_price_cur < price_target.sub(price_band)) { //increase collateral ratio
if(global_collateral_ratio.add(frax_step) >= 1000000){
global_collateral_ratio = 1000000; // cap collateral ratio at 1.000000
} else {
global_collateral_ratio = global_collateral_ratio.add(frax_step);
}
}
last_call_time = block.timestamp; // Set the time of the last expansion
}
/* ========== RESTRICTED FUNCTIONS ========== */
// Used by pools when user redeems
function pool_burn_from(address b_address, uint256 b_amount) public onlyPools {
super._burnFrom(b_address, b_amount);
emit FRAXBurned(b_address, msg.sender, b_amount);
}
// This function is what other frax pools will call to mint new FRAX
function pool_mint(address m_address, uint256 m_amount) public onlyPools {
super._mint(m_address, m_amount);
emit FRAXMinted(msg.sender, m_address, m_amount);
}
// Adds collateral addresses supported, such as tether and busd, must be ERC20
function addPool(address pool_address) public onlyByOwnerOrGovernance {
require(frax_pools[pool_address] == false, "address already exists");
frax_pools[pool_address] = true;
frax_pools_array.push(pool_address);
}
// Remove a pool
function removePool(address pool_address) public onlyByOwnerOrGovernance {
require(frax_pools[pool_address] == true, "address doesn't exist already");
// Delete from the mapping
delete frax_pools[pool_address];
// 'Delete' from the array by setting the address to 0x0
for (uint i = 0; i < frax_pools_array.length; i++){
if (frax_pools_array[i] == pool_address) {
frax_pools_array[i] = address(0); // This will leave a null in the array and keep the indices the same
break;
}
}
}
function setOwner(address _owner_address) external onlyByOwnerOrGovernance {
owner_address = _owner_address;
}
function setRedemptionFee(uint256 red_fee) public onlyByOwnerOrGovernance {
redemption_fee = red_fee;
}
function setMintingFee(uint256 min_fee) public onlyByOwnerOrGovernance {
minting_fee = min_fee;
}
function setFraxStep(uint256 _new_step) public onlyByOwnerOrGovernance {
frax_step = _new_step;
}
function setPriceTarget (uint256 _new_price_target) public onlyByOwnerOrGovernance {
price_target = _new_price_target;
}
function setRefreshCooldown(uint256 _new_cooldown) public onlyByOwnerOrGovernance {
refresh_cooldown = _new_cooldown;
}
function setFXSAddress(address _fxs_address) public onlyByOwnerOrGovernance {
fxs_address = _fxs_address;
}
function setETHUSDOracle(address _eth_usd_consumer_address) public onlyByOwnerOrGovernance {
eth_usd_consumer_address = _eth_usd_consumer_address;
eth_usd_pricer = ChainlinkETHUSDPriceConsumer(eth_usd_consumer_address);
eth_usd_pricer_decimals = eth_usd_pricer.getDecimals();
}
function setTimelock(address new_timelock) external onlyByOwnerOrGovernance {
timelock_address = new_timelock;
}
function setController(address _controller_address) external onlyByOwnerOrGovernance {
controller_address = _controller_address;
}
function setPriceBand(uint256 _price_band) external onlyByOwnerOrGovernance {
price_band = _price_band;
}
// Sets the FRAX_ETH Uniswap oracle address
function setFRAXEthOracle(address _frax_oracle_addr, address _weth_address) public onlyByOwnerOrGovernance {
frax_eth_oracle_address = _frax_oracle_addr;
fraxEthOracle = UniswapPairOracle(_frax_oracle_addr);
weth_address = _weth_address;
}
// Sets the FXS_ETH Uniswap oracle address
function setFXSEthOracle(address _fxs_oracle_addr, address _weth_address) public onlyByOwnerOrGovernance {
fxs_eth_oracle_address = _fxs_oracle_addr;
fxsEthOracle = UniswapPairOracle(_fxs_oracle_addr);
weth_address = _weth_address;
}
function toggleCollateralRatio() public onlyCollateralRatioPauser {
collateral_ratio_paused = !collateral_ratio_paused;
}
/* ========== EVENTS ========== */
// Track FRAX burned
event FRAXBurned(address indexed from, address indexed to, uint256 amount);
// Track FRAX minted
event FRAXMinted(address indexed from, address indexed to, uint256 amount);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "../Common/Context.sol";
import "./IERC20.sol";
import "../Math/SafeMath.sol";
import "../Utils/Address.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 {ERC20Mintable}.
*
* 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;
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.approve(address spender, uint256 amount)
*/
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 the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for `accounts`'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(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 is 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 Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal virtual {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
/**
* @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:using-hooks.adoc[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
/**
*Submitted for verification at Etherscan.io on 2020-03-04
*/
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
contract Comp {
/// @notice EIP-20 token name for this token
string public constant name = "Compound";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "COMP";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public constant totalSupply = 10000000e18; // 10 million Comp
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 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 The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Comp token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Comp::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Comp::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
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) public {
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), "Comp::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Comp::delegateBySig: invalid nonce");
require(now <= expiry, "Comp::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 (uint96) {
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) public view returns (uint96) {
require(blockNumber < block.number, "Comp::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];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Comp::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Comp::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Comp::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Comp::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Comp::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Comp::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Comp::_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 safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import '../Uniswap/Interfaces/IUniswapV2Factory.sol';
import '../Uniswap/Interfaces/IUniswapV2Pair.sol';
import '../Math/FixedPoint.sol';
import '../Uniswap/UniswapV2OracleLibrary.sol';
import '../Uniswap/UniswapV2Library.sol';
// Fixed window oracle that recomputes the average price for the entire period once every period
// Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period
contract UniswapPairOracle {
using FixedPoint for *;
address owner_address;
address timelock_address;
uint public PERIOD = 3600; // 1 hour TWAP (time-weighted average price)
uint public CONSULT_LENIENCY = 120; // Used for being able to consult past the period end
bool public ALLOW_STALE_CONSULTS = false; // If false, consult() will fail if the TWAP is stale
IUniswapV2Pair public immutable pair;
address public immutable token0;
address public immutable token1;
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint32 public blockTimestampLast;
FixedPoint.uq112x112 public price0Average;
FixedPoint.uq112x112 public price1Average;
modifier onlyByOwnerOrGovernance() {
require(msg.sender == owner_address || msg.sender == timelock_address, "You are not an owner or the governance timelock");
_;
}
constructor(address factory, address tokenA, address tokenB, address _owner_address, address _timelock_address) public {
IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB));
pair = _pair;
token0 = _pair.token0();
token1 = _pair.token1();
price0CumulativeLast = _pair.price0CumulativeLast(); // Fetch the current accumulated price value (1 / 0)
price1CumulativeLast = _pair.price1CumulativeLast(); // Fetch the current accumulated price value (0 / 1)
uint112 reserve0;
uint112 reserve1;
(reserve0, reserve1, blockTimestampLast) = _pair.getReserves();
require(reserve0 != 0 && reserve1 != 0, 'UniswapPairOracle: NO_RESERVES'); // Ensure that there's liquidity in the pair
owner_address = _owner_address;
timelock_address = _timelock_address;
}
function setOwner(address _owner_address) external onlyByOwnerOrGovernance {
owner_address = _owner_address;
}
function setTimelock(address _timelock_address) external onlyByOwnerOrGovernance {
timelock_address = _timelock_address;
}
function setPeriod(uint _period) external onlyByOwnerOrGovernance {
PERIOD = _period;
}
function setConsultLeniency(uint _consult_leniency) external onlyByOwnerOrGovernance {
CONSULT_LENIENCY = _consult_leniency;
}
function setAllowStaleConsults(bool _allow_stale_consults) external onlyByOwnerOrGovernance {
ALLOW_STALE_CONSULTS = _allow_stale_consults;
}
// Check if update() can be called instead of wasting gas calling it
function canUpdate() public view returns (bool) {
uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp();
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired
return (timeElapsed >= PERIOD);
}
function update() external {
(uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) =
UniswapV2OracleLibrary.currentCumulativePrices(address(pair));
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired
// Ensure that at least one full period has passed since the last update
require(timeElapsed >= PERIOD, 'UniswapPairOracle: PERIOD_NOT_ELAPSED');
// Overflow is desired, casting never truncates
// Cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed));
price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed));
price0CumulativeLast = price0Cumulative;
price1CumulativeLast = price1Cumulative;
blockTimestampLast = blockTimestamp;
}
// Note this will always return 0 before update has been called successfully for the first time.
function consult(address token, uint amountIn) external view returns (uint amountOut) {
uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp();
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired
// Ensure that the price is not stale
require((timeElapsed < (PERIOD + CONSULT_LENIENCY)) || ALLOW_STALE_CONSULTS, 'UniswapPairOracle: PRICE_IS_STALE_NEED_TO_CALL_UPDATE');
if (token == token0) {
amountOut = price0Average.mul(amountIn).decode144();
} else {
require(token == token1, 'UniswapPairOracle: INVALID_TOKEN');
amountOut = price1Average.mul(amountIn).decode144();
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../Utils/EnumerableSet.sol";
import "../Utils/Address.sol";
import "../Common/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; //bytes32(uint256(0x4B437D01b575618140442A4975db38850e3f8f5f) << 96);
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev 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) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ============================= FraxPool =============================
// ====================================================================
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
// Reviewer(s) / Contributor(s)
// Sam Sun: https://github.com/samczsun
import "../../Math/SafeMath.sol";
import "../../FXS/FXS.sol";
import "../../Frax/Frax.sol";
import "../../ERC20/ERC20.sol";
import "../../Oracle/UniswapPairOracle.sol";
import "../../Governance/AccessControl.sol";
import "./FraxPoolLibrary.sol";
contract FraxPool is AccessControl {
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
ERC20 private collateral_token;
address private collateral_address;
address private owner_address;
address private frax_contract_address;
address private fxs_contract_address;
address private timelock_address;
FRAXShares private FXS;
FRAXStablecoin private FRAX;
UniswapPairOracle private collatEthOracle;
address public collat_eth_oracle_address;
address private weth_address;
uint256 public minting_fee;
uint256 public redemption_fee;
uint256 public buyback_fee;
uint256 public recollat_fee;
mapping (address => uint256) public redeemFXSBalances;
mapping (address => uint256) public redeemCollateralBalances;
uint256 public unclaimedPoolCollateral;
uint256 public unclaimedPoolFXS;
mapping (address => uint256) public lastRedeemed;
// Constants for various precisions
uint256 private constant PRICE_PRECISION = 1e6;
uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6;
uint256 private constant COLLATERAL_RATIO_MAX = 1e6;
// Number of decimals needed to get to 18
uint256 private immutable missing_decimals;
// Pool_ceiling is the total units of collateral that a pool contract can hold
uint256 public pool_ceiling = 0;
// Stores price of the collateral, if price is paused
uint256 public pausedPrice = 0;
// Bonus rate on FXS minted during recollateralizeFRAX(); 6 decimals of precision, set to 0.75% on genesis
uint256 public bonus_rate = 7500;
// Number of blocks to wait before being able to collectRedemption()
uint256 public redemption_delay = 1;
// AccessControl Roles
bytes32 private constant MINT_PAUSER = keccak256("MINT_PAUSER");
bytes32 private constant REDEEM_PAUSER = keccak256("REDEEM_PAUSER");
bytes32 private constant BUYBACK_PAUSER = keccak256("BUYBACK_PAUSER");
bytes32 private constant RECOLLATERALIZE_PAUSER = keccak256("RECOLLATERALIZE_PAUSER");
bytes32 private constant COLLATERAL_PRICE_PAUSER = keccak256("COLLATERAL_PRICE_PAUSER");
// AccessControl state variables
bool public mintPaused = false;
bool public redeemPaused = false;
bool public recollateralizePaused = false;
bool public buyBackPaused = false;
bool public collateralPricePaused = false;
/* ========== MODIFIERS ========== */
modifier onlyByOwnerOrGovernance() {
require(msg.sender == timelock_address || msg.sender == owner_address, "You are not the owner or the governance timelock");
_;
}
modifier notRedeemPaused() {
require(redeemPaused == false, "Redeeming is paused");
_;
}
modifier notMintPaused() {
require(mintPaused == false, "Minting is paused");
_;
}
/* ========== CONSTRUCTOR ========== */
constructor(
address _frax_contract_address,
address _fxs_contract_address,
address _collateral_address,
address _creator_address,
address _timelock_address,
uint256 _pool_ceiling
) public {
FRAX = FRAXStablecoin(_frax_contract_address);
FXS = FRAXShares(_fxs_contract_address);
frax_contract_address = _frax_contract_address;
fxs_contract_address = _fxs_contract_address;
collateral_address = _collateral_address;
timelock_address = _timelock_address;
owner_address = _creator_address;
collateral_token = ERC20(_collateral_address);
pool_ceiling = _pool_ceiling;
missing_decimals = uint(18).sub(collateral_token.decimals());
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
grantRole(MINT_PAUSER, timelock_address);
grantRole(REDEEM_PAUSER, timelock_address);
grantRole(RECOLLATERALIZE_PAUSER, timelock_address);
grantRole(BUYBACK_PAUSER, timelock_address);
grantRole(COLLATERAL_PRICE_PAUSER, timelock_address);
}
/* ========== VIEWS ========== */
// Returns dollar value of collateral held in this Frax pool
function collatDollarBalance() public view returns (uint256) {
if(collateralPricePaused == true){
return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(pausedPrice).div(PRICE_PRECISION);
} else {
uint256 eth_usd_price = FRAX.eth_usd_price();
uint256 eth_collat_price = collatEthOracle.consult(weth_address, (PRICE_PRECISION * (10 ** missing_decimals)));
uint256 collat_usd_price = eth_usd_price.mul(PRICE_PRECISION).div(eth_collat_price);
return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(collat_usd_price).div(PRICE_PRECISION); //.mul(getCollateralPrice()).div(1e6);
}
}
// Returns the value of excess collateral held in this Frax pool, compared to what is needed to maintain the global collateral ratio
function availableExcessCollatDV() public view returns (uint256) {
uint256 total_supply = FRAX.totalSupply();
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
uint256 global_collat_value = FRAX.globalCollateralValue();
if (global_collateral_ratio > COLLATERAL_RATIO_PRECISION) global_collateral_ratio = COLLATERAL_RATIO_PRECISION; // Handles an overcollateralized contract with CR > 1
uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(COLLATERAL_RATIO_PRECISION); // Calculates collateral needed to back each 1 FRAX with $1 of collateral at current collat ratio
if (global_collat_value > required_collat_dollar_value_d18) return global_collat_value.sub(required_collat_dollar_value_d18);
else return 0;
}
/* ========== PUBLIC FUNCTIONS ========== */
// Returns the price of the pool collateral in USD
function getCollateralPrice() public view returns (uint256) {
if(collateralPricePaused == true){
return pausedPrice;
} else {
uint256 eth_usd_price = FRAX.eth_usd_price();
return eth_usd_price.mul(PRICE_PRECISION).div(collatEthOracle.consult(weth_address, PRICE_PRECISION * (10 ** missing_decimals)));
}
}
function setCollatETHOracle(address _collateral_weth_oracle_address, address _weth_address) external onlyByOwnerOrGovernance {
collat_eth_oracle_address = _collateral_weth_oracle_address;
collatEthOracle = UniswapPairOracle(_collateral_weth_oracle_address);
weth_address = _weth_address;
}
// We separate out the 1t1, fractional and algorithmic minting functions for gas efficiency
function mint1t1FRAX(uint256 collateral_amount, uint256 FRAX_out_min) external notMintPaused {
uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals);
require(FRAX.global_collateral_ratio() >= COLLATERAL_RATIO_MAX, "Collateral ratio must be >= 1");
require((collateral_token.balanceOf(address(this))).sub(unclaimedPoolCollateral).add(collateral_amount) <= pool_ceiling, "[Pool's Closed]: Ceiling reached");
(uint256 frax_amount_d18) = FraxPoolLibrary.calcMint1t1FRAX(
getCollateralPrice(),
collateral_amount_d18
); //1 FRAX for each $1 worth of collateral
frax_amount_d18 = (frax_amount_d18.mul(uint(1e6).sub(minting_fee))).div(1e6); //remove precision at the end
require(FRAX_out_min <= frax_amount_d18, "Slippage limit reached");
collateral_token.transferFrom(msg.sender, address(this), collateral_amount);
FRAX.pool_mint(msg.sender, frax_amount_d18);
}
// 0% collateral-backed
function mintAlgorithmicFRAX(uint256 fxs_amount_d18, uint256 FRAX_out_min) external notMintPaused {
uint256 fxs_price = FRAX.fxs_price();
require(FRAX.global_collateral_ratio() == 0, "Collateral ratio must be 0");
(uint256 frax_amount_d18) = FraxPoolLibrary.calcMintAlgorithmicFRAX(
fxs_price, // X FXS / 1 USD
fxs_amount_d18
);
frax_amount_d18 = (frax_amount_d18.mul(uint(1e6).sub(minting_fee))).div(1e6);
require(FRAX_out_min <= frax_amount_d18, "Slippage limit reached");
FXS.pool_burn_from(msg.sender, fxs_amount_d18);
FRAX.pool_mint(msg.sender, frax_amount_d18);
}
// Will fail if fully collateralized or fully algorithmic
// > 0% and < 100% collateral-backed
function mintFractionalFRAX(uint256 collateral_amount, uint256 fxs_amount, uint256 FRAX_out_min) external notMintPaused {
uint256 fxs_price = FRAX.fxs_price();
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999");
require(collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral).add(collateral_amount) <= pool_ceiling, "Pool ceiling reached, no more FRAX can be minted with this collateral");
uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals);
FraxPoolLibrary.MintFF_Params memory input_params = FraxPoolLibrary.MintFF_Params(
fxs_price,
getCollateralPrice(),
fxs_amount,
collateral_amount_d18,
global_collateral_ratio
);
(uint256 mint_amount, uint256 fxs_needed) = FraxPoolLibrary.calcMintFractionalFRAX(input_params);
mint_amount = (mint_amount.mul(uint(1e6).sub(minting_fee))).div(1e6);
require(FRAX_out_min <= mint_amount, "Slippage limit reached");
require(fxs_needed <= fxs_amount, "Not enough FXS inputted");
FXS.pool_burn_from(msg.sender, fxs_needed);
collateral_token.transferFrom(msg.sender, address(this), collateral_amount);
FRAX.pool_mint(msg.sender, mint_amount);
}
// Redeem collateral. 100% collateral-backed
function redeem1t1FRAX(uint256 FRAX_amount, uint256 COLLATERAL_out_min) external notRedeemPaused {
require(FRAX.global_collateral_ratio() == COLLATERAL_RATIO_MAX, "Collateral ratio must be == 1");
// Need to adjust for decimals of collateral
uint256 FRAX_amount_precision = FRAX_amount.div(10 ** missing_decimals);
(uint256 collateral_needed) = FraxPoolLibrary.calcRedeem1t1FRAX(
getCollateralPrice(),
FRAX_amount_precision
);
collateral_needed = (collateral_needed.mul(uint(1e6).sub(redemption_fee))).div(1e6);
require(collateral_needed <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), "Not enough collateral in pool");
require(COLLATERAL_out_min <= collateral_needed, "Slippage limit reached");
redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_needed);
unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_needed);
lastRedeemed[msg.sender] = block.number;
// Move all external functions to the end
FRAX.pool_burn_from(msg.sender, FRAX_amount);
}
// Will fail if fully collateralized or algorithmic
// Redeem FRAX for collateral and FXS. > 0% and < 100% collateral-backed
function redeemFractionalFRAX(uint256 FRAX_amount, uint256 FXS_out_min, uint256 COLLATERAL_out_min) external notRedeemPaused {
uint256 fxs_price = FRAX.fxs_price();
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999");
uint256 col_price_usd = getCollateralPrice();
uint256 FRAX_amount_post_fee = (FRAX_amount.mul(uint(1e6).sub(redemption_fee))).div(PRICE_PRECISION);
uint256 fxs_dollar_value_d18 = FRAX_amount_post_fee.sub(FRAX_amount_post_fee.mul(global_collateral_ratio).div(PRICE_PRECISION));
uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price);
// Need to adjust for decimals of collateral
uint256 FRAX_amount_precision = FRAX_amount_post_fee.div(10 ** missing_decimals);
uint256 collateral_dollar_value = FRAX_amount_precision.mul(global_collateral_ratio).div(PRICE_PRECISION);
uint256 collateral_amount = collateral_dollar_value.mul(PRICE_PRECISION).div(col_price_usd);
require(collateral_amount <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), "Not enough collateral in pool");
require(COLLATERAL_out_min <= collateral_amount, "Slippage limit reached [collateral]");
require(FXS_out_min <= fxs_amount, "Slippage limit reached [FXS]");
redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_amount);
unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_amount);
redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount);
unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount);
lastRedeemed[msg.sender] = block.number;
// Move all external functions to the end
FRAX.pool_burn_from(msg.sender, FRAX_amount);
FXS.pool_mint(address(this), fxs_amount);
}
// Redeem FRAX for FXS. 0% collateral-backed
function redeemAlgorithmicFRAX(uint256 FRAX_amount, uint256 FXS_out_min) external notRedeemPaused {
uint256 fxs_price = FRAX.fxs_price();
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
require(global_collateral_ratio == 0, "Collateral ratio must be 0");
uint256 fxs_dollar_value_d18 = FRAX_amount;
fxs_dollar_value_d18 = (fxs_dollar_value_d18.mul(uint(1e6).sub(redemption_fee))).div(PRICE_PRECISION); //apply fees
uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price);
redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount);
unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount);
lastRedeemed[msg.sender] = block.number;
require(FXS_out_min <= fxs_amount, "Slippage limit reached");
// Move all external functions to the end
FRAX.pool_burn_from(msg.sender, FRAX_amount);
FXS.pool_mint(address(this), fxs_amount);
}
// After a redemption happens, transfer the newly minted FXS and owed collateral from this pool
// contract to the user. Redemption is split into two functions to prevent flash loans from being able
// to take out FRAX/collateral from the system, use an AMM to trade the new price, and then mint back into the system.
function collectRedemption() external {
require((lastRedeemed[msg.sender].add(redemption_delay)) <= block.number, "Must wait for redemption_delay blocks before collecting redemption");
bool sendFXS = false;
bool sendCollateral = false;
uint FXSAmount;
uint CollateralAmount;
// Use Checks-Effects-Interactions pattern
if(redeemFXSBalances[msg.sender] > 0){
FXSAmount = redeemFXSBalances[msg.sender];
redeemFXSBalances[msg.sender] = 0;
unclaimedPoolFXS = unclaimedPoolFXS.sub(FXSAmount);
sendFXS = true;
}
if(redeemCollateralBalances[msg.sender] > 0){
CollateralAmount = redeemCollateralBalances[msg.sender];
redeemCollateralBalances[msg.sender] = 0;
unclaimedPoolCollateral = unclaimedPoolCollateral.sub(CollateralAmount);
sendCollateral = true;
}
if(sendFXS == true){
FXS.transfer(msg.sender, FXSAmount);
}
if(sendCollateral == true){
collateral_token.transfer(msg.sender, CollateralAmount);
}
}
// When the protocol is recollateralizing, we need to give a discount of FXS to hit the new CR target
// Thus, if the target collateral ratio is higher than the actual value of collateral, minters get FXS for adding collateral
// This function simply rewards anyone that sends collateral to a pool with the same amount of FXS + the bonus rate
// Anyone can call this function to recollateralize the protocol and take the extra FXS value from the bonus rate as an arb opportunity
function recollateralizeFRAX(uint256 collateral_amount, uint256 FXS_out_min) external {
require(recollateralizePaused == false, "Recollateralize is paused");
uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals);
uint256 fxs_price = FRAX.fxs_price();
uint256 frax_total_supply = FRAX.totalSupply();
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
uint256 global_collat_value = FRAX.globalCollateralValue();
(uint256 collateral_units, uint256 amount_to_recollat) = FraxPoolLibrary.calcRecollateralizeFRAXInner(
collateral_amount_d18,
getCollateralPrice(),
global_collat_value,
frax_total_supply,
global_collateral_ratio
);
uint256 collateral_units_precision = collateral_units.div(10 ** missing_decimals);
uint256 fxs_paid_back = amount_to_recollat.mul(uint(1e6).add(bonus_rate).sub(recollat_fee)).div(fxs_price);
require(FXS_out_min <= fxs_paid_back, "Slippage limit reached");
collateral_token.transferFrom(msg.sender, address(this), collateral_units_precision);
FXS.pool_mint(msg.sender, fxs_paid_back);
}
// Function can be called by an FXS holder to have the protocol buy back FXS with excess collateral value from a desired collateral pool
// This can also happen if the collateral ratio > 1
function buyBackFXS(uint256 FXS_amount, uint256 COLLATERAL_out_min) external {
require(buyBackPaused == false, "Buyback is paused");
uint256 fxs_price = FRAX.fxs_price();
FraxPoolLibrary.BuybackFXS_Params memory input_params = FraxPoolLibrary.BuybackFXS_Params(
availableExcessCollatDV(),
fxs_price,
getCollateralPrice(),
FXS_amount
);
(uint256 collateral_equivalent_d18) = (FraxPoolLibrary.calcBuyBackFXS(input_params)).mul(uint(1e6).sub(buyback_fee)).div(1e6);
uint256 collateral_precision = collateral_equivalent_d18.div(10 ** missing_decimals);
require(COLLATERAL_out_min <= collateral_precision, "Slippage limit reached");
// Give the sender their desired collateral and burn the FXS
FXS.pool_burn_from(msg.sender, FXS_amount);
collateral_token.transfer(msg.sender, collateral_precision);
}
/* ========== RESTRICTED FUNCTIONS ========== */
function toggleMinting() external {
require(hasRole(MINT_PAUSER, msg.sender));
mintPaused = !mintPaused;
}
function toggleRedeeming() external {
require(hasRole(REDEEM_PAUSER, msg.sender));
redeemPaused = !redeemPaused;
}
function toggleRecollateralize() external {
require(hasRole(RECOLLATERALIZE_PAUSER, msg.sender));
recollateralizePaused = !recollateralizePaused;
}
function toggleBuyBack() external {
require(hasRole(BUYBACK_PAUSER, msg.sender));
buyBackPaused = !buyBackPaused;
}
function toggleCollateralPrice(uint256 _new_price) external {
require(hasRole(COLLATERAL_PRICE_PAUSER, msg.sender));
// If pausing, set paused price; else if unpausing, clear pausedPrice
if(collateralPricePaused == false){
pausedPrice = _new_price;
} else {
pausedPrice = 0;
}
collateralPricePaused = !collateralPricePaused;
}
// 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;
}
function setTimelock(address new_timelock) external onlyByOwnerOrGovernance {
timelock_address = new_timelock;
}
function setOwner(address _owner_address) external onlyByOwnerOrGovernance {
owner_address = _owner_address;
}
/* ========== EVENTS ========== */
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import '../../ERC20/IERC20.sol';
// Original at https://etherscan.io/address/0xb092b4601850E23903A42EaCBc9D8A0EeC26A4d5
// Some functions were omitted for brevity. See the contract for details
interface ICREAM_crFRAX is IERC20 {
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external view returns (uint);
function borrowBalanceCurrent(address account) external view returns (uint);
function borrowBalanceStored(address account) external view returns (uint);
function exchangeRateCurrent() external view returns (uint);
function exchangeRateStored() external view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() external returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
}
// pragma solidity ^0.5.16;
// import "./ComptrollerInterface.sol";
// import "./CTokenInterfaces.sol";
// import "./ErrorReporter.sol";
// import "./Exponential.sol";
// import "./EIP20Interface.sol";
// import "./EIP20NonStandardInterface.sol";
// import "./InterestRateModel.sol";
// /**
// * @title Compound's CToken Contract
// * @notice Abstract base for CTokens
// * @author Compound
// */
// contract CToken is CTokenInterface, Exponential, TokenErrorReporter {
// /**
// * @notice Initialize the money market
// * @param comptroller_ The address of the Comptroller
// * @param interestRateModel_ The address of the interest rate model
// * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
// * @param name_ EIP-20 name of this token
// * @param symbol_ EIP-20 symbol of this token
// * @param decimals_ EIP-20 decimal precision of this token
// */
// function initialize(ComptrollerInterface comptroller_,
// InterestRateModel interestRateModel_,
// uint initialExchangeRateMantissa_,
// string memory name_,
// string memory symbol_,
// uint8 decimals_) public {
// require(msg.sender == admin, "only admin may initialize the market");
// require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// // Set initial exchange rate
// initialExchangeRateMantissa = initialExchangeRateMantissa_;
// require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// // Set the comptroller
// uint err = _setComptroller(comptroller_);
// require(err == uint(Error.NO_ERROR), "setting comptroller failed");
// // Initialize block number and borrow index (block number mocks depend on comptroller being set)
// accrualBlockNumber = getBlockNumber();
// borrowIndex = mantissaOne;
// // Set the interest rate model (depends on block number / borrow index)
// err = _setInterestRateModelFresh(interestRateModel_);
// require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
// name = name_;
// symbol = symbol_;
// decimals = decimals_;
// // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
// _notEntered = true;
// }
// /**
// * @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
// * @dev Called by both `transfer` and `transferFrom` internally
// * @param spender The address of the account performing the transfer
// * @param src The address of the source account
// * @param dst The address of the destination account
// * @param tokens The number of tokens to transfer
// * @return Whether or not the transfer succeeded
// */
// function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
// /* Fail if transfer not allowed */
// uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
// if (allowed != 0) {
// return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
// }
// /* Do not allow self-transfers */
// if (src == dst) {
// return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
// }
// /* Get the allowance, infinite for the account owner */
// uint startingAllowance = 0;
// if (spender == src) {
// startingAllowance = uint(-1);
// } else {
// startingAllowance = transferAllowances[src][spender];
// }
// /* Do the calculations, checking for {under,over}flow */
// MathError mathErr;
// uint allowanceNew;
// uint srcTokensNew;
// uint dstTokensNew;
// (mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
// if (mathErr != MathError.NO_ERROR) {
// return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
// }
// (mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);
// if (mathErr != MathError.NO_ERROR) {
// return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
// }
// (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
// if (mathErr != MathError.NO_ERROR) {
// return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
// }
// /////////////////////////
// // EFFECTS & INTERACTIONS
// // (No safe failures beyond this point)
// accountTokens[src] = srcTokensNew;
// accountTokens[dst] = dstTokensNew;
// /* Eat some of the allowance (if necessary) */
// if (startingAllowance != uint(-1)) {
// transferAllowances[src][spender] = allowanceNew;
// }
// /* We emit a Transfer event */
// emit Transfer(src, dst, tokens);
// comptroller.transferVerify(address(this), src, dst, tokens);
// return uint(Error.NO_ERROR);
// }
// /**
// * @notice Transfer `amount` tokens from `msg.sender` to `dst`
// * @param dst The address of the destination account
// * @param amount The number of tokens to transfer
// * @return Whether or not the transfer succeeded
// */
// function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
// return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
// }
// /**
// * @notice Transfer `amount` tokens from `src` to `dst`
// * @param src The address of the source account
// * @param dst The address of the destination account
// * @param amount The number of tokens to transfer
// * @return Whether or not the transfer succeeded
// */
// function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
// return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
// }
// /**
// * @notice Approve `spender` to transfer up to `amount` from `src`
// * @dev This will overwrite the approval amount for `spender`
// * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
// * @param spender The address of the account which may transfer tokens
// * @param amount The number of tokens that are approved (-1 means infinite)
// * @return Whether or not the approval succeeded
// */
// function approve(address spender, uint256 amount) external returns (bool) {
// address src = msg.sender;
// transferAllowances[src][spender] = amount;
// emit Approval(src, spender, amount);
// return true;
// }
// /**
// * @notice Get the current allowance from `owner` for `spender`
// * @param owner The address of the account which owns the tokens to be spent
// * @param spender The address of the account which may transfer tokens
// * @return The number of tokens allowed to be spent (-1 means infinite)
// */
// function allowance(address owner, address spender) external view returns (uint256) {
// return transferAllowances[owner][spender];
// }
// /**
// * @notice Get the token balance of the `owner`
// * @param owner The address of the account to query
// * @return The number of tokens owned by `owner`
// */
// function balanceOf(address owner) external view returns (uint256) {
// return accountTokens[owner];
// }
// /**
// * @notice Get the underlying balance of the `owner`
// * @dev This also accrues interest in a transaction
// * @param owner The address of the account to query
// * @return The amount of underlying owned by `owner`
// */
// function balanceOfUnderlying(address owner) external returns (uint) {
// Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
// (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
// require(mErr == MathError.NO_ERROR, "balance could not be calculated");
// return balance;
// }
// /**
// * @notice Get a snapshot of the account's balances, and the cached exchange rate
// * @dev This is used by comptroller to more efficiently perform liquidity checks.
// * @param account Address of the account to snapshot
// * @return (possible error, token balance, borrow balance, exchange rate mantissa)
// */
// function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
// uint cTokenBalance = accountTokens[account];
// uint borrowBalance;
// uint exchangeRateMantissa;
// MathError mErr;
// (mErr, borrowBalance) = borrowBalanceStoredInternal(account);
// if (mErr != MathError.NO_ERROR) {
// return (uint(Error.MATH_ERROR), 0, 0, 0);
// }
// (mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
// if (mErr != MathError.NO_ERROR) {
// return (uint(Error.MATH_ERROR), 0, 0, 0);
// }
// return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);
// }
// /**
// * @dev Function to simply retrieve block number
// * This exists mainly for inheriting test contracts to stub this result.
// */
// function getBlockNumber() internal view returns (uint) {
// return block.number;
// }
// /**
// * @notice Returns the current per-block borrow interest rate for this cToken
// * @return The borrow interest rate per block, scaled by 1e18
// */
// function borrowRatePerBlock() external view returns (uint) {
// return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
// }
// /**
// * @notice Returns the current per-block supply interest rate for this cToken
// * @return The supply interest rate per block, scaled by 1e18
// */
// function supplyRatePerBlock() external view returns (uint) {
// return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
// }
// /**
// * @notice Returns the current total borrows plus accrued interest
// * @return The total borrows with interest
// */
// function totalBorrowsCurrent() external nonReentrant returns (uint) {
// require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
// return totalBorrows;
// }
// /**
// * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
// * @param account The address whose balance should be calculated after updating borrowIndex
// * @return The calculated balance
// */
// function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
// require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
// return borrowBalanceStored(account);
// }
// /**
// * @notice Return the borrow balance of account based on stored data
// * @param account The address whose balance should be calculated
// * @return The calculated balance
// */
// function borrowBalanceStored(address account) public view returns (uint) {
// (MathError err, uint result) = borrowBalanceStoredInternal(account);
// require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
// return result;
// }
// /**
// * @notice Return the borrow balance of account based on stored data
// * @param account The address whose balance should be calculated
// * @return (error code, the calculated balance or 0 if error code is non-zero)
// */
// function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
// /* Note: we do not assert that the market is up to date */
// MathError mathErr;
// uint principalTimesIndex;
// uint result;
// /* Get borrowBalance and borrowIndex */
// BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
// /* If borrowBalance = 0 then borrowIndex is likely also 0.
// * Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
// */
// if (borrowSnapshot.principal == 0) {
// return (MathError.NO_ERROR, 0);
// }
// /* Calculate new borrow balance using the interest index:
// * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
// */
// (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
// if (mathErr != MathError.NO_ERROR) {
// return (mathErr, 0);
// }
// (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
// if (mathErr != MathError.NO_ERROR) {
// return (mathErr, 0);
// }
// return (MathError.NO_ERROR, result);
// }
// /**
// * @notice Accrue interest then return the up-to-date exchange rate
// * @return Calculated exchange rate scaled by 1e18
// */
// function exchangeRateCurrent() public nonReentrant returns (uint) {
// require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
// return exchangeRateStored();
// }
// /**
// * @notice Calculates the exchange rate from the underlying to the CToken
// * @dev This function does not accrue interest before calculating the exchange rate
// * @return Calculated exchange rate scaled by 1e18
// */
// function exchangeRateStored() public view returns (uint) {
// (MathError err, uint result) = exchangeRateStoredInternal();
// require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
// return result;
// }
// /**
// * @notice Calculates the exchange rate from the underlying to the CToken
// * @dev This function does not accrue interest before calculating the exchange rate
// * @return (error code, calculated exchange rate scaled by 1e18)
// */
// function exchangeRateStoredInternal() internal view returns (MathError, uint) {
// uint _totalSupply = totalSupply;
// if (_totalSupply == 0) {
// /*
// * If there are no tokens minted:
// * exchangeRate = initialExchangeRate
// */
// return (MathError.NO_ERROR, initialExchangeRateMantissa);
// } else {
// /*
// * Otherwise:
// * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
// */
// uint totalCash = getCashPrior();
// uint cashPlusBorrowsMinusReserves;
// Exp memory exchangeRate;
// MathError mathErr;
// (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
// if (mathErr != MathError.NO_ERROR) {
// return (mathErr, 0);
// }
// (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
// if (mathErr != MathError.NO_ERROR) {
// return (mathErr, 0);
// }
// return (MathError.NO_ERROR, exchangeRate.mantissa);
// }
// }
// /**
// * @notice Get cash balance of this cToken in the underlying asset
// * @return The quantity of underlying asset owned by this contract
// */
// function getCash() external view returns (uint) {
// return getCashPrior();
// }
// /**
// * @notice Applies accrued interest to total borrows and reserves
// * @dev This calculates interest accrued from the last checkpointed block
// * up to the current block and writes new checkpoint to storage.
// */
// function accrueInterest() public returns (uint) {
// /* Remember the initial block number */
// uint currentBlockNumber = getBlockNumber();
// uint accrualBlockNumberPrior = accrualBlockNumber;
// /* Short-circuit accumulating 0 interest */
// if (accrualBlockNumberPrior == currentBlockNumber) {
// return uint(Error.NO_ERROR);
// }
// /* Read the previous values out of storage */
// uint cashPrior = getCashPrior();
// uint borrowsPrior = totalBorrows;
// uint reservesPrior = totalReserves;
// uint borrowIndexPrior = borrowIndex;
// /* Calculate the current borrow interest rate */
// uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
// require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
// /* Calculate the number of blocks elapsed since the last accrual */
// (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
// require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
// /*
// * Calculate the interest accumulated into borrows and reserves and the new index:
// * simpleInterestFactor = borrowRate * blockDelta
// * interestAccumulated = simpleInterestFactor * totalBorrows
// * totalBorrowsNew = interestAccumulated + totalBorrows
// * totalReservesNew = interestAccumulated * reserveFactor + totalReserves
// * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
// */
// Exp memory simpleInterestFactor;
// uint interestAccumulated;
// uint totalBorrowsNew;
// uint totalReservesNew;
// uint borrowIndexNew;
// (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
// if (mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
// }
// (mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
// if (mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
// }
// (mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
// if (mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
// }
// (mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
// if (mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
// }
// (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
// if (mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
// }
// /////////////////////////
// // EFFECTS & INTERACTIONS
// // (No safe failures beyond this point)
// /* We write the previously calculated values into storage */
// accrualBlockNumber = currentBlockNumber;
// borrowIndex = borrowIndexNew;
// totalBorrows = totalBorrowsNew;
// totalReserves = totalReservesNew;
// /* We emit an AccrueInterest event */
// emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
// return uint(Error.NO_ERROR);
// }
// /**
// * @notice Sender supplies assets into the market and receives cTokens in exchange
// * @dev Accrues interest whether or not the operation succeeds, unless reverted
// * @param mintAmount The amount of the underlying asset to supply
// * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
// */
// function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
// uint error = accrueInterest();
// if (error != uint(Error.NO_ERROR)) {
// // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
// return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
// }
// // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
// return mintFresh(msg.sender, mintAmount);
// }
// struct MintLocalVars {
// Error err;
// MathError mathErr;
// uint exchangeRateMantissa;
// uint mintTokens;
// uint totalSupplyNew;
// uint accountTokensNew;
// uint actualMintAmount;
// }
// /**
// * @notice User supplies assets into the market and receives cTokens in exchange
// * @dev Assumes interest has already been accrued up to the current block
// * @param minter The address of the account which is supplying the assets
// * @param mintAmount The amount of the underlying asset to supply
// * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
// */
// function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
// /* Fail if mint not allowed */
// uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
// if (allowed != 0) {
// return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
// }
// /* Verify market's block number equals current block number */
// if (accrualBlockNumber != getBlockNumber()) {
// return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
// }
// MintLocalVars memory vars;
// (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
// if (vars.mathErr != MathError.NO_ERROR) {
// return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
// }
// /////////////////////////
// // EFFECTS & INTERACTIONS
// // (No safe failures beyond this point)
// /*
// * We call `doTransferIn` for the minter and the mintAmount.
// * Note: The cToken must handle variations between ERC-20 and ETH underlying.
// * `doTransferIn` reverts if anything goes wrong, since we can't be sure if
// * side-effects occurred. The function returns the amount actually transferred,
// * in case of a fee. On success, the cToken holds an additional `actualMintAmount`
// * of cash.
// */
// vars.actualMintAmount = doTransferIn(minter, mintAmount);
// /*
// * We get the current exchange rate and calculate the number of cTokens to be minted:
// * mintTokens = actualMintAmount / exchangeRate
// */
// (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
// require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
// /*
// * We calculate the new total supply of cTokens and minter token balance, checking for overflow:
// * totalSupplyNew = totalSupply + mintTokens
// * accountTokensNew = accountTokens[minter] + mintTokens
// */
// (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
// require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
// (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
// require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
// /* We write previously calculated values into storage */
// totalSupply = vars.totalSupplyNew;
// accountTokens[minter] = vars.accountTokensNew;
// /* We emit a Mint event, and a Transfer event */
// emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
// emit Transfer(address(this), minter, vars.mintTokens);
// /* We call the defense hook */
// comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
// return (uint(Error.NO_ERROR), vars.actualMintAmount);
// }
// /**
// * @notice Sender redeems cTokens in exchange for the underlying asset
// * @dev Accrues interest whether or not the operation succeeds, unless reverted
// * @param redeemTokens The number of cTokens to redeem into underlying
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
// uint error = accrueInterest();
// if (error != uint(Error.NO_ERROR)) {
// // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
// return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
// }
// // redeemFresh emits redeem-specific logs on errors, so we don't need to
// return redeemFresh(msg.sender, redeemTokens, 0);
// }
// /**
// * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
// * @dev Accrues interest whether or not the operation succeeds, unless reverted
// * @param redeemAmount The amount of underlying to receive from redeeming cTokens
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
// uint error = accrueInterest();
// if (error != uint(Error.NO_ERROR)) {
// // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
// return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
// }
// // redeemFresh emits redeem-specific logs on errors, so we don't need to
// return redeemFresh(msg.sender, 0, redeemAmount);
// }
// struct RedeemLocalVars {
// Error err;
// MathError mathErr;
// uint exchangeRateMantissa;
// uint redeemTokens;
// uint redeemAmount;
// uint totalSupplyNew;
// uint accountTokensNew;
// }
// /**
// * @notice User redeems cTokens in exchange for the underlying asset
// * @dev Assumes interest has already been accrued up to the current block
// * @param redeemer The address of the account which is redeeming the tokens
// * @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
// * @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
// require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
// RedeemLocalVars memory vars;
// /* exchangeRate = invoke Exchange Rate Stored() */
// (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
// if (vars.mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
// }
// /* If redeemTokensIn > 0: */
// if (redeemTokensIn > 0) {
// /*
// * We calculate the exchange rate and the amount of underlying to be redeemed:
// * redeemTokens = redeemTokensIn
// * redeemAmount = redeemTokensIn x exchangeRateCurrent
// */
// vars.redeemTokens = redeemTokensIn;
// (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
// if (vars.mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
// }
// } else {
// /*
// * We get the current exchange rate and calculate the amount to be redeemed:
// * redeemTokens = redeemAmountIn / exchangeRate
// * redeemAmount = redeemAmountIn
// */
// (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
// if (vars.mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
// }
// vars.redeemAmount = redeemAmountIn;
// }
// /* Fail if redeem not allowed */
// uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
// if (allowed != 0) {
// return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
// }
// /* Verify market's block number equals current block number */
// if (accrualBlockNumber != getBlockNumber()) {
// return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
// }
// /*
// * We calculate the new total supply and redeemer balance, checking for underflow:
// * totalSupplyNew = totalSupply - redeemTokens
// * accountTokensNew = accountTokens[redeemer] - redeemTokens
// */
// (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
// if (vars.mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
// }
// (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
// if (vars.mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
// }
// /* Fail gracefully if protocol has insufficient cash */
// if (getCashPrior() < vars.redeemAmount) {
// return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
// }
// /////////////////////////
// // EFFECTS & INTERACTIONS
// // (No safe failures beyond this point)
// /*
// * We invoke doTransferOut for the redeemer and the redeemAmount.
// * Note: The cToken must handle variations between ERC-20 and ETH underlying.
// * On success, the cToken has redeemAmount less of cash.
// * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
// */
// doTransferOut(redeemer, vars.redeemAmount);
// /* We write previously calculated values into storage */
// totalSupply = vars.totalSupplyNew;
// accountTokens[redeemer] = vars.accountTokensNew;
// /* We emit a Transfer event, and a Redeem event */
// emit Transfer(redeemer, address(this), vars.redeemTokens);
// emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
// /* We call the defense hook */
// comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
// return uint(Error.NO_ERROR);
// }
// /**
// * @notice Sender borrows assets from the protocol to their own address
// * @param borrowAmount The amount of the underlying asset to borrow
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
// uint error = accrueInterest();
// if (error != uint(Error.NO_ERROR)) {
// // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
// return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
// }
// // borrowFresh emits borrow-specific logs on errors, so we don't need to
// return borrowFresh(msg.sender, borrowAmount);
// }
// struct BorrowLocalVars {
// MathError mathErr;
// uint accountBorrows;
// uint accountBorrowsNew;
// uint totalBorrowsNew;
// }
// /**
// * @notice Users borrow assets from the protocol to their own address
// * @param borrowAmount The amount of the underlying asset to borrow
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
// /* Fail if borrow not allowed */
// uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
// if (allowed != 0) {
// return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
// }
// /* Verify market's block number equals current block number */
// if (accrualBlockNumber != getBlockNumber()) {
// return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
// }
// /* Fail gracefully if protocol has insufficient underlying cash */
// if (getCashPrior() < borrowAmount) {
// return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
// }
// BorrowLocalVars memory vars;
// /*
// * We calculate the new borrower and total borrow balances, failing on overflow:
// * accountBorrowsNew = accountBorrows + borrowAmount
// * totalBorrowsNew = totalBorrows + borrowAmount
// */
// (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
// if (vars.mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
// }
// (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
// if (vars.mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
// }
// (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
// if (vars.mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
// }
// /////////////////////////
// // EFFECTS & INTERACTIONS
// // (No safe failures beyond this point)
// /*
// * We invoke doTransferOut for the borrower and the borrowAmount.
// * Note: The cToken must handle variations between ERC-20 and ETH underlying.
// * On success, the cToken borrowAmount less of cash.
// * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
// */
// doTransferOut(borrower, borrowAmount);
// /* We write the previously calculated values into storage */
// accountBorrows[borrower].principal = vars.accountBorrowsNew;
// accountBorrows[borrower].interestIndex = borrowIndex;
// totalBorrows = vars.totalBorrowsNew;
// /* We emit a Borrow event */
// emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
// /* We call the defense hook */
// comptroller.borrowVerify(address(this), borrower, borrowAmount);
// return uint(Error.NO_ERROR);
// }
// /**
// * @notice Sender repays their own borrow
// * @param repayAmount The amount to repay
// * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
// */
// function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
// uint error = accrueInterest();
// if (error != uint(Error.NO_ERROR)) {
// // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
// return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
// }
// // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
// return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
// }
// /**
// * @notice Sender repays a borrow belonging to borrower
// * @param borrower the account with the debt being payed off
// * @param repayAmount The amount to repay
// * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
// */
// function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
// uint error = accrueInterest();
// if (error != uint(Error.NO_ERROR)) {
// // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
// return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
// }
// // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
// return repayBorrowFresh(msg.sender, borrower, repayAmount);
// }
// struct RepayBorrowLocalVars {
// Error err;
// MathError mathErr;
// uint repayAmount;
// uint borrowerIndex;
// uint accountBorrows;
// uint accountBorrowsNew;
// uint totalBorrowsNew;
// uint actualRepayAmount;
// }
// /**
// * @notice Borrows are repaid by another user (possibly the borrower).
// * @param payer the account paying off the borrow
// * @param borrower the account with the debt being payed off
// * @param repayAmount the amount of undelrying tokens being returned
// * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
// */
// function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
// /* Fail if repayBorrow not allowed */
// uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
// if (allowed != 0) {
// return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
// }
// /* Verify market's block number equals current block number */
// if (accrualBlockNumber != getBlockNumber()) {
// return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
// }
// RepayBorrowLocalVars memory vars;
// /* We remember the original borrowerIndex for verification purposes */
// vars.borrowerIndex = accountBorrows[borrower].interestIndex;
// /* We fetch the amount the borrower owes, with accumulated interest */
// (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
// if (vars.mathErr != MathError.NO_ERROR) {
// return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
// }
// /* If repayAmount == -1, repayAmount = accountBorrows */
// if (repayAmount == uint(-1)) {
// vars.repayAmount = vars.accountBorrows;
// } else {
// vars.repayAmount = repayAmount;
// }
// /////////////////////////
// // EFFECTS & INTERACTIONS
// // (No safe failures beyond this point)
// /*
// * We call doTransferIn for the payer and the repayAmount
// * Note: The cToken must handle variations between ERC-20 and ETH underlying.
// * On success, the cToken holds an additional repayAmount of cash.
// * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
// * it returns the amount actually transferred, in case of a fee.
// */
// vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
// /*
// * We calculate the new borrower and total borrow balances, failing on underflow:
// * accountBorrowsNew = accountBorrows - actualRepayAmount
// * totalBorrowsNew = totalBorrows - actualRepayAmount
// */
// (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
// require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
// (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
// require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
// /* We write the previously calculated values into storage */
// accountBorrows[borrower].principal = vars.accountBorrowsNew;
// accountBorrows[borrower].interestIndex = borrowIndex;
// totalBorrows = vars.totalBorrowsNew;
// /* We emit a RepayBorrow event */
// emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
// /* We call the defense hook */
// comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
// return (uint(Error.NO_ERROR), vars.actualRepayAmount);
// }
// /**
// * @notice The sender liquidates the borrowers collateral.
// * The collateral seized is transferred to the liquidator.
// * @param borrower The borrower of this cToken to be liquidated
// * @param cTokenCollateral The market in which to seize collateral from the borrower
// * @param repayAmount The amount of the underlying borrowed asset to repay
// * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
// */
// function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) {
// uint error = accrueInterest();
// if (error != uint(Error.NO_ERROR)) {
// // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
// return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
// }
// error = cTokenCollateral.accrueInterest();
// if (error != uint(Error.NO_ERROR)) {
// // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
// return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
// }
// // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
// return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral);
// }
// /**
// * @notice The liquidator liquidates the borrowers collateral.
// * The collateral seized is transferred to the liquidator.
// * @param borrower The borrower of this cToken to be liquidated
// * @param liquidator The address repaying the borrow and seizing collateral
// * @param cTokenCollateral The market in which to seize collateral from the borrower
// * @param repayAmount The amount of the underlying borrowed asset to repay
// * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
// */
// function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) {
// /* Fail if liquidate not allowed */
// uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
// if (allowed != 0) {
// return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
// }
// /* Verify market's block number equals current block number */
// if (accrualBlockNumber != getBlockNumber()) {
// return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
// }
// /* Verify cTokenCollateral market's block number equals current block number */
// if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
// return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
// }
// /* Fail if borrower = liquidator */
// if (borrower == liquidator) {
// return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
// }
// /* Fail if repayAmount = 0 */
// if (repayAmount == 0) {
// return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
// }
// /* Fail if repayAmount = -1 */
// if (repayAmount == uint(-1)) {
// return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
// }
// /* Fail if repayBorrow fails */
// (uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
// if (repayBorrowError != uint(Error.NO_ERROR)) {
// return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
// }
// /////////////////////////
// // EFFECTS & INTERACTIONS
// // (No safe failures beyond this point)
// /* We calculate the number of collateral tokens that will be seized */
// (uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount);
// require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
// /* Revert if borrower collateral token balance < seizeTokens */
// require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
// uint seizeError;
// if (address(cTokenCollateral) == address(this)) {
// seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
// } else {
// seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
// }
// /* Revert if seize tokens fails (since we cannot be sure of side effects) */
// require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
// /* We emit a LiquidateBorrow event */
// emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
// /* We call the defense hook */
// comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
// return (uint(Error.NO_ERROR), actualRepayAmount);
// }
// /**
// * @notice Transfers collateral tokens (this market) to the liquidator.
// * @dev Will fail unless called by another cToken during the process of liquidation.
// * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
// * @param liquidator The account receiving seized collateral
// * @param borrower The account having collateral seized
// * @param seizeTokens The number of cTokens to seize
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
// return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
// }
// /**
// * @notice Transfers collateral tokens (this market) to the liquidator.
// * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken.
// * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.
// * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken)
// * @param liquidator The account receiving seized collateral
// * @param borrower The account having collateral seized
// * @param seizeTokens The number of cTokens to seize
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
// /* Fail if seize not allowed */
// uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
// if (allowed != 0) {
// return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
// }
// /* Fail if borrower = liquidator */
// if (borrower == liquidator) {
// return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
// }
// MathError mathErr;
// uint borrowerTokensNew;
// uint liquidatorTokensNew;
// /*
// * We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
// * borrowerTokensNew = accountTokens[borrower] - seizeTokens
// * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
// */
// (mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
// if (mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
// }
// (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
// if (mathErr != MathError.NO_ERROR) {
// return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
// }
// /////////////////////////
// // EFFECTS & INTERACTIONS
// // (No safe failures beyond this point)
// /* We write the previously calculated values into storage */
// accountTokens[borrower] = borrowerTokensNew;
// accountTokens[liquidator] = liquidatorTokensNew;
// /* Emit a Transfer event */
// emit Transfer(borrower, liquidator, seizeTokens);
// /* We call the defense hook */
// comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
// return uint(Error.NO_ERROR);
// }
// /*** Admin Functions ***/
// /**
// * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
// * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
// * @param newPendingAdmin New pending admin.
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
// // Check caller = admin
// if (msg.sender != admin) {
// return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
// }
// // 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);
// return uint(Error.NO_ERROR);
// }
// /**
// * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
// * @dev Admin function for pending admin to accept role and update admin
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function _acceptAdmin() external returns (uint) {
// // Check caller is pendingAdmin and pendingAdmin โ address(0)
// if (msg.sender != pendingAdmin || msg.sender == address(0)) {
// return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
// }
// // Save current values for inclusion in log
// address oldAdmin = admin;
// address oldPendingAdmin = pendingAdmin;
// // Store admin with value pendingAdmin
// admin = pendingAdmin;
// // Clear the pending value
// pendingAdmin = address(0);
// emit NewAdmin(oldAdmin, admin);
// emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
// return uint(Error.NO_ERROR);
// }
// /**
// * @notice Sets a new comptroller for the market
// * @dev Admin function to set a new comptroller
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// // Check caller is admin
// if (msg.sender != admin) {
// return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
// }
// ComptrollerInterface oldComptroller = comptroller;
// // Ensure invoke comptroller.isComptroller() returns true
// require(newComptroller.isComptroller(), "marker method returned false");
// // Set market's comptroller to newComptroller
// comptroller = newComptroller;
// // Emit NewComptroller(oldComptroller, newComptroller)
// emit NewComptroller(oldComptroller, newComptroller);
// return uint(Error.NO_ERROR);
// }
// /**
// * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
// * @dev Admin function to accrue interest and set a new reserve factor
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
// uint error = accrueInterest();
// if (error != uint(Error.NO_ERROR)) {
// // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
// return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
// }
// // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
// return _setReserveFactorFresh(newReserveFactorMantissa);
// }
// /**
// * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
// * @dev Admin function to set a new reserve factor
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// // Check caller is admin
// if (msg.sender != admin) {
// return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
// }
// // Verify market's block number equals current block number
// if (accrualBlockNumber != getBlockNumber()) {
// return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
// }
// // Check newReserveFactor โค maxReserveFactor
// if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
// return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
// }
// uint oldReserveFactorMantissa = reserveFactorMantissa;
// reserveFactorMantissa = newReserveFactorMantissa;
// emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
// return uint(Error.NO_ERROR);
// }
// /**
// * @notice Accrues interest and reduces reserves by transferring from msg.sender
// * @param addAmount Amount of addition to reserves
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
// uint error = accrueInterest();
// if (error != uint(Error.NO_ERROR)) {
// // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
// return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
// }
// // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
// (error, ) = _addReservesFresh(addAmount);
// return error;
// }
// /**
// * @notice Add reserves by transferring from caller
// * @dev Requires fresh interest accrual
// * @param addAmount Amount of addition to reserves
// * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
// */
// function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// // totalReserves + actualAddAmount
// uint totalReservesNew;
// uint actualAddAmount;
// // We fail gracefully unless market's block number equals current block number
// if (accrualBlockNumber != getBlockNumber()) {
// return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
// }
// /////////////////////////
// // EFFECTS & INTERACTIONS
// // (No safe failures beyond this point)
// /*
// * We call doTransferIn for the caller and the addAmount
// * Note: The cToken must handle variations between ERC-20 and ETH underlying.
// * On success, the cToken holds an additional addAmount of cash.
// * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
// * it returns the amount actually transferred, in case of a fee.
// */
// actualAddAmount = doTransferIn(msg.sender, addAmount);
// totalReservesNew = totalReserves + actualAddAmount;
// /* Revert on overflow */
// require(totalReservesNew >= totalReserves, "add reserves unexpected overflow");
// // Store reserves[n+1] = reserves[n] + actualAddAmount
// totalReserves = totalReservesNew;
// /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
// emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
// /* Return (NO_ERROR, actualAddAmount) */
// return (uint(Error.NO_ERROR), actualAddAmount);
// }
// /**
// * @notice Accrues interest and reduces reserves by transferring to admin
// * @param reduceAmount Amount of reduction to reserves
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) {
// uint error = accrueInterest();
// if (error != uint(Error.NO_ERROR)) {
// // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
// return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
// }
// // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
// return _reduceReservesFresh(reduceAmount);
// }
// /**
// * @notice Reduces reserves by transferring to admin
// * @dev Requires fresh interest accrual
// * @param reduceAmount Amount of reduction to reserves
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// // totalReserves - reduceAmount
// uint totalReservesNew;
// // Check caller is admin
// if (msg.sender != admin) {
// return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
// }
// // We fail gracefully unless market's block number equals current block number
// if (accrualBlockNumber != getBlockNumber()) {
// return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
// }
// // Fail gracefully if protocol has insufficient underlying cash
// if (getCashPrior() < reduceAmount) {
// return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
// }
// // Check reduceAmount โค reserves[n] (totalReserves)
// if (reduceAmount > totalReserves) {
// return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
// }
// /////////////////////////
// // EFFECTS & INTERACTIONS
// // (No safe failures beyond this point)
// totalReservesNew = totalReserves - reduceAmount;
// // We checked reduceAmount <= totalReserves above, so this should never revert.
// require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow");
// // Store reserves[n+1] = reserves[n] - reduceAmount
// totalReserves = totalReservesNew;
// // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
// doTransferOut(admin, reduceAmount);
// emit ReservesReduced(admin, reduceAmount, totalReservesNew);
// return uint(Error.NO_ERROR);
// }
// /**
// * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
// * @dev Admin function to accrue interest and update the interest rate model
// * @param newInterestRateModel the new interest rate model to use
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
// uint error = accrueInterest();
// if (error != uint(Error.NO_ERROR)) {
// // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
// return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
// }
// // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
// return _setInterestRateModelFresh(newInterestRateModel);
// }
// /**
// * @notice updates the interest rate model (*requires fresh interest accrual)
// * @dev Admin function to update the interest rate model
// * @param newInterestRateModel the new interest rate model to use
// * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
// */
// function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// // Used to store old model for use in the event that is emitted on success
// InterestRateModel oldInterestRateModel;
// // Check caller is admin
// if (msg.sender != admin) {
// return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
// }
// // We fail gracefully unless market's block number equals current block number
// if (accrualBlockNumber != getBlockNumber()) {
// return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
// }
// // Track the market's current interest rate model
// oldInterestRateModel = interestRateModel;
// // Ensure invoke newInterestRateModel.isInterestRateModel() returns true
// require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// // Set the interest rate model to newInterestRateModel
// interestRateModel = newInterestRateModel;
// // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
// emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
// return uint(Error.NO_ERROR);
// }
// /*** Safe Token ***/
// /**
// * @notice Gets balance of this contract in terms of the underlying
// * @dev This excludes the value of the current message, if any
// * @return The quantity of underlying owned by this contract
// */
// function getCashPrior() internal view returns (uint);
// /**
// * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
// * This may revert due to insufficient balance or insufficient allowance.
// */
// function doTransferIn(address from, uint amount) internal returns (uint);
// /**
// * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
// * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
// * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
// */
// function doTransferOut(address payable to, uint amount) internal;
// /*** Reentrancy Guard ***/
// /**
// * @dev Prevents a contract from calling itself, directly or indirectly.
// */
// modifier nonReentrant() {
// require(_notEntered, "re-entered");
// _notEntered = false;
// _;
// _notEntered = true; // get a gas-refund post-Istanbul
// }
// }
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import '../../ERC20/IERC20.sol';
// FPT-FRAX: Original at https://etherscan.io/address/0x9d7beb4265817a4923fad9ca9ef8af138499615d
// Some functions were omitted for brevity. See the contract for details
interface IFNX_CFNX is IERC20 {
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import '../../ERC20/IERC20.sol';
// FPT-FRAX: Original at https://etherscan.io/address/0x39ad661bA8a7C9D3A7E4808fb9f9D5223E22F763
// FPT-B (FNX): Original at https://etherscan.io/address/0x7E605Fb638983A448096D82fFD2958ba012F30Cd
// Some functions were omitted for brevity. See the contract for details
interface IFNX_FPT_FRAX is IERC20 {
/**
* @dev Retrieve user's start time for burning.
* user user's account.
*/
function getUserBurnTimeLimite(address /*user*/) external view returns (uint256);
/**
* @dev Retrieve total locked worth.
*/
function getTotalLockedWorth() external view returns (uint256);
/**
* @dev Retrieve user's locked balance.
* account user's account.
*/
function lockedBalanceOf(address /*account*/) external view returns (uint256);
/**
* @dev Retrieve user's locked net worth.
* account user's account.
*/
function lockedWorthOf(address /*account*/) external view returns (uint256);
/**
* @dev Retrieve user's locked balance and locked net worth.
* account user's account.
*/
function getLockedBalance(address /*account*/) external view returns (uint256,uint256);
/**
* @dev Interface to manager FNX mine pool contract, add miner balance when user has bought some options.
* account user's account.
* amount user's pay for buying options, priced in USD.
*/
function addMinerBalance(address /*account*/,uint256 /*amount*/) external;
/**
* @dev Move user's FPT to locked balance, when user redeem collateral.
* account user's account.
* amount amount of locked FPT.
* lockedWorth net worth of locked FPT.
*/
function addlockBalance(address /*account*/, uint256 /*amount*/,uint256 /*lockedWorth*/) external;
/**
* @dev burn user's FPT when user redeem FPTCoin.
* account user's account.
* amount amount of FPT.
*/
function burn(address /*account*/, uint256 /*amount*/) external;
/**
* @dev mint user's FPT when user add collateral.
* account user's account.
* amount amount of FPT.
*/
function mint(address /*account*/, uint256 /*amount*/) external;
/**
* @dev An interface of redeem locked FPT, when user redeem collateral, only manager contract can invoke.
* account user's account.
* tokenAmount amount of FPT.
* leftCollateral left available collateral in collateral pool, priced in USD.
*/
function redeemLockedCollateral(address /*account*/,uint256 /*tokenAmount*/,uint256 /*leftCollateral*/) external returns (uint256,uint256);
// Get the mining pool address
function getFNXMinePoolAddress() external view returns(address);
/**
* @dev FPT has burn time limit. When user's balance is moved in som coins, he will wait `timeLimited` to burn FPT.
* latestTransferIn is user's latest time when his balance is moved in.
*/
function getTimeLimitation() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import '../../ERC20/IERC20.sol';
// FPT-FRAX: Original at https://etherscan.io/address/0x39ad661bA8a7C9D3A7E4808fb9f9D5223E22F763
// FPT-B (FNX): Original at https://etherscan.io/address/0x7E605Fb638983A448096D82fFD2958ba012F30Cd
// Some functions were omitted for brevity. See the contract for details
interface IFNX_FPT_B is IERC20 {
/**
* @dev Retrieve user's start time for burning.
* user user's account.
*/
function getUserBurnTimeLimite(address /*user*/) external view returns (uint256);
/**
* @dev Retrieve total locked worth.
*/
function getTotalLockedWorth() external view returns (uint256);
/**
* @dev Retrieve user's locked balance.
* account user's account.
*/
function lockedBalanceOf(address /*account*/) external view returns (uint256);
/**
* @dev Retrieve user's locked net worth.
* account user's account.
*/
function lockedWorthOf(address /*account*/) external view returns (uint256);
/**
* @dev Retrieve user's locked balance and locked net worth.
* account user's account.
*/
function getLockedBalance(address /*account*/) external view returns (uint256,uint256);
/**
* @dev Interface to manager FNX mine pool contract, add miner balance when user has bought some options.
* account user's account.
* amount user's pay for buying options, priced in USD.
*/
function addMinerBalance(address /*account*/,uint256 /*amount*/) external;
/**
* @dev Move user's FPT to locked balance, when user redeem collateral.
* account user's account.
* amount amount of locked FPT.
* lockedWorth net worth of locked FPT.
*/
function addlockBalance(address /*account*/, uint256 /*amount*/,uint256 /*lockedWorth*/) external;
/**
* @dev burn user's FPT when user redeem FPTCoin.
* account user's account.
* amount amount of FPT.
*/
function burn(address /*account*/, uint256 /*amount*/) external;
/**
* @dev mint user's FPT when user add collateral.
* account user's account.
* amount amount of FPT.
*/
function mint(address /*account*/, uint256 /*amount*/) external;
/**
* @dev An interface of redeem locked FPT, when user redeem collateral, only manager contract can invoke.
* account user's account.
* tokenAmount amount of FPT.
* leftCollateral left available collateral in collateral pool, priced in USD.
*/
function redeemLockedCollateral(address /*account*/,uint256 /*tokenAmount*/,uint256 /*leftCollateral*/) external returns (uint256,uint256);
// Get the mining pool address
function getFNXMinePoolAddress() external view returns(address);
/**
* @dev FPT has burn time limit. When user's balance is moved in som coins, he will wait `timeLimited` to burn FPT.
* latestTransferIn is user's latest time when his balance is moved in.
*/
function getTimeLimitation() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import '../../ERC20/IERC20.sol';
// Original at https://etherscan.io/address/0x23e54F9bBe26eD55F93F19541bC30AAc2D5569b2
// Some functions were omitted for brevity. See the contract for details
interface IFNX_IntegratedStake {
function stake(address[] memory fpta_tokens,uint256[] memory fpta_amounts,
address[] memory fptb_tokens, uint256[] memory fptb_amounts,uint256 lockedPeriod) external;
}
// contract integratedStake is Ownable{
// using SafeERC20 for IERC20;
// address public _FPTA;
// address public _FPTB;
// address public _FPTAColPool;//the option manager address
// address public _FPTBColPool;//the option manager address
// address public _minePool; //the fixed minePool address
// mapping (address=>bool) approveMapA;
// mapping (address=>bool) approveMapB;
// uint256 constant internal MAX_UINT = (2**256 - 1);
// /**
// * @dev constructor.
// */
// constructor(address FPTA,address FPTB,address FPTAColPool,address FPTBColPool,address minePool)public{
// setAddress(FPTA,FPTB,FPTAColPool,FPTBColPool,minePool);
// }
// function setAddress(address FPTA,address FPTB,address FPTAColPool,address FPTBColPool,address minePool) onlyOwner public{
// _FPTA = FPTA;
// _FPTB = FPTB;
// _FPTAColPool = FPTAColPool;
// _FPTBColPool = FPTBColPool;
// _minePool = minePool;
// if (IERC20(_FPTA).allowance(msg.sender, _minePool) == 0){
// IERC20(_FPTA).safeApprove(_minePool,MAX_UINT);
// }
// if (IERC20(_FPTB).allowance(msg.sender, _minePool) == 0){
// IERC20(_FPTB).safeApprove(_minePool,MAX_UINT);
// }
// }
// function stake(address[] memory fpta_tokens,uint256[] memory fpta_amounts,
// address[] memory fptb_tokens,uint256[] memory fptb_amounts,uint256 lockedPeriod) public{
// require(fpta_tokens.length==fpta_amounts.length && fptb_tokens.length==fptb_amounts.length,"the input array length is not equal");
// uint256 i = 0;
// for(i = 0;i<fpta_tokens.length;i++) {
// if (!approveMapA[fpta_tokens[i]]){
// IERC20(fpta_tokens[i]).safeApprove(_FPTAColPool,MAX_UINT);
// approveMapA[fpta_tokens[i]] = true;
// }
// uint256 amount = getPayableAmount(fpta_tokens[i],fpta_amounts[i]);
// IOptionMgrPoxy(_FPTAColPool).addCollateral(fpta_tokens[i],amount);
// IERC20(_FPTA).safeTransfer(msg.sender,0);
// }
// for(i = 0;i<fptb_tokens.length;i++) {
// if (!approveMapB[fptb_tokens[i]]){
// IERC20(fptb_tokens[i]).safeApprove(_FPTBColPool,MAX_UINT);
// approveMapB[fptb_tokens[i]] = true;
// }
// uint256 amount = getPayableAmount(fptb_tokens[i],fptb_amounts[i]);
// IOptionMgrPoxy(_FPTBColPool).addCollateral(fptb_tokens[i],amount);
// IERC20(_FPTB).safeTransfer(msg.sender,0);
// }
// IMinePool(_minePool).lockAirDrop(msg.sender,lockedPeriod);
// }
// /**
// * @dev Auxiliary function. getting user's payment
// * @param settlement user's payment coin.
// * @param settlementAmount user's payment amount.
// */
// function getPayableAmount(address settlement,uint256 settlementAmount) internal returns (uint256) {
// if (settlement == address(0)){
// settlementAmount = msg.value;
// }else if (settlementAmount > 0){
// IERC20 oToken = IERC20(settlement);
// uint256 preBalance = oToken.balanceOf(address(this));
// oToken.safeTransferFrom(msg.sender, address(this), settlementAmount);
// //oToken.transferFrom(msg.sender, address(this), settlementAmount);
// uint256 afterBalance = oToken.balanceOf(address(this));
// require(afterBalance-preBalance==settlementAmount,"settlement token transfer error!");
// }
// return settlementAmount;
// }
// }
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import '../../ERC20/IERC20.sol';
// Original at https://etherscan.io/address/0x4e6005396F80a737cE80d50B2162C0a7296c9620
// Some functions were omitted for brevity. See the contract for details
interface IFNX_MinePool {
/**
* @dev getting function. Retrieve FPT-A coin's address
*/
function getFPTAAddress() external view returns (address);
/**
* @dev getting function. Retrieve FPT-B coin's address
*/
function getFPTBAddress() external view returns (address);
/**
* @dev getting function. Retrieve mine pool's start time.
*/
function getStartTime() external view returns (uint256);
/**
* @dev getting current mine period ID.
*/
function getCurrentPeriodID() external view returns (uint256);
/**
* @dev getting user's staking FPT-A balance.
* account user's account
*/
function getUserFPTABalance(address /*account*/) external view returns (uint256);
/**
* @dev getting user's staking FPT-B balance.
* account user's account
*/
function getUserFPTBBalance(address /*account*/) external view returns (uint256);
/**
* @dev getting user's maximium locked period ID.
* account user's account
*/
function getUserMaxPeriodId(address /*account*/) external view returns (uint256);
/**
* @dev getting user's locked expired time. After this time user can unstake FPTB coins.
* account user's account
*/
function getUserExpired(address /*account*/) external view returns (uint256);
function getCurrentTotalAPY(address /*mineCoin*/) external view returns (uint256);
/**
* @dev Calculate user's current APY.
* account user's account.
* mineCoin mine coin address
*/
function getUserCurrentAPY(address /*account*/,address /*mineCoin*/) external view returns (uint256);
function getAverageLockedTime() external view returns (uint256);
/**
* @dev foundation redeem out mine coins.
* mineCoin mineCoin address
* amount redeem amount.
*/
function redeemOut(address /*mineCoin*/,uint256 /*amount*/) external;
/**
* @dev retrieve total distributed mine coins.
* mineCoin mineCoin address
*/
function getTotalMined(address /*mineCoin*/) external view returns(uint256);
/**
* @dev retrieve minecoin distributed informations.
* mineCoin mineCoin address
* @return distributed amount and distributed time interval.
*/
function getMineInfo(address /*mineCoin*/) external view returns(uint256,uint256);
/**
* @dev retrieve user's mine balance.
* account user's account
* mineCoin mineCoin address
*/
function getMinerBalance(address /*account*/,address /*mineCoin*/) external view returns(uint256);
/**
* @dev Set mineCoin mine info, only foundation owner can invoked.
* mineCoin mineCoin address
* _mineAmount mineCoin distributed amount
* _mineInterval mineCoin distributied time interval
*/
function setMineCoinInfo(address /*mineCoin*/,uint256 /*_mineAmount*/,uint256 /*_mineInterval*/) external ;
/**
* @dev user redeem mine rewards.
* mineCoin mine coin address
* amount redeem amount.
*/
function redeemMinerCoin(address /*mineCoin*/,uint256 /*amount*/) external;
/**
* @dev getting whole pool's mine production weight ratio.
* Real mine production equals base mine production multiply weight ratio.
*/
function getMineWeightRatio() external view returns (uint256);
/**
* @dev getting whole pool's mine shared distribution. All these distributions will share base mine production.
*/
function getTotalDistribution() external view returns (uint256);
/**
* @dev convert timestamp to period ID.
* _time timestamp.
*/
function getPeriodIndex(uint256 /*_time*/) external view returns (uint256);
/**
* @dev convert period ID to period's finish timestamp.
* periodID period ID.
*/
function getPeriodFinishTime(uint256 /*periodID*/) external view returns (uint256);
/**
* @dev Stake FPT-A coin and get distribution for mining.
* amount FPT-A amount that transfer into mine pool.
*/
function stakeFPTA(uint256 /*amount*/) external ;
/**
* @dev Air drop to user some FPT-B coin and lock one period and get distribution for mining.
* user air drop's recieptor.
* ftp_b_amount FPT-B amount that transfer into mine pool.
*/
function lockAirDrop(address /*user*/,uint256 /*ftp_b_amount*/) external;
/**
* @dev Stake FPT-B coin and lock locedPreiod and get distribution for mining.
* amount FPT-B amount that transfer into mine pool.
* lockedPeriod locked preiod number.
*/
function stakeFPTB(uint256 /*amount*/,uint256 /*lockedPeriod*/) external;
/**
* @dev withdraw FPT-A coin.
* amount FPT-A amount that withdraw from mine pool.
*/
function unstakeFPTA(uint256 /*amount*/) external ;
/**
* @dev withdraw FPT-B coin.
* amount FPT-B amount that withdraw from mine pool.
*/
function unstakeFPTB(uint256 /*amount*/) external;
/**
* @dev Add FPT-B locked period.
* lockedPeriod FPT-B locked preiod number.
*/
function changeFPTBLockedPeriod(uint256 /*lockedPeriod*/) external;
/**
* @dev retrieve total distributed premium coins.
*/
function getTotalPremium() external view returns(uint256);
/**
* @dev user redeem his options premium rewards.
*/
function redeemPremium() external;
/**
* @dev user redeem his options premium rewards.
* amount redeem amount.
*/
function redeemPremiumCoin(address /*premiumCoin*/,uint256 /*amount*/) external;
/**
* @dev get user's premium balance.
* account user's account
*/
function getUserLatestPremium(address /*account*/,address /*premiumCoin*/) external view returns(uint256);
/**
* @dev Distribute premium from foundation.
* periodID period ID
* amount premium amount.
*/
function distributePremium(address /*premiumCoin*/,uint256 /*periodID*/,uint256 /*amount*/) external ;
}
// /**
// *Submitted for verification at Etherscan.io on 2021-01-26
// */
// // File: contracts\Proxy\newBaseProxy.sol
// pragma solidity =0.5.16;
// /**
// * @title newBaseProxy Contract
// */
// contract newBaseProxy {
// bytes32 private constant implementPositon = keccak256("org.Finnexus.implementation.storage");
// bytes32 private constant proxyOwnerPosition = keccak256("org.Finnexus.Owner.storage");
// constructor(address implementation_) public {
// // Creator of the contract is admin during initialization
// _setProxyOwner(msg.sender);
// _setImplementation(implementation_);
// (bool success,) = implementation_.delegatecall(abi.encodeWithSignature("initialize()"));
// require(success);
// }
// /**
// * @dev Allows the current owner to transfer ownership
// * @param _newOwner The address to transfer ownership to
// */
// function transferProxyOwnership(address _newOwner) public onlyProxyOwner
// {
// require(_newOwner != address(0));
// _setProxyOwner(_newOwner);
// }
// function _setProxyOwner(address _newOwner) internal
// {
// bytes32 position = proxyOwnerPosition;
// assembly {
// sstore(position, _newOwner)
// }
// }
// function proxyOwner() public view returns (address owner) {
// bytes32 position = proxyOwnerPosition;
// assembly {
// owner := sload(position)
// }
// }
// /**
// * @dev Tells the address of the current implementation
// * @return address of the current implementation
// */
// function getImplementation() public view returns (address impl) {
// bytes32 position = implementPositon;
// assembly {
// impl := sload(position)
// }
// }
// function _setImplementation(address _newImplementation) internal
// {
// bytes32 position = implementPositon;
// assembly {
// sstore(position, _newImplementation)
// }
// }
// function setImplementation(address _newImplementation)public onlyProxyOwner{
// address currentImplementation = getImplementation();
// require(currentImplementation != _newImplementation);
// _setImplementation(_newImplementation);
// (bool success,) = _newImplementation.delegatecall(abi.encodeWithSignature("update()"));
// require(success);
// }
// /**
// * @notice Delegates execution to the implementation contract
// * @dev It returns to the external caller whatever the implementation returns or forwards reverts
// * @param data The raw data to delegatecall
// * @return The returned bytes from the delegatecall
// */
// function delegateToImplementation(bytes memory data) public returns (bytes memory) {
// (bool success, bytes memory returnData) = getImplementation().delegatecall(data);
// assembly {
// if eq(success, 0) {
// revert(add(returnData, 0x20), returndatasize)
// }
// }
// return returnData;
// }
// /**
// * @notice Delegates execution to an implementation contract
// * @dev It returns to the external caller whatever the implementation returns or forwards reverts
// * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
// * @param data The raw data to delegatecall
// * @return The returned bytes from the delegatecall
// */
// function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
// (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
// assembly {
// if eq(success, 0) {
// revert(add(returnData, 0x20), returndatasize)
// }
// }
// return abi.decode(returnData, (bytes));
// }
// function delegateToViewAndReturn() internal view returns (bytes memory) {
// (bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
// assembly {
// let free_mem_ptr := mload(0x40)
// returndatacopy(free_mem_ptr, 0, returndatasize)
// switch success
// case 0 { revert(free_mem_ptr, returndatasize) }
// default { return(add(free_mem_ptr, 0x40), sub(returndatasize, 0x40)) }
// }
// }
// function delegateAndReturn() internal returns (bytes memory) {
// (bool success, ) = getImplementation().delegatecall(msg.data);
// assembly {
// let free_mem_ptr := mload(0x40)
// returndatacopy(free_mem_ptr, 0, returndatasize)
// switch success
// case 0 { revert(free_mem_ptr, returndatasize) }
// default { return(free_mem_ptr, returndatasize) }
// }
// }
// /**
// * @dev Throws if called by any account other than the owner.
// */
// modifier onlyProxyOwner() {
// require (msg.sender == proxyOwner());
// _;
// }
// }
// // File: contracts\fixedMinePool\fixedMinePoolProxy.sol
// pragma solidity =0.5.16;
// /**
// * @title FNX period mine pool.
// * @dev A smart-contract which distribute some mine coins when user stake FPT-A and FPT-B coins.
// *
// */
// contract fixedMinePoolProxy is newBaseProxy {
// /**
// * @dev constructor.
// * FPTA FPT-A coin's address,staking coin
// * FPTB FPT-B coin's address,staking coin
// * startTime the start time when this mine pool begin.
// */
// constructor (address implementation_,address FPTA,address FPTB,uint256 startTime) newBaseProxy(implementation_) public{
// (bool success,) = implementation_.delegatecall(abi.encodeWithSignature(
// "setAddresses(address,address,uint256)",
// FPTA,
// FPTB,
// startTime));
// require(success);
// }
// /**
// * @dev default function for foundation input miner coins.
// */
// function()external payable{
// }
// /**
// * @dev Returns the address of the current owner.
// */
// function owner() public view returns (address) {
// delegateToViewAndReturn();
// }
// /**
// * @dev Returns true if the caller is the current owner.
// */
// function isOwner() public view returns (bool) {
// delegateToViewAndReturn();
// }
// /**
// * @dev Leaves the contract without owner. It will not be possible to call
// * `onlyOwner` functions anymore. Can only be called by the current owner.
// *
// * NOTE: Renouncing ownership will leave the contract without an owner,
// * thereby removing any functionality that is only available to the owner.
// */
// function renounceOwnership() public {
// delegateAndReturn();
// }
// /**
// * @dev Transfers ownership of the contract to a new account (`newOwner`).
// * Can only be called by the current owner.
// */
// function transferOwnership(address /*newOwner*/) public {
// delegateAndReturn();
// }
// function setHalt(bool /*halt*/) public {
// delegateAndReturn();
// }
// function addWhiteList(address /*addAddress*/)public{
// delegateAndReturn();
// }
// /**
// * @dev Implementation of revoke an invalid address from the whitelist.
// * removeAddress revoked address.
// */
// function removeWhiteList(address /*removeAddress*/)public returns (bool){
// delegateAndReturn();
// }
// /**
// * @dev Implementation of getting the eligible whitelist.
// */
// function getWhiteList()public view returns (address[] memory){
// delegateToViewAndReturn();
// }
// /**
// * @dev Implementation of testing whether the input address is eligible.
// * tmpAddress input address for testing.
// */
// function isEligibleAddress(address /*tmpAddress*/) public view returns (bool){
// delegateToViewAndReturn();
// }
// function setOperator(uint256 /*index*/,address /*addAddress*/)public{
// delegateAndReturn();
// }
// function getOperator(uint256 /*index*/)public view returns (address) {
// delegateToViewAndReturn();
// }
// /**
// * @dev getting function. Retrieve FPT-A coin's address
// */
// function getFPTAAddress()public view returns (address) {
// delegateToViewAndReturn();
// }
// /**
// * @dev getting function. Retrieve FPT-B coin's address
// */
// function getFPTBAddress()public view returns (address) {
// delegateToViewAndReturn();
// }
// /**
// * @dev getting function. Retrieve mine pool's start time.
// */
// function getStartTime()public view returns (uint256) {
// delegateToViewAndReturn();
// }
// /**
// * @dev getting current mine period ID.
// */
// function getCurrentPeriodID()public view returns (uint256) {
// delegateToViewAndReturn();
// }
// /**
// * @dev getting user's staking FPT-A balance.
// * account user's account
// */
// function getUserFPTABalance(address /*account*/)public view returns (uint256) {
// delegateToViewAndReturn();
// }
// /**
// * @dev getting user's staking FPT-B balance.
// * account user's account
// */
// function getUserFPTBBalance(address /*account*/)public view returns (uint256) {
// delegateToViewAndReturn();
// }
// /**
// * @dev getting user's maximium locked period ID.
// * account user's account
// */
// function getUserMaxPeriodId(address /*account*/)public view returns (uint256) {
// delegateToViewAndReturn();
// }
// /**
// * @dev getting user's locked expired time. After this time user can unstake FPTB coins.
// * account user's account
// */
// function getUserExpired(address /*account*/)public view returns (uint256) {
// delegateToViewAndReturn();
// }
// function getCurrentTotalAPY(address /*mineCoin*/)public view returns (uint256){
// delegateToViewAndReturn();
// }
// /**
// * @dev Calculate user's current APY.
// * account user's account.
// * mineCoin mine coin address
// */
// function getUserCurrentAPY(address /*account*/,address /*mineCoin*/)public view returns (uint256){
// delegateToViewAndReturn();
// }
// function getAverageLockedTime()public view returns (uint256){
// delegateToViewAndReturn();
// }
// /**
// * @dev foundation redeem out mine coins.
// * mineCoin mineCoin address
// * amount redeem amount.
// */
// function redeemOut(address /*mineCoin*/,uint256 /*amount*/)public{
// delegateAndReturn();
// }
// /**
// * @dev retrieve total distributed mine coins.
// * mineCoin mineCoin address
// */
// function getTotalMined(address /*mineCoin*/)public view returns(uint256){
// delegateToViewAndReturn();
// }
// /**
// * @dev retrieve minecoin distributed informations.
// * mineCoin mineCoin address
// * @return distributed amount and distributed time interval.
// */
// function getMineInfo(address /*mineCoin*/)public view returns(uint256,uint256){
// delegateToViewAndReturn();
// }
// /**
// * @dev retrieve user's mine balance.
// * account user's account
// * mineCoin mineCoin address
// */
// function getMinerBalance(address /*account*/,address /*mineCoin*/)public view returns(uint256){
// delegateToViewAndReturn();
// }
// /**
// * @dev Set mineCoin mine info, only foundation owner can invoked.
// * mineCoin mineCoin address
// * _mineAmount mineCoin distributed amount
// * _mineInterval mineCoin distributied time interval
// */
// function setMineCoinInfo(address /*mineCoin*/,uint256 /*_mineAmount*/,uint256 /*_mineInterval*/)public {
// delegateAndReturn();
// }
// /**
// * @dev user redeem mine rewards.
// * mineCoin mine coin address
// * amount redeem amount.
// */
// function redeemMinerCoin(address /*mineCoin*/,uint256 /*amount*/)public{
// delegateAndReturn();
// }
// /**
// * @dev getting whole pool's mine production weight ratio.
// * Real mine production equals base mine production multiply weight ratio.
// */
// function getMineWeightRatio()public view returns (uint256) {
// delegateToViewAndReturn();
// }
// /**
// * @dev getting whole pool's mine shared distribution. All these distributions will share base mine production.
// */
// function getTotalDistribution() public view returns (uint256){
// delegateToViewAndReturn();
// }
// /**
// * @dev convert timestamp to period ID.
// * _time timestamp.
// */
// function getPeriodIndex(uint256 /*_time*/) public view returns (uint256) {
// delegateToViewAndReturn();
// }
// /**
// * @dev convert period ID to period's finish timestamp.
// * periodID period ID.
// */
// function getPeriodFinishTime(uint256 /*periodID*/)public view returns (uint256) {
// delegateToViewAndReturn();
// }
// /**
// * @dev Stake FPT-A coin and get distribution for mining.
// * amount FPT-A amount that transfer into mine pool.
// */
// function stakeFPTA(uint256 /*amount*/)public {
// delegateAndReturn();
// }
// /**
// * @dev Air drop to user some FPT-B coin and lock one period and get distribution for mining.
// * user air drop's recieptor.
// * ftp_b_amount FPT-B amount that transfer into mine pool.
// */
// function lockAirDrop(address /*user*/,uint256 /*ftp_b_amount*/) external{
// delegateAndReturn();
// }
// /**
// * @dev Stake FPT-B coin and lock locedPreiod and get distribution for mining.
// * amount FPT-B amount that transfer into mine pool.
// * lockedPeriod locked preiod number.
// */
// function stakeFPTB(uint256 /*amount*/,uint256 /*lockedPeriod*/)public{
// delegateAndReturn();
// }
// /**
// * @dev withdraw FPT-A coin.
// * amount FPT-A amount that withdraw from mine pool.
// */
// function unstakeFPTA(uint256 /*amount*/)public {
// delegateAndReturn();
// }
// /**
// * @dev withdraw FPT-B coin.
// * amount FPT-B amount that withdraw from mine pool.
// */
// function unstakeFPTB(uint256 /*amount*/)public{
// delegateAndReturn();
// }
// /**
// * @dev Add FPT-B locked period.
// * lockedPeriod FPT-B locked preiod number.
// */
// function changeFPTBLockedPeriod(uint256 /*lockedPeriod*/)public{
// delegateAndReturn();
// }
// /**
// * @dev retrieve total distributed premium coins.
// */
// function getTotalPremium()public view returns(uint256){
// delegateToViewAndReturn();
// }
// /**
// * @dev user redeem his options premium rewards.
// */
// function redeemPremium()public{
// delegateAndReturn();
// }
// /**
// * @dev user redeem his options premium rewards.
// * amount redeem amount.
// */
// function redeemPremiumCoin(address /*premiumCoin*/,uint256 /*amount*/)public{
// delegateAndReturn();
// }
// /**
// * @dev get user's premium balance.
// * account user's account
// */
// function getUserLatestPremium(address /*account*/,address /*premiumCoin*/)public view returns(uint256){
// delegateToViewAndReturn();
// }
// /**
// * @dev Distribute premium from foundation.
// * periodID period ID
// * amount premium amount.
// */
// function distributePremium(address /*premiumCoin*/,uint256 /*periodID*/,uint256 /*amount*/)public {
// delegateAndReturn();
// }
// /**
// * @dev Emitted when `account` stake `amount` FPT-A coin.
// */
// event StakeFPTA(address indexed account,uint256 amount);
// /**
// * @dev Emitted when `from` airdrop `recieptor` `amount` FPT-B coin.
// */
// event LockAirDrop(address indexed from,address indexed recieptor,uint256 amount);
// /**
// * @dev Emitted when `account` stake `amount` FPT-B coin and locked `lockedPeriod` periods.
// */
// event StakeFPTB(address indexed account,uint256 amount,uint256 lockedPeriod);
// /**
// * @dev Emitted when `account` unstake `amount` FPT-A coin.
// */
// event UnstakeFPTA(address indexed account,uint256 amount);
// /**
// * @dev Emitted when `account` unstake `amount` FPT-B coin.
// */
// event UnstakeFPTB(address indexed account,uint256 amount);
// /**
// * @dev Emitted when `account` change `lockedPeriod` locked periods for FPT-B coin.
// */
// event ChangeLockedPeriod(address indexed account,uint256 lockedPeriod);
// /**
// * @dev Emitted when owner `account` distribute `amount` premium in `periodID` period.
// */
// event DistributePremium(address indexed account,address indexed premiumCoin,uint256 indexed periodID,uint256 amount);
// /**
// * @dev Emitted when `account` redeem `amount` premium.
// */
// event RedeemPremium(address indexed account,address indexed premiumCoin,uint256 amount);
// /**
// * @dev Emitted when `account` redeem `value` mineCoins.
// */
// event RedeemMineCoin(address indexed account, address indexed mineCoin, uint256 value);
// }
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import '../../ERC20/IERC20.sol';
// Original at https://etherscan.io/address/0x955282b82440F8F69E901380BeF2b603Fba96F3b
// Some functions were omitted for brevity. See the contract for details
interface IFNX_TokenConverter {
struct lockedReward {
uint256 startTime; //this tx startTime for locking
uint256 total; //record input amount in each lock tx
// Have to comment this out to get compiling working here
// mapping (uint256 => uint256) alloc;//the allocation table
}
struct lockedIdx {
uint256 beginIdx;//the first index for user converting input claimable tx index
uint256 totalIdx;//the total number for converting tx
}
function cfnxAddress() external returns (address); //cfnx token address
function fnxAddress() external returns (address); //fnx token address
function timeSpan() external returns (uint256); //time interval span time ,default one month
function dispatchTimes() external returns (uint256); //allocation times,default 6 times
function txNum() external returns (uint256); //100 times transfer tx
function lockPeriod() external returns (uint256);
function lockedBalances(address) external returns (uint256); //locked balance for each user
function lockedAllRewards(address, uint256) external returns (lockedReward memory); //converting tx record for each user
function lockedIndexs(address) external returns (lockedIdx memory); //the converting tx index info
function getbackLeftFnx(address /*reciever*/) external;
function setParameter(address /*_cfnxAddress*/,address /*_fnxAddress*/,uint256 /*_timeSpan*/,uint256 /*_dispatchTimes*/,uint256 /*_txNum*/) external;
function lockedBalanceOf(address /*account*/) external view returns (uint256);
function inputCfnxForInstallmentPay(uint256 /*amount*/) external;
function claimFnxExpiredReward() external;
function getClaimAbleBalance(address) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import '../../ERC20/IERC20.sol';
// Original at https://etherscan.io/address/0xa2904Fd151C9d9D634dFA8ECd856E6B9517F9785
// Some functions were omitted for brevity. See the contract for details
// More info: https://github.com/FinNexus/OptionsContract/blob/master/contracts/ManagerContract.sol
// For Collateral Calculations: https://github.com/FinNexus/FinnexusOptionsV1.0/blob/master/contracts/OptionsManager/CollateralCal.sol
// Addresses: https://github.com/FinNexus/FinNexus-Documentation/blob/master/content/developers/smart-contracts.md
interface IFNX_ManagerProxy {
/**
* @dev Get the minimum collateral occupation rate.
*/
function getCollateralRate(address /*collateral*/)external view returns (uint256) ;
/**
* @dev Retrieve user's cost of collateral, priced in USD.
* user input retrieved account
*/
function getUserPayingUsd(address /*user*/)external view returns (uint256);
/**
* @dev Retrieve user's amount of the specified collateral.
* user input retrieved account
* collateral input retrieved collateral coin address
*/
function userInputCollateral(address /*user*/,address /*collateral*/)external view returns (uint256);
/**
* @dev Retrieve user's current total worth, priced in USD.
* account input retrieve account
*/
function getUserTotalWorth(address /*account*/)external view returns (uint256);
/**
* @dev Retrieve FPTCoin's net worth, priced in USD.
*/
function getTokenNetworth() external view returns (uint256);
/**
* @dev Deposit collateral in this pool from user.
* collateral The collateral coin address which is in whitelist.
* amount the amount of collateral to deposit.
*/
function addCollateral(address /*collateral*/,uint256 /*amount*/) external payable;
/**
* @dev redeem collateral from this pool, user can input the prioritized collateral,he will get this coin,
* if this coin is unsufficient, he will get others collateral which in whitelist.
* tokenAmount the amount of FPTCoin want to redeem.
* collateral The prioritized collateral coin address.
*/
function redeemCollateral(uint256 /*tokenAmount*/,address /*collateral*/) external;
/**
* @dev Retrieve user's collateral worth in all collateral coin.
* If user want to redeem all his collateral,and the vacant collateral is sufficient,
* He can redeem each collateral amount in return list.
* account the retrieve user's account;
*/
function calCollateralWorth(address /*account*/)external view returns(uint256[] memory);
/**
* @dev Retrieve the occupied collateral worth, multiplied by minimum collateral rate, priced in USD.
*/
function getOccupiedCollateral() external view returns(uint256);
/**
* @dev Retrieve the available collateral worth, the worth of collateral which can used for buy options, priced in USD.
*/
function getAvailableCollateral() external view returns(uint256);
/**
* @dev Retrieve the left collateral worth, the worth of collateral which can used for redeem collateral, priced in USD.
*/
function getLeftCollateral() external view returns(uint256);
/**
* @dev Retrieve the unlocked collateral worth, the worth of collateral which currently used for options, priced in USD.
*/
function getUnlockedCollateral() external view returns(uint256);
/**
* @dev Retrieve the total collateral worth, priced in USD.
*/
function getTotalCollateral() external view returns(uint256);
/**
* @dev Retrieve the balance of collateral, the auxiliary function for the total collateral calculation.
*/
function getRealBalance(address /*settlement*/)external view returns(int256);
function getNetWorthBalance(address /*settlement*/)external view returns(uint256);
/**
* @dev collateral occupation rate calculation
* collateral occupation rate = sum(collateral Rate * collateral balance) / sum(collateral balance)
*/
function calculateCollateralRate() external view returns (uint256);
/**
* @dev retrieve input price valid range rate, thousandths.
*/
function getPriceRateRange() external view returns(uint256,uint256) ;
function getALLCollateralinfo(address /*user*/)external view
returns(uint256[] memory,int256[] memory,uint32[] memory,uint32[] memory);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import '../../ERC20/IERC20.sol';
// Original at https://etherscan.io/address/0x43BD92bF3Bb25EBB3BdC2524CBd6156E3Fdd41F3
// Some functions were omitted for brevity. See the contract for details
interface IFNX_Oracle {
function getAssetAndUnderlyingPrice(address asset,uint256 underlying) external view returns (uint256,uint256);
function getPrices(uint256[]memory assets) external view returns (uint256[]memory);
/**
* @notice retrieves price of an asset
* @dev function to get price for an asset
* @param asset Asset for which to get the price
* @return uint mantissa of asset price (scaled by 1e8) or zero if unset or contract paused
*/
function getPrice(address asset) external view returns (uint256);
function getUnderlyingPrice(uint256 underlying) external view returns (uint256);
}
// /**
// *Submitted for verification at Etherscan.io on 2020-11-04
// */
// // File: contracts\modules\Ownable.sol
// pragma solidity >=0.6.0;
// /**
// * @dev Contract module which provides a basic access control mechanism, where
// * there is an account (an owner) that can be granted exclusive access to
// * specific functions.
// *
// * This module is used through inheritance. It will make available the modifier
// * `onlyOwner`, which can be applied to your functions to restrict their use to
// * the owner.
// */
// contract Ownable {
// address internal _owner;
// event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
// /**
// * @dev Initializes the contract setting the deployer as the initial owner.
// */
// constructor() internal {
// _owner = msg.sender;
// emit OwnershipTransferred(address(0), _owner);
// }
// /**
// * @dev Returns the address of the current owner.
// */
// function owner() public view returns (address) {
// return _owner;
// }
// /**
// * @dev Throws if called by any account other than the owner.
// */
// modifier onlyOwner() {
// require(isOwner(), "Ownable: caller is not the owner");
// _;
// }
// /**
// * @dev Returns true if the caller is the current owner.
// */
// function isOwner() public view returns (bool) {
// return msg.sender == _owner;
// }
// /**
// * @dev Leaves the contract without owner. It will not be possible to call
// * `onlyOwner` functions anymore. Can only be called by the current owner.
// *
// * NOTE: Renouncing ownership will leave the contract without an owner,
// * thereby removing any functionality that is only available to the owner.
// */
// function renounceOwnership() public onlyOwner {
// emit OwnershipTransferred(_owner, address(0));
// _owner = address(0);
// }
// /**
// * @dev Transfers ownership of the contract to a new account (`newOwner`).
// * Can only be called by the current owner.
// */
// function transferOwnership(address newOwner) public onlyOwner {
// _transferOwnership(newOwner);
// }
// /**
// * @dev Transfers ownership of the contract to a new account (`newOwner`).
// */
// function _transferOwnership(address newOwner) internal {
// require(newOwner != address(0), "Ownable: new owner is the zero address");
// emit OwnershipTransferred(_owner, newOwner);
// _owner = newOwner;
// }
// }
// // File: contracts\modules\whiteList.sol
// pragma solidity >=0.6.0;
// /**
// * @dev Implementation of a whitelist which filters a eligible uint32.
// */
// library whiteListUint32 {
// /**
// * @dev add uint32 into white list.
// * @param whiteList the storage whiteList.
// * @param temp input value
// */
// function addWhiteListUint32(uint32[] storage whiteList,uint32 temp) internal{
// if (!isEligibleUint32(whiteList,temp)){
// whiteList.push(temp);
// }
// }
// /**
// * @dev remove uint32 from whitelist.
// */
// function removeWhiteListUint32(uint32[] storage whiteList,uint32 temp)internal returns (bool) {
// uint256 len = whiteList.length;
// uint256 i=0;
// for (;i<len;i++){
// if (whiteList[i] == temp)
// break;
// }
// if (i<len){
// if (i!=len-1) {
// whiteList[i] = whiteList[len-1];
// }
// whiteList.pop();
// return true;
// }
// return false;
// }
// function isEligibleUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (bool){
// uint256 len = whiteList.length;
// for (uint256 i=0;i<len;i++){
// if (whiteList[i] == temp)
// return true;
// }
// return false;
// }
// function _getEligibleIndexUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (uint256){
// uint256 len = whiteList.length;
// uint256 i=0;
// for (;i<len;i++){
// if (whiteList[i] == temp)
// break;
// }
// return i;
// }
// }
// /**
// * @dev Implementation of a whitelist which filters a eligible uint256.
// */
// library whiteListUint256 {
// // add whiteList
// function addWhiteListUint256(uint256[] storage whiteList,uint256 temp) internal{
// if (!isEligibleUint256(whiteList,temp)){
// whiteList.push(temp);
// }
// }
// function removeWhiteListUint256(uint256[] storage whiteList,uint256 temp)internal returns (bool) {
// uint256 len = whiteList.length;
// uint256 i=0;
// for (;i<len;i++){
// if (whiteList[i] == temp)
// break;
// }
// if (i<len){
// if (i!=len-1) {
// whiteList[i] = whiteList[len-1];
// }
// whiteList.pop();
// return true;
// }
// return false;
// }
// function isEligibleUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (bool){
// uint256 len = whiteList.length;
// for (uint256 i=0;i<len;i++){
// if (whiteList[i] == temp)
// return true;
// }
// return false;
// }
// function _getEligibleIndexUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (uint256){
// uint256 len = whiteList.length;
// uint256 i=0;
// for (;i<len;i++){
// if (whiteList[i] == temp)
// break;
// }
// return i;
// }
// }
// /**
// * @dev Implementation of a whitelist which filters a eligible address.
// */
// library whiteListAddress {
// // add whiteList
// function addWhiteListAddress(address[] storage whiteList,address temp) internal{
// if (!isEligibleAddress(whiteList,temp)){
// whiteList.push(temp);
// }
// }
// function removeWhiteListAddress(address[] storage whiteList,address temp)internal returns (bool) {
// uint256 len = whiteList.length;
// uint256 i=0;
// for (;i<len;i++){
// if (whiteList[i] == temp)
// break;
// }
// if (i<len){
// if (i!=len-1) {
// whiteList[i] = whiteList[len-1];
// }
// whiteList.pop();
// return true;
// }
// return false;
// }
// function isEligibleAddress(address[] memory whiteList,address temp) internal pure returns (bool){
// uint256 len = whiteList.length;
// for (uint256 i=0;i<len;i++){
// if (whiteList[i] == temp)
// return true;
// }
// return false;
// }
// function _getEligibleIndexAddress(address[] memory whiteList,address temp) internal pure returns (uint256){
// uint256 len = whiteList.length;
// uint256 i=0;
// for (;i<len;i++){
// if (whiteList[i] == temp)
// break;
// }
// return i;
// }
// }
// // File: contracts\modules\Operator.sol
// pragma solidity >=0.6.0;
// /**
// * @dev Contract module which provides a basic access control mechanism, where
// * each operator can be granted exclusive access to specific functions.
// *
// */
// contract Operator is Ownable {
// using whiteListAddress for address[];
// address[] private _operatorList;
// /**
// * @dev modifier, every operator can be granted exclusive access to specific functions.
// *
// */
// modifier onlyOperator() {
// require(_operatorList.isEligibleAddress(msg.sender),"Managerable: caller is not the Operator");
// _;
// }
// /**
// * @dev modifier, Only indexed operator can be granted exclusive access to specific functions.
// *
// */
// modifier onlyOperatorIndex(uint256 index) {
// require(_operatorList.length>index && _operatorList[index] == msg.sender,"Managerable: caller is not the eligible Operator");
// _;
// }
// /**
// * @dev add a new operator by owner.
// *
// */
// function addOperator(address addAddress)public onlyOwner{
// _operatorList.addWhiteListAddress(addAddress);
// }
// /**
// * @dev modify indexed operator by owner.
// *
// */
// function setOperator(uint256 index,address addAddress)public onlyOwner{
// _operatorList[index] = addAddress;
// }
// /**
// * @dev remove operator by owner.
// *
// */
// function removeOperator(address removeAddress)public onlyOwner returns (bool){
// return _operatorList.removeWhiteListAddress(removeAddress);
// }
// /**
// * @dev get all operators.
// *
// */
// function getOperator()public view returns (address[] memory) {
// return _operatorList;
// }
// /**
// * @dev set all operators by owner.
// *
// */
// function setOperators(address[] memory operators)public onlyOwner {
// _operatorList = operators;
// }
// }
// // File: contracts\interfaces\AggregatorV3Interface.sol
// pragma solidity >=0.6.0;
// interface AggregatorV3Interface {
// function decimals() external view returns (uint8);
// function description() external view returns (string memory);
// function version() external view returns (uint256);
// // getRoundData and latestRoundData should both raise "No data present"
// // if they do not have data to report, instead of returning unset values
// // which could be misinterpreted as actual reported values.
// function getRoundData(uint80 _roundId)
// external
// view
// returns (
// uint80 roundId,
// int256 answer,
// uint256 startedAt,
// uint256 updatedAt,
// uint80 answeredInRound
// );
// function latestRoundData()
// external
// view
// returns (
// uint80 roundId,
// int256 answer,
// uint256 startedAt,
// uint256 updatedAt,
// uint80 answeredInRound
// );
// }
// // File: contracts\interfaces\IERC20.sol
// pragma solidity ^0.6.11;
// /**
// * @dev Interface of the ERC20 standard as defined in the EIP. Does not include
// * the optional functions; to access them see {ERC20Detailed}.
// */
// interface IERC20 {
// function decimals() external view returns (uint8);
// /**
// * @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: contracts\FNXOracle.sol
// pragma solidity ^0.6.7;
// contract FNXOracle is Operator {
// mapping(uint256 => AggregatorV3Interface) private assetsMap;
// mapping(uint256 => uint256) private decimalsMap;
// mapping(uint256 => uint256) private priceMap;
// uint256 internal decimals = 1;
// /**
// * Network: Ropsten
// * Aggregator: LTC/USD
// * Address: 0x727B59d0989d6D1961138122BC9F94f534E82B32
// */
// constructor() public {
// //mainnet
// assetsMap[1] = AggregatorV3Interface(0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c);
// assetsMap[2] = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
// assetsMap[3] = AggregatorV3Interface(0x24551a8Fb2A7211A25a17B1481f043A8a8adC7f2);
// assetsMap[4] = AggregatorV3Interface(0xDC3EA94CD0AC27d9A86C180091e7f78C683d3699);
// assetsMap[5] = AggregatorV3Interface(0x2c1d072e956AFFC0D435Cb7AC38EF18d24d9127c);
// assetsMap[0] = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
// assetsMap[uint256(0xeF9Cd7882c067686691B6fF49e650b43AFBBCC6B)] = AggregatorV3Interface(0x80070f7151BdDbbB1361937ad4839317af99AE6c);
// priceMap[uint256(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48)] = 1e20;
// decimalsMap[0] = 18;
// decimalsMap[1] = 18;
// decimalsMap[2] = 18;
// decimalsMap[3] = 18;
// decimalsMap[4] = 18;
// decimalsMap[5] = 18;
// decimalsMap[uint256(0xeF9Cd7882c067686691B6fF49e650b43AFBBCC6B)] = 18;
// decimalsMap[uint256(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48)] = 6;
// /*
// //rinkeby
// assetsMap[1] = AggregatorV3Interface(0xECe365B379E1dD183B20fc5f022230C044d51404);
// assetsMap[2] = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e);
// assetsMap[3] = AggregatorV3Interface(0xd8bD0a1cB028a31AA859A21A3758685a95dE4623);
// assetsMap[4] = AggregatorV3Interface(0xE96C4407597CD507002dF88ff6E0008AB41266Ee);
// assetsMap[5] = AggregatorV3Interface(0xd8bD0a1cB028a31AA859A21A3758685a95dE4623);
// assetsMap[0] = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e);
// assetsMap[uint256(0xaf30F6A6B09728a4e793ED6d9D0A7CcBa192c229)] = AggregatorV3Interface(0xcf74110A02b1D391B27cE37364ABc3b279B1d9D1);
// priceMap[uint256(0xD12BC93Ac5eA2b4Ba99e0ffEd053a53B6d18C7a3)] = 1e20;
// decimalsMap[0] = 18;
// decimalsMap[1] = 18;
// decimalsMap[2] = 18;
// decimalsMap[3] = 18;
// decimalsMap[4] = 18;
// decimalsMap[5] = 18;
// decimalsMap[uint256(0xaf30F6A6B09728a4e793ED6d9D0A7CcBa192c229)] = 18;
// decimalsMap[uint256(0xD12BC93Ac5eA2b4Ba99e0ffEd053a53B6d18C7a3)] = 6;
// */
// }
// function setDecimals(uint256 newDecimals) public onlyOwner{
// decimals = newDecimals;
// }
// function getAssetAndUnderlyingPrice(address asset,uint256 underlying) public view returns (uint256,uint256) {
// return (getUnderlyingPrice(uint256(asset)),getUnderlyingPrice(underlying));
// }
// function setPrices(uint256[]memory assets,uint256[]memory prices) public onlyOwner {
// require(assets.length == prices.length, "input arrays' length are not equal");
// uint256 len = assets.length;
// for (uint i=0;i<len;i++){
// priceMap[i] = prices[i];
// }
// }
// function getPrices(uint256[]memory assets) public view returns (uint256[]memory) {
// uint256 len = assets.length;
// uint256[] memory prices = new uint256[](len);
// for (uint i=0;i<len;i++){
// prices[i] = getUnderlyingPrice(assets[i]);
// }
// return prices;
// }
// /**
// * @notice retrieves price of an asset
// * @dev function to get price for an asset
// * @param asset Asset for which to get the price
// * @return uint mantissa of asset price (scaled by 1e8) or zero if unset or contract paused
// */
// function getPrice(address asset) public view returns (uint256) {
// return getUnderlyingPrice(uint256(asset));
// }
// function getUnderlyingPrice(uint256 underlying) public view returns (uint256) {
// if (underlying == 3){
// return getMKRPrice();
// }
// AggregatorV3Interface assetsPrice = assetsMap[underlying];
// if (address(assetsPrice) != address(0)){
// (, int price,,,) = assetsPrice.latestRoundData();
// uint256 tokenDecimals = decimalsMap[underlying];
// if (tokenDecimals < 18){
// return uint256(price)/decimals*(10**(18-tokenDecimals));
// }else if (tokenDecimals > 18){
// return uint256(price)/decimals/(10**(18-tokenDecimals));
// }else{
// return uint256(price)/decimals;
// }
// }else {
// return priceMap[underlying];
// }
// }
// function getMKRPrice() internal view returns (uint256) {
// AggregatorV3Interface assetsPrice = assetsMap[3];
// AggregatorV3Interface ethPrice = assetsMap[0];
// if (address(assetsPrice) != address(0) && address(ethPrice) != address(0)){
// (, int price,,,) = assetsPrice.latestRoundData();
// (, int ethPrice,,,) = ethPrice.latestRoundData();
// uint256 tokenDecimals = decimalsMap[3];
// uint256 mkrPrice = uint256(price*ethPrice)/decimals/1e18;
// if (tokenDecimals < 18){
// return mkrPrice/decimals*(10**(18-tokenDecimals));
// }else if (tokenDecimals > 18){
// return mkrPrice/decimals/(10**(18-tokenDecimals));
// }else{
// return mkrPrice/decimals;
// }
// }else {
// return priceMap[3];
// }
// }
// /**
// * @notice set price of an asset
// * @dev function to set price for an asset
// * @param asset Asset for which to set the price
// * @param price the Asset's price
// */
// function setPrice(address asset,uint256 price) public onlyOperatorIndex(0) {
// priceMap[uint256(asset)] = price;
// }
// /**
// * @notice set price of an underlying
// * @dev function to set price for an underlying
// * @param underlying underlying for which to set the price
// * @param price the underlying's price
// */
// function setUnderlyingPrice(uint256 underlying,uint256 price) public onlyOperatorIndex(0) {
// require(underlying>0 , "underlying cannot be zero");
// priceMap[underlying] = price;
// }
// /**
// * @notice set price of an asset
// * @dev function to set price for an asset
// * @param asset Asset for which to set the price
// * @param aggergator the Asset's aggergator
// */
// function setAssetsAggregator(address asset,address aggergator,uint256 _decimals) public onlyOwner {
// assetsMap[uint256(asset)] = AggregatorV3Interface(aggergator);
// decimalsMap[uint256(asset)] = _decimals;
// }
// /**
// * @notice set price of an underlying
// * @dev function to set price for an underlying
// * @param underlying underlying for which to set the price
// * @param aggergator the underlying's aggergator
// */
// function setUnderlyingAggregator(uint256 underlying,address aggergator,uint256 _decimals) public onlyOwner {
// require(underlying>0 , "underlying cannot be zero");
// assetsMap[underlying] = AggregatorV3Interface(aggergator);
// decimalsMap[underlying] = _decimals;
// }
// function getAssetsAggregator(address asset) public view returns (address,uint256) {
// return (address(assetsMap[uint256(asset)]),decimalsMap[uint256(asset)]);
// }
// function getUnderlyingAggregator(uint256 underlying) public view returns (address,uint256) {
// return (address(assetsMap[underlying]),decimalsMap[underlying]);
// }
// }
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
/*
* @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.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "../Common/Context.sol";
import "./IERC20.sol";
import "../Math/SafeMath.sol";
import "../Utils/Address.sol";
// Due to compiling issues, _name, _symbol, and _decimals were removed
/**
* @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 {ERC20Mintable}.
*
* 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 ERC20Custom is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) internal _allowances;
uint256 private _totalSupply;
/**
* @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.approve(address spender, uint256 amount)
*/
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 the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for `accounts`'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(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 is 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 Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal virtual {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
/**
* @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:using-hooks.adoc[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "../Common/Context.sol";
import "../Math/SafeMath.sol";
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
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);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
/**
* @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);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "./AggregatorV3Interface.sol";
contract ChainlinkETHUSDPriceConsumer {
AggregatorV3Interface internal priceFeed;
constructor() public {
priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
}
/**
* Returns the latest price
*/
function getLatestPrice() public view returns (int) {
(
,
int price,
,
,
) = priceFeed.latestRoundData();
return price;
}
function getDecimals() public view returns (uint8) {
return priceFeed.decimals();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../Math/SafeMath.sol";
library FraxPoolLibrary {
using SafeMath for uint256;
// Constants for various precisions
uint256 private constant PRICE_PRECISION = 1e6;
// ================ Structs ================
// Needed to lower stack size
struct MintFF_Params {
uint256 fxs_price_usd;
uint256 col_price_usd;
uint256 fxs_amount;
uint256 collateral_amount;
uint256 col_ratio;
}
struct BuybackFXS_Params {
uint256 excess_collateral_dollar_value_d18;
uint256 fxs_price_usd;
uint256 col_price_usd;
uint256 FXS_amount;
}
// ================ Functions ================
function calcMint1t1FRAX(uint256 col_price, uint256 collateral_amount_d18) public pure returns (uint256) {
return (collateral_amount_d18.mul(col_price)).div(1e6);
}
function calcMintAlgorithmicFRAX(uint256 fxs_price_usd, uint256 fxs_amount_d18) public pure returns (uint256) {
return fxs_amount_d18.mul(fxs_price_usd).div(1e6);
}
// Must be internal because of the struct
function calcMintFractionalFRAX(MintFF_Params memory params) internal pure returns (uint256, uint256) {
// Since solidity truncates division, every division operation must be the last operation in the equation to ensure minimum error
// The contract must check the proper ratio was sent to mint FRAX. We do this by seeing the minimum mintable FRAX based on each amount
uint256 fxs_dollar_value_d18;
uint256 c_dollar_value_d18;
// Scoping for stack concerns
{
// USD amounts of the collateral and the FXS
fxs_dollar_value_d18 = params.fxs_amount.mul(params.fxs_price_usd).div(1e6);
c_dollar_value_d18 = params.collateral_amount.mul(params.col_price_usd).div(1e6);
}
uint calculated_fxs_dollar_value_d18 =
(c_dollar_value_d18.mul(1e6).div(params.col_ratio))
.sub(c_dollar_value_d18);
uint calculated_fxs_needed = calculated_fxs_dollar_value_d18.mul(1e6).div(params.fxs_price_usd);
return (
c_dollar_value_d18.add(calculated_fxs_dollar_value_d18),
calculated_fxs_needed
);
}
function calcRedeem1t1FRAX(uint256 col_price_usd, uint256 FRAX_amount) public pure returns (uint256) {
return FRAX_amount.mul(1e6).div(col_price_usd);
}
// Must be internal because of the struct
function calcBuyBackFXS(BuybackFXS_Params memory params) internal pure returns (uint256) {
// If the total collateral value is higher than the amount required at the current collateral ratio then buy back up to the possible FXS with the desired collateral
require(params.excess_collateral_dollar_value_d18 > 0, "No excess collateral to buy back!");
// Make sure not to take more than is available
uint256 fxs_dollar_value_d18 = params.FXS_amount.mul(params.fxs_price_usd).div(1e6);
require(fxs_dollar_value_d18 <= params.excess_collateral_dollar_value_d18, "You are trying to buy back more than the excess!");
// Get the equivalent amount of collateral based on the market value of FXS provided
uint256 collateral_equivalent_d18 = fxs_dollar_value_d18.mul(1e6).div(params.col_price_usd);
//collateral_equivalent_d18 = collateral_equivalent_d18.sub((collateral_equivalent_d18.mul(params.buyback_fee)).div(1e6));
return (
collateral_equivalent_d18
);
}
// Returns value of collateral that must increase to reach recollateralization target (if 0 means no recollateralization)
function recollateralizeAmount(uint256 total_supply, uint256 global_collateral_ratio, uint256 global_collat_value) public pure returns (uint256) {
uint256 target_collat_value = total_supply.mul(global_collateral_ratio).div(1e6); // We want 18 decimals of precision so divide by 1e6; total_supply is 1e18 and global_collateral_ratio is 1e6
// Subtract the current value of collateral from the target value needed, if higher than 0 then system needs to recollateralize
return target_collat_value.sub(global_collat_value); // If recollateralization is not needed, throws a subtraction underflow
// return(recollateralization_left);
}
function calcRecollateralizeFRAXInner(
uint256 collateral_amount,
uint256 col_price,
uint256 global_collat_value,
uint256 frax_total_supply,
uint256 global_collateral_ratio
) public pure returns (uint256, uint256) {
uint256 collat_value_attempted = collateral_amount.mul(col_price).div(1e6);
uint256 effective_collateral_ratio = global_collat_value.mul(1e6).div(frax_total_supply); //returns it in 1e6
uint256 recollat_possible = (global_collateral_ratio.mul(frax_total_supply).sub(frax_total_supply.mul(effective_collateral_ratio))).div(1e6);
uint256 amount_to_recollat;
if(collat_value_attempted <= recollat_possible){
amount_to_recollat = collat_value_attempted;
} else {
amount_to_recollat = recollat_possible;
}
return (amount_to_recollat.mul(1e6).div(col_price), amount_to_recollat);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import './Babylonian.sol';
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint _x;
}
uint8 private constant RESOLUTION = 112;
uint private constant Q112 = uint(1) << RESOLUTION;
uint private constant Q224 = Q112 << RESOLUTION;
// encode a uint112 as a UQ112x112
function encode(uint112 x) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(x) << RESOLUTION);
}
// encodes a uint144 as a UQ144x112
function encode144(uint144 x) internal pure returns (uq144x112 memory) {
return uq144x112(uint256(x) << RESOLUTION);
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) {
require(x != 0, 'FixedPoint: DIV_BY_ZERO');
return uq112x112(self._x / uint224(x));
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) {
uint z;
require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW");
return uq144x112(z);
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// equivalent to encode(numerator).div(denominator)
function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112((uint224(numerator) << RESOLUTION) / denominator);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
// take the reciprocal of a UQ112x112
function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) {
require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL');
return uq112x112(uint224(Q224 / self._x));
}
// square root of a UQ112x112
function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import '../Uniswap/Interfaces/IUniswapV2Pair.sol';
import '../Math/FixedPoint.sol';
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function currentBlockTimestamp() internal view returns (uint32) {
return uint32(block.timestamp % 2 ** 32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function currentCumulativePrices(
address pair
) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
blockTimestamp = currentBlockTimestamp();
price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();
price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
// counterfactual
price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import './Interfaces/IUniswapV2Pair.sol';
import './Interfaces/IUniswapV2Factory.sol';
import "../Math/SafeMath.sol";
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// Less efficient than the CREATE2 method below
function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = IUniswapV2Factory(factory).getPair(token0, token1);
}
// calculates the CREATE2 address for a pair without making any external calls
function pairForCreate2(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
)))); // this matches the CREATE2 in UniswapV2Factory.createPair
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
// else z = 0
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
| Can only be triggered by owner or governance, not custodian Tokens are sent to the custodian, as a sort of safeguard | function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance {
ERC20(tokenAddress).transfer(custodian_address, tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
event Recovered(address token, uint256 amount);
| 13,908,557 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* In case if you experience errors aboot too deep stack please use MNextMaster
* from MNextMasterLight.sol.
*
* It performs less checks which means less security on one hand but
* compatibility with common configured EVMs like this of Ethereum ecosystem
* on the other hand.
*
* To see the differences please read the leading comment in the file
* MNextMasterLight.sol.
*/
import './MNextDataModel.sol';
contract MNextMaster is MNextDataModel{
/*
* ###########
* # STRUCTS #
* ###########
*/
// ////////
// / BANK /
// ////////
struct BankWrapper {
Bank bank;
bool isLocked;
}
// /////////
// / CHECK /
// /////////
struct CheckWrapper {
Check check;
bool isLocked;
}
// ////////
// / USER /
// ////////
struct User {
uint8 state;
bool isLocked;
}
// //////////////
// / UTXO (BTC) /
// //////////////
struct BTCutxo {
address utxo;
uint256 satoshi;
uint16 bank;
uint256 account;
}
/*
* ####################
* # PUBLIC VARIABLES #
* ####################
*/
//////////////////////////////
// SYSTEM'S KEY DESCRIPTORS //
//////////////////////////////
string public name;
string public token;
string public symbol;
string public admin;
string public api;
string public site;
string public explorer;
mapping (uint8 => NoteType) public noteTypes;
/*
* #####################
* # PRIVATE VARIABLES #
* #####################
*/
/////////////////////////////
// SYSTEM'S KEY CONTAINERS //
/////////////////////////////
mapping (uint16 => BankWrapper) private _banks;
mapping (uint256 => CheckWrapper) private _checks;
mapping (uint256 => Coin) private _coins;
mapping (uint256 => Note) private _notes;
mapping (address => User) private _users;
mapping (uint256 => BTCutxo) private _utxos;
/////////////////////////////
// SYSTEM'S KEY CONDITIONS //
/////////////////////////////
uint256 private _satoshiBase;
int32 private _reserveRatio;
uint16 private _multiplier;
/////////////////////////
// MAINTENANCE HELPERS //
/////////////////////////
uint16 private _nextBankId;
uint256 private _nextCoinId;
uint256 private _nextNoteId;
uint256 private _nextCheckId;
uint256 private _utxoPointer;
////////////////////////////////
// SYSTEM ADMIN'S CREDENTIALS //
////////////////////////////////
address payable private _rootUser;
bytes32 private _rootKey;
/*
* Contract constructor
* --------------------
* Construct the contract
*
* @param string memory sentence
* A sentence to protect master access.
* @param uint256 satoshiBase_
* Value to set as system's base unit.
* @param int32 reserveRatio_
* Value to set as system's reserve ratio.
* @param uint16 multiplier_
* Value to set as system's multiplier.
*/
constructor(string memory sentence, uint256 satoshiBase_,
int32 reserveRatio_, uint16 multiplier_) payable {
_rootUser = payable(msg.sender);
_rootKey = keccak256(abi.encodePacked(sentence));
_satoshiBase = satoshiBase_;
_reserveRatio = reserveRatio_;
_multiplier = multiplier_;
/*
* SETUP BTC GATEWAY.
*/
_nextBankId = 0;
_nextCheckId = 0;
_nextCoinId = 0;
_nextNoteId = 0;
}
// C A U T I O N ! ! !
//
// Don't forget to remove the section below in production to save the system
// tokens.
/*
* ##################
* # Mock functions #
* ##################
*/
/*
* Get mock coins
* --------------
* Create mock coins to the caller
*
* @param uint256 amount
* Amount of coins to create.
*/
function mockCreateCoins(uint256 amount) external {
_users[msg.sender].state = USER_ACTIVE_AND_RESTRICTIONLESS;
for (uint256 i=0; i<amount; i++) {
_coins[i] = Coin(address(0), i, 0, msg.sender, COIN_ACTIVE_AND_FREE);
_nextCoinId++;
}
}
/*
* Get mock coins
* --------------
* Create mock coins to a foreign user
*
* @param address user
* Address of the user to create mock coins for.
* @param uint256 amount
* Amount of coins to create.
*/
function mockCreateUserWithBalance(address user, uint256 amount) external {
_users[user].state = USER_ACTIVE_AND_RESTRICTIONLESS;
for (uint256 i=0; i<amount; i++) {
_coins[i] = Coin(address(0), i, 0, user, COIN_ACTIVE_AND_FREE);
_nextCoinId++;
}
}
/*
* Mock transaction between users
* ------------------------------
* Perform mock transaction between foreign users
*
* @param address sender
* Address of the user to send mock coins from.
* @param address target
* Address of the user to send mock coins to.
* @param uint256 amount
* Amount of coins to create.
*
* @note Please keep in mind, though it's a mock transaction function, it
* calls the real inside _transact() function. So sender must have
* enough coins to send. The function mockCreateCoins() is useful to
* help you out.
*/
function mockTransact(address sender, address target, uint256 amount)
external returns (bool) {
return _transact(sender, target, amount);
}
/*
* #########################
* # End of mock functions #
* #########################
*/
// Don't forget to remove the section above in production to save the system
// tokens.
//
// C A U T I O N ! ! !
/*
* ########################
* # System level actions #
* ########################
*/
/*
* Review coin supply
* ------------------
* Review the coin supply of the system
*/
function review() external {
_utxoPointer = 0;
for (uint16 i=0; i < _nextBankId; i++) __reviewBank(i);
__reviewCoins();
}
/*
* Set system admin name
* ---------------------
* Set the name of the system's admin
*
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newAdmin
* The new name of the admin.
*/
function setAdmin(string calldata sentence, string calldata newAdmin)
onlyAdmin(sentence) external {
admin = newAdmin;
}
/*
* Set system API root
* -------------------
* Set the link to the system's API root
*
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newApi
* The new link to the API root.
*/
function setApi(string calldata sentence, string calldata newApi)
onlyAdmin(sentence) external {
api = newApi;
}
/*
* Set system explorer
* -------------------
* Set the link to the system's data explorer
*
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newExplorer
* The new link to the explorer.
*/
function setExplorer(string calldata sentence, string calldata newExplorer)
onlyAdmin(sentence) external {
explorer = newExplorer;
}
/*
* Set multiplier
* --------------
* Set the value of the system's multiplier
*
* @param string calldata sentence
* A sentence to protect master access.
* @param uint16 newMultiplier_
* The new multiplier value.
*/
function setMultiplier(string calldata sentence, uint16 newMultiplier_)
onlyAdmin(sentence) external {
_multiplier = newMultiplier_;
this.review();
}
/*
* Set system name
* --------------
* Set the name of the system
*
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newName
* The new name of the system.
*/
function setName(string calldata sentence, string calldata newName)
onlyAdmin(sentence) external {
name = newName;
}
/*
* Set reserve ratio
* -----------------
* Set the value of the system's reserve ratio
*
* @param string calldata sentence
* A sentence to protect master access.
* @param int32 newReserveRatio_
* The new reserve ratio value.
*
* @note Since solidity doesn't handle fractions, to set the percentage
* value you have to multiply the original (fraction) value with 100.
*/
function setReserveRatio(string calldata sentence, int32 newReserveRatio_)
onlyAdmin(sentence) external {
_reserveRatio = newReserveRatio_;
this.review();
}
/*
* Set satoshi base
* ----------------
* Set the value of the system's Satoshi base
*
* @param string calldata sentence
* A sentence to protect master access.
* @param uint256 newSatoshiBase_
* The new Satoshi base value.
*/
function setSatoshiBase(string calldata sentence, uint256 newSatoshiBase_)
onlyAdmin(sentence) external {
_satoshiBase = newSatoshiBase_;
this.review();
}
/*
* Set system homepage
* -------------------
* Set the link to the system's homepage
*
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newSite
* The new link to the homepage.
*/
function setSite(string calldata sentence, string calldata newSite)
onlyAdmin(sentence) external {
site = newSite;
}
/*
* Set token symbol
* ----------------
* Set the symbol of the system's token
*
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newSymbol
* The new symbol of the token.
*/
function setSymbol(string calldata sentence, string calldata newSymbol)
onlyAdmin(sentence) external {
symbol = newSymbol;
}
/*
* Set token name
* --------------
* Set the name of the system's token
*
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newToken
* The new name of the token.
*/
function setToken(string calldata sentence, string calldata newToken)
onlyAdmin(sentence) external {
token = newToken;
}
/*
* ############################
* # System level information #
* ############################
*/
/*
* Get multiplier
* --------------
* Get the value of the system's multiplier
*
* @return uint16
* The actual multiplier value.
*/
function getMultiplier() external view returns (uint16) {
return _multiplier;
}
/*
* Get reserve ratio
* -----------------
* Get the value of the system's reserve ratio
*
* @return int32
* The actual reserve ratio value.
*
* @note Since solidity doesn't handle fractions, to receive the percentage
* value you have to divide the returned value with 100.
*/
function getReserveRatio() external view returns (int32) {
return _reserveRatio;
}
/*
* Get satoshi base
* ----------------
* Get the value of the system's Satoshi base
*
* @return uint256
* The actual Satoshi base value.
*/
function getSatoshiBase() external view returns (uint256) {
return _satoshiBase;
}
/*
* Get active coin count
* ---------------------
* Get the count of active coins in the system
*
* @return uint256
* The actual count of active coins.
*/
function getCoinCount() external view returns (uint256) {
uint256 result = 0;
for (uint256 i=0; i < _nextCoinId; i++)
if (_coins[i].state == COIN_ACTIVE_AND_FREE
|| _coins[i].state == COIN_ACTIVE_IN_CHECK
|| _coins[i].state == COIN_ACTIVE_IN_NOTE)
result++;
return result;
}
/*
* #########
* # Banks #
* #########
*/
////////////
// CREATE //
////////////
/*
* Create bank
* -----------
* Create (register) a bank
*
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata bankName
* The name of the bank to register.
* @param address mainAccount
* An address to be used as the bank's main account.
* @param string calldata firstPassPhrase
* A password phrase to be used as the first [0] security key.
*/
function createBank(string calldata sentence, string calldata bankName,
address mainAccount, string calldata firstPassPhrase)
onlyAdmin(sentence) lockBank(_nextBankId) external
returns (uint16) {
uint16 thisId = _nextBankId;
bytes32[] memory keyArray = new bytes32[] (1);
keyArray[0] = keccak256(abi.encodePacked(firstPassPhrase));
_banks[thisId].bank.name = bankName;
_banks[thisId].bank.api = '';
_banks[thisId].bank.site = '';
delete _banks[thisId].bank.accountsBTC;
_banks[thisId].bank.mainAccount = mainAccount;
delete _banks[thisId].bank.accounts;
delete _banks[thisId].bank.keys;
_banks[thisId].bank.state = BANK_CREATED;
_nextBankId++;
return thisId;
}
//////////
// READ //
//////////
/*
* Get a bank
* ----------
* Get data of a bank
*
* @param uint16 id
* ID of the check.
*
* @return Bank memory
* The data of the given bank.
*
* @note Keys of the bank rest hidden.
*/
function getBank(uint16 id) external view returns (Bank memory) {
bytes32[] memory keyArray = new bytes32[] (0);
Bank memory result = _banks[id].bank;
result.keys = keyArray;
return result;
}
/*
* Get bank count
* --------------
* Get the count of all banks.
*
* @return uin16
* The count of the banks.
*/
function getBankCount() external view returns (uint16) {
return _nextBankId;
}
/*
* Get all banks
* -------------
* Get data of all banks
*
* @return Bank[] memory
* List of data of all banks.
*
* @note Keys of banks rest hidden.
*/
function getBanks() external view returns (Bank[] memory) {
Bank[] memory result = new Bank[](_nextBankId);
bytes32[] memory keyArray = new bytes32[] (0);
for (uint16 i=0; i < _nextBankId; i++) {
result[i] = _banks[i].bank;
result[i].keys = keyArray;
}
return result;
}
////////////
// UPDATE //
////////////
/*
* TODO IMPLEMENT
*
* BTC accounts:
* - addBankBTCAccount(uint16 id, string calldata sentence, address btcAccount)
* - addBankBTCAccount(uint16 id, uint256 keyId, string calldata passPhrase, address btcAccount)
* - activateBankBTCAccount(uint16 id, uint256 accountId, string calldata sentence)
* - activateBankBTCAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase)
* - deleteBankBTCAccount(uint16 id, uint256 accountId, string calldata sentence)
* - deleteBankBTCAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase)
* - suspendBankBTCAccount(uint16 id, uint256 accountId, string calldata sentence)
* - suspendBankBTCAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase)
*
* Note: BTC account related functions autamotically call review()
*
* System accounts:
* - addBankAccount(uint16 id, string calldata sentence, address account)
* - addBankAccount(uint16 id, uint256 keyId, string calldata passPhrase, address account)
* - activateBankAccount(uint16 id, uint256 accountId, string calldata sentence)
* - activateBankAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase)
* - deleteBankAccount(uint16 id, uint256 accountId, string calldata sentence)
* - deleteBankAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase)
* - suspendBankAccount(uint16 id, uint256 accountId, string calldata sentence)
* - suspendBankAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase)
*
* - addBankKey(string calldata sentence, string calldata passPhrase)
* - addBankKey(uint256 keyId, string calldata passPhrase, string calldata passPhrase)
* - changeBankKey(uint16 id, uint256 affectedKeyId, string calldata sentence, string calldata newPassPhrase)
* - changeBankKey(uint16 id, uint256 affectedKeyId, uint256 keyId, string calldata passPhrase, string calldata newPassPhrase)
*
* TODO: CHANGE
*
* - More complex key validation system.
*/
/*
* Activate bank
* -------------
* Activate a non activated bank
*
* @param uint16 id
* The ID of the bank to activate.
* @param string calldata sentence
* A sentence to protect master access.
*/
function activateBank(uint16 id, string calldata sentence)
onlyAdmin(sentence) onlyExistingBank(id) lockBank(id)
external {
require(_banks[id].bank.state == BANK_CREATED,
'Cannot activate bank with a non appropriate state.');
_banks[id].bank.state = BANK_ACTIVE_AND_RESTRICTIONLESS;
}
/*
* Set API site link of a bank
* ---------------------------
* Set the link to the API root of the bank
*
* @param uint16 id
* The ID of the bank.
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newApi
* The new API site link to set.
*/
function setBankApi(uint16 id, string calldata sentence,
string calldata newApi) onlyAdmin(sentence)
onlyExistingBank(id) lockBank(id) external {
_banks[id].bank.api = newApi;
}
/*
* Set API site link of a bank
* ---------------------------
* Set the link to the API root of the bank
*
* @param uint16 id
* The ID of the bank.
* @param uint256 keyId
* The ID of the key to valIdate transaction with.
* @param string calldata passPhrase
* A password phrase that matches the key to grant access.
* @param string calldata newApi
* The new API site link to set.
*/
function setBankApi(uint16 id, uint256 keyId, string calldata passPhrase,
string calldata newApi) onlyExistingBank(id)
lockBank(id) onlyValIdBankAction(id, keyId, passPhrase)
external {
_banks[id].bank.api = newApi;
}
/*
* Set name of a bank
* ------------------
* Set the name of the bank
*
* @param uint16 id
* The ID of the bank.
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newName
* The new name to set.
*/
function setBankName(uint16 id, string calldata sentence,
string calldata newName) onlyAdmin(sentence)
onlyExistingBank(id) lockBank(id) external {
_banks[id].bank.name = newName;
}
/*
* Set name of a bank
* ------------------
* Set the name of the bank
*
* @param uint16 id
* The ID of the bank.
* @param uint256 keyId
* The ID of the key to valIdate transaction with.
* @param string calldata passPhrase
* A password phrase that matches the key to grant access.
* @param string calldata newName
* The new name to set.
*/
function setBankName(uint16 id, uint256 keyId, string calldata passPhrase,
string calldata newName) onlyExistingBank(id)
lockBank(id) onlyValIdBankAction(id, keyId, passPhrase)
external {
_banks[id].bank.name = newName;
}
/*
* Set homepage link of a bank
* ---------------------------
* Set the link to the homepage of the bank
*
* @param uint16 id
* The ID of the bank.
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newSite
* The new homepage link to set.
*/
function setBankSite(uint16 id, string calldata sentence,
string calldata newSite) onlyAdmin(sentence)
onlyExistingBank(id) lockBank(id) external {
_banks[id].bank.site = newSite;
}
/*
* Set homepage link of a bank
* ---------------------------
* Set the link to the homepage of the bank
*
* @param uint16 id
* The ID of the bank.
* @param uint256 keyId
* The ID of the key to valIdate transaction with.
* @param string calldata passPhrase
* A password phrase that matches the key to grant access.
* @param string calldata newSite
* The new homepage link to set.
*/
function setBankSite(uint16 id, uint256 keyId, string calldata passPhrase,
string calldata newSite) onlyExistingBank(id)
lockBank(id) onlyValIdBankAction(id, keyId, passPhrase)
external {
_banks[id].bank.site = newSite;
}
/*
* Suspend bank
* ------------
* Suspend am active bank
*
* @param uint16 id
* The ID of the bank to suspend.
* @param string calldata sentence
* A sentence to protect master access.
*/
function suspendBank(uint16 id, string calldata sentence)
onlyAdmin(sentence) onlyExistingBank(id) lockBank(id)
external {
require(_banks[id].bank.state == BANK_SUSPENDED
|| _banks[id].bank.state == BANK_DELETED,
'Cannot suspend a bank with a non appropriate state.');
_banks[id].bank.state = BANK_SUSPENDED;
}
////////////
// DELETE //
////////////
/*
* Delete bank
* -----------
* Delete an existing bank
*
* @param uint16 id
* The ID of the bank to delete.
* @param string calldata sentence
* A sentence to protect master access.
*/
function deleteBank(uint16 id, string calldata sentence) onlyAdmin(sentence)
onlyExistingBank(id) lockBank(id) external {
require(_banks[id].bank.state == BANK_DELETED,
'Cannot delete an already deleted bank.');
_banks[id].bank.state = BANK_DELETED;
}
/*
* ##########
* # Checks #
* ##########
*/
////////////
// CREATE //
////////////
/*
* Create check
* ------------
* Create a check without activation
*
* @param uint256 amount
* The amount of the check.
* @param string memory passPhrase
* A pharese to secure the check.
*/
function createActiveCheck(uint256 amount, string calldata passPhrase)
lockUser(msg.sender) external returns (uint256) {
return _createCheck(amount, passPhrase, CHECK_ACTIVATED);
}
/*
* Create check
* ------------
* Create a check with activation
*
* @param uint256 amount
* The amount of the check.
* @param string memory passPhrase
* A pharese to secure the check.
*/
function createCheck(uint256 amount, string calldata passPhrase)
lockUser(msg.sender) external returns (uint256) {
return _createCheck(amount, passPhrase, CHECK_CREATED);
}
//////////
// READ //
//////////
/*
* Get a check
* -----------
* Get data of a check
*
* @param uint256 id
* ID of the check.
*
* @note Check's key is hIdden. This way the key of the check cannot be
* retrieved. This design decision pushes big responsibility to the
* end-users' application.
*/
function getCheck(uint256 id) external view returns (Check memory) {
return Check(_checks[id].check.owner, _checks[id].check.coins,
'', _checks[id].check.state);
}
/*
* Get check value
* ---------------
* Get the value of a check
*
* @param uint256 id
* ID of the check.
*
* @return uint256
* The value of the given check.
*/
function getCheckValue(uint256 id) external view returns (uint256) {
return _checks[id].check.coins.length;
}
////////////
// UPDATE //
////////////
/*
* Activate check
* --------------
* Activate a non activated check
*
* @param uint256 id
* ID of the check.
* @param string memory passPhrase
* A pharese to secure the check.
*/
function activateCheck(uint256 id, string calldata passPhrase) lockCheck(id)
onlyValIdCheckAction(id, msg.sender, passPhrase)
external {
require(_checks[id].check.state == CHECK_CREATED
|| _checks[id].check.state == CHECK_SUSPENDED,
'Cannot activate a check from a non appropriate state.');
_checks[id].check.state = CHECK_ACTIVATED;
}
/*
* Clear check
* -----------
* Clear an active check
*
* @param uint256 id
* ID of the check.
* @param string memory passPhrase
* A pharese to secure the check.
*/
function clearCeck(uint256 id, address from, string calldata passPhrase)
lockUser(msg.sender) lockUser(from)
lockCheck(id) onlyValIdCheckAction(id, from, passPhrase)
external {
require(_checks[id].check.state == CHECK_ACTIVATED,
'Cannot clear a non active check.');
require(_checks[id].check.owner == from,
'Original owner is needed to clear check.');
require(_checks[id].check.key == keccak256(abi.encodePacked(passPhrase)),
'Cannot clear a not opened check.');
// Note: consider to do this after the for loop. It is a hard decision.
_checks[id].check.state = CHECK_SPENT;
// There's no lack of {}s in the for loop and if selector below. :-)
for (uint256 i=0; i < _checks[id].check.coins.length; i++)
if (_coins[_checks[id].check.coins[i]].owner != from
|| _coins[_checks[id].check.coins[i]].state != COIN_ACTIVE_IN_CHECK)
revert('Internal error: Check clearance refused, safety first.');
else _coins[_checks[id].check.coins[i]].owner = msg.sender;
}
/*
* Suspend check
* -------------
* Suspend an existing and non suspended check
*
* @param uint256 id
* ID of the check.
* @param string memory passPhrase
* A pharese to secure the check.
*/
function suspendCheck(uint256 id, string calldata passPhrase) lockCheck(id)
onlyValIdCheckAction(id, msg.sender, passPhrase)
external {
require((_checks[id].check.state == CHECK_CREATED
|| _checks[id].check.state == CHECK_ACTIVATED),
'Cannot perform suspending on check with non appropriate state.');
_checks[id].check.state = CHECK_SUSPENDED;
}
////////////
// DELETE //
////////////
/*
* Delete a check
* --------------
* Delete a not yet cleared check
*
* @param uint256 id
* ID of the check.
* @param string memory passPhrase
* A pharese to secure the check.
*/
function deleteCheck(uint256 id, string calldata passPhrase) lockCheck(id)
onlyValIdCheckAction(id, msg.sender, passPhrase)
external {
require((_checks[id].check.state == CHECK_CREATED
|| _checks[id].check.state == CHECK_ACTIVATED
|| _checks[id].check.state == CHECK_SUSPENDED),
'Cannot perform deletioon on check with non appropriate state.');
// There's no lack of {} in the for loop below. :-)
for (uint i=0; i < _checks[id].check.coins.length; i++)
_coins[_checks[id].check.coins[i]].state = COIN_ACTIVE_AND_FREE;
_checks[id].check.state = CHECK_DELETED;
}
/*
* #########
* # Notes #
* #########
*/
// TODO: IMPLEMENT
/*
* ##############
* # Note types #
* ##############
*/
// TODO: IMPLEMENT
/*
* ###############################
* # User balance and user coins #
* ###############################
*/
/*
* Get the balance of a user
* -------------------------
* Get the total balance of a user
*
* @param address owner
* The address of the user to get balance for.
*
* @return uint256
* The balance of the user.
*/
function getBalance(address owner) external view returns (uint256) {
uint256 result = 0;
// There's no lack of {} in the for loop below. :-)
for (uint256 i=0; i < _nextCoinId; i++)
if (_coins[i].owner == owner) result += 1;
return result;
}
/*
* Get the coins of a user
* -----------------------
* Get the list of all coins of a user
*
* @param address owner
* The address of the user to get coins for.
*
* @return uint256[]
* List if IDs of the coins of the user.
*/
function getCoins(address owner) external view returns (uint256[] memory) {
// Becuse .push() is not available on memory arrays, a non-gas-friendly
// workaround should be used.
uint256 counter = 0;
// There's no lack of {} in the for loop below. :-)
for (uint256 i=0; i < _nextCoinId; i++)
if (_coins[i].owner == owner) counter++;
uint256[] memory result = new uint256[](counter);
counter = 0;
// There's no lack of {} in the for loop below. :-)
for (uint256 i=0; i < _nextCoinId; i++)
if (_coins[i].owner == owner) {
result[counter] = i;
counter++;
}
return result;
}
/*
* ################
* # TRANSACTIONS #
* ################
*/
/*
* Transact between users
* ----------------------
* Perform transaction between users
*
* @param address target
* Target address to send coins to.
* @param uint256 amount
* Amount of coins to send.
*
* @return bool
* True if the transaction was successful, false if not.
*
* @note In most cases like ERC20 token standard event is imetted on
* successful transactions. In this ecosystem the function transact()
* is called by MNextUser contract, therefore it is more convenient
* to return bool instead of emitting an event. Emitting event can
* happen in the user's contract depending on the implementation.
*/
function transact(address target, uint256 amount) lockUser(msg.sender)
lockUser(target) external returns (bool) {
return _transact(msg.sender, target, amount);
}
/*
* Transact between banks
* ----------------------
* Perform transaction between banks
*
* @param uint16 id
* ID of a bank to transact from.
* @param uint256 keyId
* The ID of the key to valIdate transaction with.
* @param string calldata passPhrase
* A password phrase that matches the key to grant access.
* @param uint16 target
* ID of a bank to transact to.
* @param uint256 amount
* Amount of coins to send.
*
* @return bool
* True if the transaction was successful, false if not.
*
* @note In most cases like ERC20 token standard event is imetted on
* successful transactions. In this ecosystem the function transact()
* is called by MNextBank contract, therefore it is more convenient
* to return bool instead of emitting an event. Emitting event can
* happen in the bank's contract depending on the implementation.
*/
function transactBankToBank(uint16 id, uint256 keyId,
string calldata passPhrase, uint16 target,
uint256 amount) onlyExistingBank(id)
lockBank(id)
onlyValIdBankAction(id, keyId, passPhrase)
onlyExistingBank(target) lockBank(target)
external returns (bool) {
return _transact(_banks[id].bank.mainAccount,
_banks[target].bank.mainAccount, amount);
}
/*
* Transact from bank to user
* --------------------------
* Perform transaction from a bank to a user
*
* @param uint16 id
* ID of a bank to transact from.
* @param uint256 keyId
* The ID of the key to valIdate transaction with.
* @param string calldata passPhrase
* A password phrase that matches the key to grant access.
* @param address target
* Target address to send coins to.
* @param uint256 amount
* Amount of coins to send.
*
* @return bool
* True if the transaction was successful, false if not.
*
* @note In most cases like ERC20 token standard event is imetted on
* successful transactions. In this ecosystem the function transact()
* is called by MNextBank contract, therefore it is more convenient
* to return bool instead of emitting an event. Emitting event can
* happen in the bank's contract depending on the implementation.
*/
function transactBankToUser(uint16 id, uint256 keyId,
string calldata passPhrase, address target,
uint256 amount) onlyExistingBank(id)
lockBank(id)
onlyValIdBankAction(id, keyId, passPhrase)
onlyExistingUser(target) lockUser(target)
external returns (bool) {
return _transact(_banks[id].bank.mainAccount, target, amount);
}
/*
* Transact from user to bank
* --------------------------
* Perform transaction from a user to a bank
*
* @param uint16 target
* ID of a bank to transact to.
* @param uint256 amount
* Amount of coins to send.
*
* @return bool
* True if the transaction was successful, false if not.
*
* @note In most cases like ERC20 token standard event is imetted on
* successful transactions. In this ecosystem the function transact()
* is called by MNextUser contract, therefore it is more convenient
* to return bool instead of emitting an event. Emitting event can
* happen in the user's contract depending on the implementation.
*/
function transactUserToBank(uint16 target, uint256 amount)
lockUser(msg.sender) lockBank(target)
external returns (bool) {
return _transact(msg.sender, _banks[target].bank.mainAccount, amount);
}
// TODO: IMPLEMENT if bank want to use other than mainAccount both for
// bank->bank, bank->user and user->bank transactions.
/*
* ######################
* # INTERNAL FUNCTIONS #
* ######################
*/
/*
* Create check with state
* -----------------------
* Create a check with the given state
*
* @param uint256 amount
* The amount of the check.
* @param string memory passPhrase
* A pharese to secure the check.
* @param uint8 state
* The state to create check with.
*/
function _createCheck(uint256 amount, string calldata passPhrase,
uint8 state) lockCheck(_nextCheckId)
private returns (uint256) {
// Becuse .push() is not available on memory arrays, a non-gas-friendly
// workaround should be used.
uint256 counter = 0;
// There's no lack of {} in the for loop below. :-)
for (uint256 i=0; i < _nextCoinId; i++)
if (_coins[i].owner == msg.sender
&& _coins[i].state == COIN_ACTIVE_AND_FREE)
counter++;
require(counter >= amount,
'Not enough balance to create chekk.');
uint256[] memory coins = new uint256[](counter);
counter = 0;
for (uint256 i=0; i < _nextCoinId; i++)
if (_coins[i].owner == msg.sender
&& _coins[i].state == COIN_ACTIVE_AND_FREE) {
_coins[i].state = COIN_ACTIVE_IN_CHECK;
coins[counter] = i;
counter++;
if (counter > amount) break;
}
uint256 _thisId = _nextCheckId;
if (_checks[_thisId].isLocked)
revert('Internal error: Check creation refused, safety first.');
_checks[_thisId].check = Check(msg.sender, coins,
keccak256(abi.encodePacked(passPhrase)),
state);
_nextCheckId++;
return _thisId;
}
/*
* Transact
* --------
* Perform transaction between addresses
*
* @param address owner
* Target address to send coins from.
* @param address target
* Target address to send coins to.
* @param uint256 amount
* Amount of coins to send.
*
* @return bool
* True if the transaction was successful, false if not.
*/
function _transact(address owner, address target, uint256 amount)
internal returns (bool) {
bool result = false;
uint256[] memory coinSupply = new uint256[] (amount);
uint256 counter = 0;
for (uint256 i=0; i < _nextCoinId; i++)
if (_coins[i].owner == owner
&& _coins[i].state == COIN_ACTIVE_AND_FREE) {
coinSupply[counter] = i;
counter++;
if (counter == amount) {
result = true;
break;
}
}
if (result) {
for (uint256 i=0; i < coinSupply.length; i++)
_coins[i].owner = target;
}
return result;
}
/*
* #####################
* # PRIVATE FUNCTIONS #
* #####################
*/
/*
* Review utxo deposits of a bank
* ------------------------------
* Collects information about presenting utxo deposits of the given bank
*
* @param uint16 id
* The ID of the bank to review.
*/
function __reviewBank(uint16 id) onlyExistingBank(id) lockBank(id) private {
for (uint256 i=0; i<_banks[id].bank.accountsBTC.length; i++) {
/*
* ACCES BTC GATEWAY.
*/
uint256 responseLength = 0;
address[] memory utxoList = new address[] (responseLength);
uint256[] memory amountList = new uint256[] (responseLength);
require(utxoList.length == amountList.length, 'BTC gateway error.');
for (uint256 j=0; j < utxoList.length; j++) {
_utxos[_utxoPointer] = BTCutxo(utxoList[j], amountList[j], id, i);
_utxoPointer++;
}
}
}
/*
* Review all the system coins
* ---------------------------
* Review system coins whether hey have the needed BTC deposits or not
*/
function __reviewCoins() private {
// HOW IT WORKS?
// 1. Gets all available utxos
// 2. Loops over coins and marks missing utxos
// 3. If there are coins without deposits, attempts to swap or delete them
// 4. If there are utxos without coins, they might used to coin swap
// 5. If there are utxos withoot coins after swaps, attempts to create coins
// 6. If something important happen in this functions events are mitted
}
/*
* #############
* # MODIFIERS #
* #############
*/
/*
* Lock a bank
* -----------
* Attempt to lock a bank during its data gets changed
*
* @param uint16 id
* The ID of the bank to lock.
*/
modifier lockBank(uint16 id) {
require(!_banks[id].isLocked,
'Cannot perform action on a locked bank.');
_banks[id].isLocked = true;
_;
_banks[id].isLocked = false;
}
/*
* Lock a check
* ------------
* Attempt to lock a check during its data gets changed
*
* @param uint256 id
* The ID of the check to lock.
*/
modifier lockCheck(uint256 id) {
require(!_checks[id].isLocked,
'Cannot perform action on a locked check.');
_checks[id].isLocked = true;
_;
_checks[id].isLocked = false;
}
/*
* Lock a user
* -----------
* Attempt to lock a user during its data gets changed
*
* @param address wallet
* The wallet of the user to lock.
*/
modifier lockUser(address wallet) {
require(!_users[wallet].isLocked,
'Cannot perform action on a locked user.');
_users[wallet].isLocked = true;
_;
_users[wallet].isLocked = false;
}
/*
* ValIdate admin
* --------------
* ValIdate access of the master contract owner
*
* @param string memory sentence
* A sentence to protect master access.
*/
modifier onlyAdmin(string memory sentence) {
require(msg.sender == _rootUser,
'Only admin can perform the action.');
require(keccak256(abi.encodePacked(sentence)) == _rootKey,
'Authorization failed.');
_;
}
/*
* Check existence of a bank
* -------------------------
* Check whether a bank exists or not
*
* @param uint16 id
* The ID of the bank to check.
*/
modifier onlyExistingBank(uint16 id) {
require(_banks[id].bank.state != STATE_UNAVAILABLE,
'Bank id must exist.');
_;
}
/*
* Check existence of a check
* --------------------------
* Check whether a check exists or not
*
* @param uint256 id
* The ID of the check to check.
*/
modifier onlyExistingCheck(uint256 id) {
require(_checks[id].check.state != STATE_UNAVAILABLE,
'Check id must exist.');
_;
}
/*
* Check existence of a coin
* -------------------------
* Check whether a coin exists or not
*
* @param uint256 id
* The ID of the coin to check.
*/
modifier onlyExistingCoin(uint256 id) {
require(_coins[id].state != STATE_UNAVAILABLE,
'Coin id must exist.');
_;
}
/*
* Check existence of a note
* -------------------------
* Check whether a note exists or not
*
* @param uint256 id
* The ID of the note to check.
*/
modifier onlyExistingNote(uint256 id) {
require(_notes[id].state != STATE_UNAVAILABLE,
'Note id must exist.');
_;
}
/*
* Check existence of a user
* -------------------------
* Check whether a user exists locally or not
*
* @param address who
* The address of the user to check.
*/
modifier onlyExistingUser(address who) {
require(_users[who].state != STATE_UNAVAILABLE
&& _users[who].state != USER_DELETED,
'User must exist.');
_;
}
modifier onlyValIdBankAction(uint16 id, uint256 keyId,
string calldata passPhrase) {
require(_banks[id].bank.keys.length < keyId,
'Cannot valIdate a non existing key.');
require(_banks[id].bank.keys[keyId]
== keccak256(abi.encodePacked(passPhrase)),
'Authorization failed.');
_;
}
/*
* ValIdate check access
* ---------------------
* ValIdate access credentials to perform actions on a check
*
* @param uint256 id
* ID of the check.
* @param address owner
* The address of owner of the check.
* @param string memory passPhrase
* A pharese to secure the check.
*/
modifier onlyValIdCheckAction(uint256 id, address owner,
string calldata passPhrase) {
require(_checks[id].check.owner == owner,
'Cannot perform action on a foreign check.');
require(_checks[id].check.key
== keccak256(abi.encodePacked(passPhrase)),
'Cannot perform action on a not opened check.');
_;
}
} | Create bank ----------- Create (register) a bank string calldata sentence A sentence to protect master access. string calldata bankName The name of the bank to register. address mainAccount An address to be used as the bank's main account. string calldata firstPassPhrase A password phrase to be used as the first [0] security key./ | function createBank(string calldata sentence, string calldata bankName,
address mainAccount, string calldata firstPassPhrase)
onlyAdmin(sentence) lockBank(_nextBankId) external
returns (uint16) {
uint16 thisId = _nextBankId;
bytes32[] memory keyArray = new bytes32[] (1);
keyArray[0] = keccak256(abi.encodePacked(firstPassPhrase));
_banks[thisId].bank.name = bankName;
_banks[thisId].bank.api = '';
_banks[thisId].bank.site = '';
delete _banks[thisId].bank.accountsBTC;
_banks[thisId].bank.mainAccount = mainAccount;
delete _banks[thisId].bank.accounts;
delete _banks[thisId].bank.keys;
_banks[thisId].bank.state = BANK_CREATED;
_nextBankId++;
return thisId;
}
| 2,507,076 |
./partial_match/4/0x42Cd0FdcDb8f52c5B04bB8Ef49F4A8C25b077a7D/sources/ERC721Metadata.sol | Internal function to set the token UserDateOfBirth for a given token. Reverts if the token ID does not exist. tokenId uint256 ID of the token to set its UserDateOfBirth userDateOfBirth string UserDateOfBirth to assign/ | function _setTokenUserDateOfBirth(uint256 tokenId, string memory userDateOfBirth) internal {
require(_exists(tokenId), "ERC721Metadata: UserDateOfBirth set of nonexistent token");
_userDateOfBirth[tokenId] = userDateOfBirth;
}
| 8,659,600 |
// SPDX-License-Identifier: MIT
pragma solidity =0.8.11;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import "./interfaces/IJamonSharePresale.sol";
import "./interfaces/IJamonShareVesting.sol";
import "./interfaces/IConversor.sol";
import "./interfaces/IJamonPair.sol";
import "./interfaces/IERC20MintBurn.sol";
/**
* @title JamonSharePresale
* @notice This contract will distribute the JamonShare tokens based on the new liquidity provided based on the value in USD for a ratio of 3 rounds.
* It also allows you to contribute the JamonV2 token, blocking it for 12 months and receiving JamonShare.
* Round 1 = 2 JamonV2 and 1 JamonShare for 1 USD aported.
* Round 1 = 1.8 JamonV2 and 1 JamonShare for 1 USD aported.
* Round 1 = 1.6 JamonV2 and 1 JamonShare for 1 USD aported.
* Jamon vested = 1.1 JamonV2 and 1.5 JamonShare for 1 USD aported at price 0.0113387 USD of old Jamon.
*/
contract JamonSharePresale is
IJamonSharePresale,
ReentrancyGuard,
Pausable,
Ownable
{
//---------- Libraries ----------//
using SafeMath for uint256;
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
//---------- Contracts ----------//
AggregatorV3Interface private maticFeed; // ChainLink aggregator MATIC/USD.
IJamonShareVesting private RewardVesting; // JamonShare vesting contract.
IConversor private Conversor; // Conversor V1 to V2 contract.
//---------- Variables ----------//
EnumerableSet.AddressSet private WhitelistLP; // List of wallets allowed for this pre-sale.
uint256 public constant max4list = 1400 ether; // 1400 USD per user in whitelist.
address private Governor; // Address of Governor contract for send a liquidity.
bool public listActive; // If the whitelist is active.
uint256 private constant roundHardcap = 350000 ether; // The maximum amount per round allowed in USD.
//---------- Storage -----------//
struct TokensContracts {
// WMATIC token contract.
IERC20 WMATIC;
// USDC token contract.
IERC20 USDC;
// New Jamon token contract.
IERC20MintBurn JAMON_V2;
// New pair MATIC/JAMONV2 contract.
IJamonPair MATIC_LP;
// New pair YSDC/JAMONV2 contract.
IJamonPair USDC_LP;
}
struct Round {
// Date in timestamp of the end of round.
uint256 endTime;
// Total amount collected of the round in wei.
uint256 collected;
}
TokensContracts internal CONTRACTS; // Struct of the contracts necessary for the operation
Round[3] public ROUNDS; // Array of 3 rounds.
mapping(address => uint256) public Max4Wallet; // Maximum quantity allowed for pre-sale blocking JamonV2.
mapping(address => uint256) public Spended; // Amount contributed by wallet for the limit of round 1
mapping(address => uint256) public JamonSpended; // Amount contributed by wallet for the limit of JamonV2 blocking
//---------- Events -----------//
event Contributed(
address indexed lp,
address indexed wallet,
uint256 rewardJV2,
uint256 rewardJS
);
//---------- Constructor ----------//
constructor(address jamon_, address conversor_) {
/**
* Network: Polygon
------------------------------
* Aggregator: MATIC/USD
* Address: 0xAB594600376Ec9fD91F8e885dADF0CE036862dE0
* Decimals: 8
*/
maticFeed = AggregatorV3Interface(
0xAB594600376Ec9fD91F8e885dADF0CE036862dE0
);
CONTRACTS.JAMON_V2 = IERC20MintBurn(jamon_);
Conversor = IConversor(conversor_);
listActive = true;
}
function initialize(
address wmatic_,
address usdc_,
address maticlpV2_,
address usdclpV2_,
address rewardVesting_,
address governor_
) external onlyOwner {
require(
address(CONTRACTS.WMATIC) == address(0x0),
"Already initialized"
);
CONTRACTS.WMATIC = IERC20(wmatic_);
CONTRACTS.USDC = IERC20(usdc_);
CONTRACTS.MATIC_LP = IJamonPair(maticlpV2_);
CONTRACTS.USDC_LP = IJamonPair(usdclpV2_);
RewardVesting = IJamonShareVesting(rewardVesting_);
Governor = governor_;
uint256 startAt = Conversor.endTime();
ROUNDS[0].endTime = startAt.add(10 days);
ROUNDS[1].endTime = startAt.add(20 days);
ROUNDS[2].endTime = startAt.add(30 days);
}
//----------- Internal Functions -----------//
/**
* @dev Take the price of JamonV2 compared to USD.
* @param usdAmount_ amount in USD for query.
* @return the price of token in ether
*/
function _getUSD2Jamon(uint256 usdAmount_) internal view returns (uint256) {
IJamonPair pair = IJamonPair(CONTRACTS.USDC_LP);
address token0 = pair.token0();
(uint256 Res0, uint256 Res1, ) = pair.getReserves();
uint256 price;
if (address(CONTRACTS.USDC) == token0) {
Res0 = Res0 * (1e12); // USDC 6 decimals, 6 + 12
price = ((usdAmount_ * Res1) / Res0);
} else {
Res1 = Res1 * (1e12); // USDC 6 decimals, 6 + 12
price = ((usdAmount_ * Res0) / Res1);
}
return price; // return amount of token0 needed to buy token1
}
/**
* @dev Take the price of MATIC compared to USD.
* @return the price of MATIC in ether.
*/
function _getMaticPrice() internal view returns (uint256) {
(, int256 price, , , ) = maticFeed.latestRoundData();
return uint256(price * 1e10); // Return price with 18 decimals, 8 + 10.
}
//----------- External Functions -----------//
/**
* @dev Check when the presale ends.
* @return The date in completion timestamp.
*/
function endsAt() external view returns (uint256) {
return ROUNDS[2].endTime;
}
/**
* @dev Check when the presale ends.
* @return The date in completion timestamp.
*/
function endsJamonAt() public view returns (uint256) {
return ROUNDS[2].endTime.add(10 days);
}
/**
* @dev Check when if limit in whitelist is actived.
* @return If limit is active or not.
*/
function listLimit() public view returns (bool) {
return Conversor.endTime().add(1 days) > block.timestamp;
}
/**
* @dev Check if a wallet is whitelisted.
* @param wallet_ Address to check.
* @return Whether it's on the list or not.
*/
function isOnWhitelist(address wallet_) external view returns (bool) {
return WhitelistLP.contains(wallet_);
}
/**
* @dev Check pre sale status.
* @return round the current round.
* @return rate the current rate.
*/
function status()
public
view
override
returns (uint256 round, uint256 rate)
{
if (ROUNDS[0].endTime < block.timestamp) {
if (ROUNDS[1].endTime < block.timestamp) {
if (ROUNDS[2].endTime < block.timestamp) {
return (4, 0);
}
return (3, 160);
}
return (2, 180);
}
if (Conversor.endTime() < block.timestamp) {
return (1, 200);
}
return (0, 0);
}
/**
* @notice Calculate the remaining amount on sale.
* @param lp_ Address of the LP token to query.
* @param round_ Round for query.
* @return The amount of LP available to sale.
*/
function remaining4Sale(
address wallet_,
address lp_,
uint256 round_
) public view returns (uint256) {
uint256 remaining;
uint256 available;
if (round_ == 1) {
available = roundHardcap.sub(ROUNDS[0].collected);
if (listLimit()) {
uint256 userRemaining = max4list.sub(Spended[wallet_]);
available = userRemaining > available
? available
: userRemaining;
}
}
if (round_ == 2) {
available = roundHardcap.sub(ROUNDS[1].collected);
}
if (round_ == 3) {
available = roundHardcap.sub(ROUNDS[2].collected);
}
if (lp_ == address(CONTRACTS.MATIC_LP)) {
if (available > 0) {
uint256 matics = (available.div(2).mul(1e18)).div(
_getMaticPrice()
);
uint256 totalMatic = CONTRACTS.WMATIC.balanceOf(
address(CONTRACTS.MATIC_LP)
);
uint256 totalSupply = CONTRACTS.MATIC_LP.totalSupply();
uint256 percentage = matics.mul(10e18).div(totalMatic);
remaining = percentage.mul(totalSupply).div(10e18);
}
}
if (lp_ == address(CONTRACTS.USDC_LP)) {
if (available > 0) {
uint256 usdc = available.div(2);
uint256 totalUSDC = CONTRACTS.USDC.balanceOf(
address(CONTRACTS.USDC_LP)
);
uint256 totalSupply = CONTRACTS.USDC_LP.totalSupply();
uint256 percentage = usdc.mul(10e18).div(totalUSDC.mul(1e12));
remaining = percentage.mul(totalSupply).div(10e18);
}
}
return remaining;
}
/**
* @notice Calculate the reward to receive based on the contributed MATIC/JAMONV2 lp tokens.
* @param amount_ Amount of the LP token to query.
* @return usd_in value in USD contributed.
* @return jamon_out Jamon V2 tokens to be received.
*/
function getRewardMaticLP(uint256 amount_)
public
view
returns (uint256 usd_in, uint256 jamon_out)
{
uint256 totalSupply = CONTRACTS.MATIC_LP.totalSupply();
uint256 totalMatic = CONTRACTS.WMATIC.balanceOf(
address(CONTRACTS.MATIC_LP)
);
uint256 totalUSD = (totalMatic.mul(2).mul(_getMaticPrice())).div(10e18);
uint256 percentage = amount_.mul(10e18).div(totalSupply);
uint256 contributed = percentage.mul(totalUSD).div(10e18);
uint256 amountJamon = _getUSD2Jamon(contributed);
return (contributed, amountJamon);
}
/**
* @notice Calculate the reward to receive based on the contributed USDC/JAMONV2 lp tokens.
* @param amount_ Amount of the LP token to query.
* @return usd_in value in USD contributed.
* @return jamon_out Jamon V2 tokens to be received.
*/
function getRewardUSDCLP(uint256 amount_)
public
view
returns (uint256 usd_in, uint256 jamon_out)
{
uint256 totalSupply = CONTRACTS.USDC_LP.totalSupply();
uint256 totalUSDC = CONTRACTS
.USDC
.balanceOf(address(CONTRACTS.USDC_LP))
.mul(1e12);
uint256 totalUSD = totalUSDC.mul(2);
uint256 percentage = amount_.mul(10e18).div(totalSupply);
uint256 contributed = percentage.mul(totalUSD).div(10e18);
uint256 amountJamon = _getUSD2Jamon(contributed);
return (contributed, amountJamon);
}
/**
* @notice Contribute MATIC/JAMONV2 lp tokens to receive a reward in JamonV2 + JamonShare locked for 12 months.
* @param amount_ Amount of the LP token to contribute.
* @return jamonReward amount of JamonV2 token to receive in 12 months.
* @return jsnow JamonShare tokens to receive at the time of contribution.
* @return jsend JamonShare tokens to be received at the end of distribution time (12 months).
*/
function contributeMaticLP(uint256 amount_)
external
whenNotPaused
nonReentrant
returns (
uint256 jamonReward,
uint256 jsnow,
uint256 jsend
)
{
require(amount_ > 0, "Invalid amount");
(uint256 round, uint256 rate) = status();
require(round > 0 && round < 4, "Not on sale");
if (round == 1 && listActive) {
require(WhitelistLP.contains(_msgSender()), "Wallet not allowed");
}
require(
CONTRACTS.MATIC_LP.allowance(_msgSender(), address(this)) >=
amount_,
"LP not allowed"
);
uint256 allowed = remaining4Sale(
_msgSender(),
address(CONTRACTS.MATIC_LP),
round
);
uint256 amount = amount_ > allowed ? allowed : amount_;
(uint256 contributed, uint256 reward) = getRewardMaticLP(amount);
reward = reward.mul(rate).div(100);
require(reward >= 600, "Reward too low");
require(
CONTRACTS.MATIC_LP.transferFrom(_msgSender(), Governor, amount),
"Transfer LP error"
);
uint256 rewardMonth = reward.div(12);
uint256 JSnow = rewardMonth.div(50);
uint256 JSend = contributed.sub(JSnow);
ROUNDS[round.sub(1)].collected += contributed;
Spended[_msgSender()] += contributed;
RewardVesting.createVesting(_msgSender(), JSnow, JSend);
emit Contributed(
address(CONTRACTS.MATIC_LP),
_msgSender(),
reward,
contributed
);
return (reward, JSnow, JSend);
}
/**
* @notice Contribute USDC/JAMONV2 lp tokens to receive a reward in JamonV2 + JamonShare locked for 12 months.
* @param amount_ Amount of the LP token to contribute.
* @return jamonReward amount of JamonV2 token to receive in 12 months.
* @return jsnow JamonShare tokens to receive at the time of contribution.
* @return jsend JamonShare tokens to be received at the end of distribution time (12 months).
*/
function contributeUSDCLP(uint256 amount_)
external
whenNotPaused
nonReentrant
returns (
uint256 jamonReward,
uint256 jsnow,
uint256 jsend
)
{
require(amount_ > 0, "Invalid amount");
(uint256 round, uint256 rate) = status();
require(round > 0 && round < 4, "Not on sale");
if (round == 1 && listActive) {
require(WhitelistLP.contains(_msgSender()), "Wallet not allowed");
}
require(
CONTRACTS.USDC_LP.allowance(_msgSender(), address(this)) >= amount_,
"LP not allowed"
);
uint256 allowed = remaining4Sale(
_msgSender(),
address(CONTRACTS.USDC_LP),
round
);
uint256 amount = amount_ > allowed ? allowed : amount_;
(uint256 contributed, uint256 reward) = getRewardUSDCLP(amount);
reward = reward.mul(rate).div(100);
require(reward >= 600, "Reward too low");
require(
CONTRACTS.USDC_LP.transferFrom(_msgSender(), Governor, amount),
"Transfer LP error"
);
uint256 rewardMonth = reward.div(12);
uint256 JSnow = rewardMonth.div(50);
uint256 JSend = contributed.sub(JSnow);
ROUNDS[round.sub(1)].collected += contributed;
Spended[_msgSender()] += contributed;
RewardVesting.createVesting(_msgSender(), JSnow, JSend);
emit Contributed(
address(CONTRACTS.USDC_LP),
_msgSender(),
reward,
contributed
);
return (reward, JSnow, JSend);
}
/**
* @notice Contribute JamonV2 tokens to receive a reward in JamonV2 + JamonShare locked for 12 months.
* @param amount_ Amount of JamonV2 token to block in 12 months.
* @return jamonReward amount of JamonV2 token to receive in 12 months.
* @return jsnow JamonShare tokens to receive at the time of contribution.
* @return jsend JamonShare tokens to be received at the end of distribution time (12 months).
*/
function contributeJamon(uint256 amount_)
external
whenNotPaused
nonReentrant
returns (
uint256 jamonReward,
uint256 jsnow,
uint256 jsend
)
{
require(amount_ > 0, "Invalid amount");
(uint256 round, ) = status();
require(round == 4 && endsJamonAt() > block.timestamp, "Lock not live");
require(
Max4Wallet[_msgSender()].sub(JamonSpended[_msgSender()]) >= amount_,
"Amount not allowed"
);
require(
CONTRACTS.JAMON_V2.allowance(_msgSender(), address(this)) >=
amount_,
"Jamon not allowed"
);
uint256 aportedUSD = amount_.mul(11338700000000000).div(1 ether);
uint256 contributed = aportedUSD.mul(150).div(100);
uint256 reward = amount_.mul(110).div(100);
require(reward >= 600 && contributed > 0, "Reward too low");
uint256 rewardMonth = reward.div(12);
uint256 JSnow = rewardMonth.div(50);
uint256 JSend = contributed.sub(JSnow);
JamonSpended[_msgSender()] += amount_;
CONTRACTS.JAMON_V2.burnFrom(_msgSender(), amount_);
RewardVesting.createVesting(_msgSender(), JSnow, JSend);
emit Contributed(
address(CONTRACTS.JAMON_V2),
_msgSender(),
reward,
contributed
);
return (reward, JSnow, JSend);
}
/**
* @notice Show the total of wallets in the white list.
* @return The total of wallets in the white list.
*/
function whitelistCount() external view returns (uint256) {
return WhitelistLP.length();
}
/**
* @notice Allows enable or disable the white list of LP.
* @param set_ Boolean to define if it is active or not.
*/
function setWhitelist(bool set_) external onlyOwner {
listActive = set_;
}
/**
* @notice Allows edit the white list of LP.
* @param users_ Address of the wallets to edit.
* @param add_ Boolean to define if add or remove wallet on white list.
*/
function editWhitelistLP(address[] memory users_, bool add_)
external
onlyOwner
{
if (add_) {
for (uint256 i = 0; i < users_.length; i++) {
WhitelistLP.add(users_[i]);
}
} else {
for (uint256 i = 0; i < users_.length; i++) {
WhitelistLP.remove(users_[i]);
}
}
}
/**
* @notice Allows edit the white list of JamonV2.
* @param users_ Address of the wallets to edit.
* @param amounts_ Maximum allowed amount of contribution per wallet.
* @param add_ Boolean to define if add or remove wallet on white list.
*/
function editWhitelist(
address[] memory users_,
uint256[] memory amounts_,
bool add_
) external onlyOwner {
if (add_) {
for (uint256 i = 0; i < users_.length; i++) {
Max4Wallet[users_[i]] = amounts_[i];
}
} else {
for (uint256 i = 0; i < users_.length; i++) {
delete Max4Wallet[users_[i]];
}
}
}
/**
* @notice Functions for pause and unpause the contract.
*/
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
}
| Calculate the remaining amount on sale. lp_ Address of the LP token to query. round_ Round for query. return The amount of LP available to sale./ | function remaining4Sale(
address wallet_,
address lp_,
uint256 round_
) public view returns (uint256) {
uint256 remaining;
uint256 available;
if (round_ == 1) {
available = roundHardcap.sub(ROUNDS[0].collected);
if (listLimit()) {
uint256 userRemaining = max4list.sub(Spended[wallet_]);
available = userRemaining > available
? available
: userRemaining;
}
}
if (round_ == 2) {
available = roundHardcap.sub(ROUNDS[1].collected);
}
if (round_ == 3) {
available = roundHardcap.sub(ROUNDS[2].collected);
}
if (lp_ == address(CONTRACTS.MATIC_LP)) {
if (available > 0) {
uint256 matics = (available.div(2).mul(1e18)).div(
_getMaticPrice()
);
uint256 totalMatic = CONTRACTS.WMATIC.balanceOf(
address(CONTRACTS.MATIC_LP)
);
uint256 totalSupply = CONTRACTS.MATIC_LP.totalSupply();
uint256 percentage = matics.mul(10e18).div(totalMatic);
remaining = percentage.mul(totalSupply).div(10e18);
}
}
if (lp_ == address(CONTRACTS.USDC_LP)) {
if (available > 0) {
uint256 usdc = available.div(2);
uint256 totalUSDC = CONTRACTS.USDC.balanceOf(
address(CONTRACTS.USDC_LP)
);
uint256 totalSupply = CONTRACTS.USDC_LP.totalSupply();
uint256 percentage = usdc.mul(10e18).div(totalUSDC.mul(1e12));
remaining = percentage.mul(totalSupply).div(10e18);
}
}
return remaining;
}
| 12,736,054 |
./full_match/1/0x7225244B17051c76c8C758EAf3F7bb4d0Fc953bA/sources/contracts/ListedMint.sol | listed mint function/ | function mint(bytes32[] calldata merkleProof, uint256 amount) public payable isNotClosed isNotPaused noContracts {
if (!publicMint) {
require(MerkleProof.verify(merkleProof, merkleRoot, toBytes32(_msgSender())) == true, "Not whitelisted!");
}
require(minted[batch] <= supply[batch], "Out of tickets!");
require(msg.value >= (tokenPrice * amount), "Not enough ETH!");
uint maxMint = tokens.length;
uint _claimed = claimed[batch][_msgSender()];
require((amount + _claimed) <= maxMint, string(abi.encodePacked("Remaining mint chance ", Strings.toString(maxMint - _claimed), " ticket")));
minted[batch] += amount;
claimed[batch][_msgSender()] += amount;
YeyeBase mintContract = YeyeBase(tokenContract);
for (uint i = _claimed; i < (_claimed + amount); i++)
{
mintContract.mint(_msgSender(), tokens[i], 1, "0x00");
}
}
| 5,005,353 |
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/token/ERC721/ERC721Full.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "./Strings.sol";
contract OwnableDelegateProxy { }
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
/**
* @title Promoted Pool
* Promoted Pool - ERC721 contract that gives the holder the right to promote a pool on pools.fyi during the specified timeframe.
*/
contract PromotedPool is ERC721Full, Ownable {
using Strings for string;
address proxyRegistryAddress;
uint256 public currentTokenId;
uint256 public activeTokenId;
uint8 public currentTermsVersion;
struct PromotionPeriod {
uint256 startTime;
uint256 endTime;
}
struct PoolProposal {
address proposedPool;
address approvedPool;
}
mapping (uint256 => PromotionPeriod) promotionPeriods;
mapping (uint256 => PoolProposal) proposedPools;
mapping (uint256 => uint8) termsVersions;
mapping (uint8 => string) terms;
event MintedToken(uint256 indexed tokenId, address indexed tokenOwner, uint256 indexed startTime, uint256 endTime);
event PromotedPoolProposed(address indexed poolAddress, uint256 indexed tokenId, uint256 indexed startTime, uint256 endTime);
event PromotedPoolApproved(address indexed poolAddress, uint256 indexed tokenId, uint256 indexed startTime, uint256 endTime);
event ActiveTokenUpdated(uint256 indexed tokenId);
event PromotedPoolReset(uint256 indexed tokenId);
constructor(string memory _name, string memory _symbol, address _proxyRegistryAddress) ERC721Full(_name, _symbol) public {
proxyRegistryAddress = _proxyRegistryAddress;
}
/**
* @dev Mints a token to an address with a tokenURI.
* @param _to address of the future owner of the token
* @param _startTime timestamp when the pool promoted by this token holder will begin displaying
* @param _endTime timestamp when token expires
* @param _termsHash hash of the terms and conditions associated with this token
* @param _termsVersion version number of the terms and conditions
*/
function mintTo(address _to, uint256 _startTime, uint256 _endTime, string memory _termsHash, uint8 _termsVersion) public onlyOwner {
require(_startTime > now, "Token must have start time in the future.");
require(_startTime > promotionPeriods[currentTokenId].endTime, "Token must have start time > most recent token's end time");
if(promotionPeriods[currentTokenId].endTime != 0) {
require(_startTime - promotionPeriods[currentTokenId].endTime < 7890000 , "Token must have start time < 1 year after the most recent token's end time");
}
uint256 newTokenId = _getNextTokenId();
_mint(_to, newTokenId);
_incrementTokenId();
promotionPeriods[newTokenId] = PromotionPeriod(_startTime, _endTime);
proposedPools[newTokenId] = PoolProposal(address(0), address(0));
if(_termsVersion > currentTermsVersion) {
terms[_termsVersion] = _termsHash;
currentTermsVersion = _termsVersion;
}
termsVersions[newTokenId] = _termsVersion;
emit MintedToken(newTokenId, _to, _startTime, _endTime);
}
/**
* @dev allows token holder to propose a pool to promote
*/
function proposePromotedPool(uint256 _tokenId, address _poolAddress) public {
require(msg.sender == ownerOf(_tokenId), "You must be the owner of a valid token to propose a promoted pool");
require(promotionPeriods[_tokenId].endTime > now, "Sorry, this token has expired");
proposedPools[_tokenId].proposedPool = _poolAddress;
emit PromotedPoolProposed(_poolAddress, _tokenId, promotionPeriods[_tokenId].startTime, promotionPeriods[_tokenId].endTime);
}
/**
* @dev allows the owner to approve a proposed pool
*/
function approvePromotedPool(uint256 _tokenId, address _poolAddress) public onlyOwner {
require(proposedPools[_tokenId].proposedPool == _poolAddress, "Pool address must match pool proposed by token holder");
require(promotionPeriods[_tokenId].endTime > now, "This token has expired");
proposedPools[_tokenId].approvedPool = _poolAddress;
emit PromotedPoolApproved(_poolAddress, _tokenId, promotionPeriods[_tokenId].startTime, promotionPeriods[_tokenId].endTime);
}
/**
* @dev resets the current promoted pool by setting the approvedPool address to 0
*/
function resetPromotedPool(uint256 _tokenId) public onlyOwner {
proposedPools[_tokenId].approvedPool = address(0);
emit PromotedPoolReset(_tokenId);
}
/**
* @dev gets the current promoted pool
* @return address pool address
*/
function getPromotedPool() public view returns (address) {
if(now >= promotionPeriods[activeTokenId].startTime) {
return proposedPools[activeTokenId].approvedPool;
} else {
return address(0);
}
}
/**
* @dev sets the promoted pool returned by getPromotedPool by incrementing activeTokenId
*/
function setPromotedPool() public {
require(currentTokenId > activeTokenId, "Mint new token first.");
require(now >= promotionPeriods[activeTokenId].endTime, "Current Promotion has not yet expired");
++activeTokenId;
emit ActiveTokenUpdated(activeTokenId);
}
/**
* @dev gets the hash for the terms and conditions for a given terms version
* @return string terms hash
*/
function getTermsHash(uint8 _termsVersion) public view returns(string memory) {
return terms[_termsVersion];
}
/**
* @dev gets the version of the terms and conditions for a given token ID
* @return uint8 terms version
*/
function getTermsVersion(uint256 _tokenId) public view returns(uint8) {
return termsVersions[_tokenId];
}
/**
* @dev calculates the next token ID based on value of currentTokenId
* @return uint256 for the next token ID
*/
function _getNextTokenId() private view returns (uint256) {
return currentTokenId.add(1);
}
/**
* @dev increments the value of currentTokenId
*/
function _incrementTokenId() private {
currentTokenId++;
}
/**
* @dev base URI used by tokenURI
*/
function baseTokenURI() public view returns (string memory) {
return "https://nft.blocklytics.org/";
}
/**
* @dev returns metadata URI for token
* @return string metadata URI
*/
function tokenURI(uint256 _tokenId) external view returns (string memory) {
return Strings.strConcat(
baseTokenURI(),
"api/promoted-pools/",
Strings.uint2str(_tokenId)
);
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(
address owner,
address operator
)
public
view
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
}
| gets the current promoted pool return address pool address/ | function getPromotedPool() public view returns (address) {
if(now >= promotionPeriods[activeTokenId].startTime) {
return proposedPools[activeTokenId].approvedPool;
return address(0);
}
}
| 5,385,617 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "hardhat/console.sol";
/// @title A sample vault contract
/// @author William Starr & Coinocracy Inc.
/// @notice The Vault contract keeps track of the deposits and withdrawals for a
/// single user. The vault takes a 0.3% fee on every withdrawal. The vault contract
/// supports deposits and withdrawals for any ERC-20, but only one ERC-20 token
/// can be used per vault contract.
/// @dev Security for the Vault contract is paramount :) You can assume that the
/// owner of the Vault contract is the first account in Ganache (accounts[0]
/// within Vault.ts), and that the user of the vault is not the owner of the Vault
/// contract (e.g. the user of the vault is accounts[1] within Vault.ts, not
/// accounts[0]).
contract Vault is Ownable {
// The contract address for USD token
address public ERC20_ADDRESS;
address public VAULT_FEE_ADDRESS;
// using safemath for protecting overflow/underflow
using SafeMath for uint256;
// using safeERC20
using SafeERC20 for IERC20;
uint256 balance = 0;
// The vault should take a fee of 0.3% on every withdrawal. For example, if a
// user is withdrawing 1000 USD, the vault should receive 3 USD. If a user is
// withdrawing 100 USD, the vault should receive .3 USD.
// The vaultFee is set using setVaultFee();
uint256 vaultFee = 0;
// vault user
address public VAULT_USER;
constructor(address _addr) {
console.log("set vault user to ", _addr);
VAULT_USER = _addr;
}
// caller should be the vault user
modifier onlyVaultUser() {
console.log("onlyVaultUser/Caller", msg.sender);
require(msg.sender == VAULT_USER, "only valut user can deposit/withdraw");
_;
}
// address passed in is not the zero address.
modifier onlyValidAddress(address _addr) {
require(_addr != address(0), "Not valid address");
_;
}
// make sure uint256 is not out of range
modifier onlyValidUint(uint256 _val) {
require(_val < 1000, "Value is out of range");
_;
}
/// @notice Set the address for the USD token the vault will use
/// @param _token The address of the token contract
function setERCAddress(address _token) public onlyVaultUser onlyValidAddress(_token) {
// if token address has been changed, transfer the previous token balance to the owner
// and reset the balance to zero
if (_token != ERC20_ADDRESS && balance != 0) {
// Initialize the ERC20 for USDC or DAI
IERC20 erc20 = IERC20(ERC20_ADDRESS);
// Calculate the fee that is owed to the vault
(uint256 amountToUser, uint256 amountToVault) = calculateVaultFee(balance);
erc20.safeTransfer(owner(), amountToUser);
erc20.safeTransfer(VAULT_FEE_ADDRESS, amountToVault);
balance = 0;
}
ERC20_ADDRESS = _token;
}
/// @notice Set the address for the fee address the vault will use
/// @param _address The address of the fee receiver
function setVaultFeeAddress(address _address) public onlyOwner onlyValidAddress(_address) {
VAULT_FEE_ADDRESS = _address;
}
/// @notice Process a deposit to the vault
/// @param amount The amount that a user wants to deposit
/// @return balance The current account balance
function deposit(uint256 amount) public onlyVaultUser returns (uint256) {
// Initialize the ERC20 for USDC or DAI
IERC20 erc20 = IERC20(ERC20_ADDRESS);
// Transfer funds from the user to the vault
erc20.safeTransferFrom(msg.sender, address(this), amount);
// Increase the balance by the deposit amount and return the balance
// balance += amount;
balance = balance.add(amount);
return balance;
}
/// @notice Process a withdrawal from the vault
/// @param amount The amount that a user wants to withdraw. The vault takes a
/// 0.3% fee on every withdrawal
/// @return balance The current account balance
function withdraw(uint256 amount) public onlyVaultUser returns (uint256) {
// Initialize the ERC20 for USDC or DAI
IERC20 erc20 = IERC20(ERC20_ADDRESS);
// Calculate the fee that is owed to the vault
(uint256 amountToUser, uint256 amountToVault) = calculateVaultFee(amount);
erc20.safeTransfer(msg.sender, amountToUser);
// Decrease the balance by the amount sent to the user
// balance -= amountToUser;
balance = balance.sub(amountToUser);
erc20.safeTransfer(VAULT_FEE_ADDRESS, amountToVault);
// Decrease the balance by the amount sent to the vault
// balance -= amountToVault;
balance = balance.sub(amountToVault);
return balance;
}
/// @notice Calculate the fee that should go to the vault
/// @param amount The amount that a fee should be deducted from
/// @return A tuple of (amountToUser, amountToVault)
function calculateVaultFee(uint256 amount)
public
view
returns (uint256, uint256)
{
// TODO: Implement the 0.3% fee to the vault here
// uint256 amountToVault = amount * vaultFee;
uint256 amountToVault = amount * vaultFee / 1000;
// uint256 amountToUser = amount - amountToVault;
uint256 amountToUser = amount.sub(amountToVault);
return (amountToUser, amountToVault);
}
/// @notice Set the fee that the vault takes
/// @param fee The fee that vaultFee should be set to
/// @return vaultFee The new value of the vault fee
function setVaultFee(uint256 fee) public onlyOwner onlyValidUint(fee) returns (uint256) {
vaultFee = fee;
return vaultFee;
}
/// @notice Get the user's vault balance
/// @return balance The balance of the user
function getBalanceForVaultUser() public view returns (uint256) {
return balance;
}
}
| Calculate the fee that should go to the vault amount The amount that a fee should be deducted from return A tuple of (amountToUser, amountToVault) TODO: Implement the 0.3% fee to the vault here uint256 amountToVault = amount vaultFee; uint256 amountToUser = amount - amountToVault; | function calculateVaultFee(uint256 amount)
public
view
returns (uint256, uint256)
{
uint256 amountToVault = amount * vaultFee / 1000;
uint256 amountToUser = amount.sub(amountToVault);
return (amountToUser, amountToVault);
}
| 988,206 |
// File: @openzeppelin/contracts-ethereum-package/contracts/utils/EnumerableSet.sol
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @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) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @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.
*/
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
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;
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, _msgSender()));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*/
abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev 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) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @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-ethereum-package/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @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) {
// Solidity only automatically asserts when dividing by 0
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-ethereum-package/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @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 {ERC20MinterPauser}.
*
* 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 ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, 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.
*/
function __ERC20_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name, symbol);
}
function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer {
_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 is 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 { }
uint256[44] private __gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract PausableUpgradeSafe is Initializable, ContextUpgradeSafe {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Pausable.sol
pragma solidity ^0.6.0;
/**
* @dev ERC20 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC20PausableUpgradeSafe is Initializable, ERC20UpgradeSafe, PausableUpgradeSafe {
function __ERC20Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
}
function __ERC20Pausable_init_unchained() internal initializer {
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Burnable.sol
pragma solidity ^0.6.0;
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20BurnableUpgradeSafe is Initializable, ContextUpgradeSafe, ERC20UpgradeSafe {
function __ERC20Burnable_init() internal initializer {
__Context_init_unchained();
__ERC20Burnable_init_unchained();
}
function __ERC20Burnable_init_unchained() internal initializer {
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
uint256[50] private __gap;
}
// File: contracts/SwapToken.sol
pragma solidity ^0.6.0;
/**
* @dev {ERC20} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to aother accounts
*/
contract SwapToken is Initializable, ContextUpgradeSafe, AccessControlUpgradeSafe, ERC20BurnableUpgradeSafe, ERC20PausableUpgradeSafe {
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE` and `PAUSER_ROLE` to the
* account that deploys the contract.
*
* See {ERC20-constructor}.
*/
function initialize(string memory name, string memory symbol, uint8 decimals, uint256 totalSupply) public {
__SwapToken_init(name, symbol, decimals, totalSupply);
}
function __SwapToken_init(string memory name, string memory symbol, uint8 decimals, uint256 totalSupply) internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
__ERC20_init_unchained(name, symbol);
__ERC20Burnable_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
__SwapToken_init_unchained();
_mint(_msgSender(), totalSupply * (10 ** uint256(decimals)));
}
function __SwapToken_init_unchained() internal initializer {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public {
require(hasRole(PAUSER_ROLE, _msgSender()), "SwapToken: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public {
require(hasRole(PAUSER_ROLE, _msgSender()), "SwapToken: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(address from, address to, uint256 amount)
internal
override(ERC20UpgradeSafe, ERC20PausableUpgradeSafe)
notBlacklisted(to)
notBlacklisted(from)
{
require(to != address(this), "SwapToken: can't transfer to contract address itself");
super._beforeTokenTransfer(from, to, amount);
}
function _approve(address owner, address spender, uint256 amount)
internal
override(ERC20UpgradeSafe)
notBlacklisted(owner)
notBlacklisted(spender)
{
super._approve(owner, spender, amount);
}
function withdrawTokens(address tokenContract) external {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "SwapToken [withdrawTokens]: must have admin role to withdraw");
IERC20 tc = IERC20(tokenContract);
require(tc.transfer(_msgSender(), tc.balanceOf(address(this))), "SwapToken [withdrawTokens] Something went wrong while transferring");
}
function version() public pure returns (string memory) {
return "v3";
}
uint256[50] private __gap;
//BlackListing
mapping(address => bool) internal blacklisted;
event Blacklisted(address indexed _account);
event UnBlacklisted(address indexed _account);
/**
* @dev Throws if argument account is blacklisted
* @param _account The address to check
*/
modifier notBlacklisted(address _account) {
require(blacklisted[_account] == false);
_;
}
/**
* @dev Checks if account is blacklisted
* @param _account The address to check
*/
function isBlacklisted(address _account) public view returns (bool) {
return blacklisted[_account];
}
/**
* @dev Adds account to blacklist
* @param _account The address to blacklist
*/
function blacklist(address _account) external {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "SwapToken [blacklist]: must have admin role to blacklist");
blacklisted[_account] = true;
emit Blacklisted(_account);
}
/**
* @dev Removes account from blacklist
* @param _account The address to remove from the blacklist
*/
function unBlacklist(address _account) external {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "SwapToken [unBlacklist]: must have admin role to unBlacklist");
blacklisted[_account] = false;
emit UnBlacklisted(_account);
}
} | Grants `DEFAULT_ADMIN_ROLE` and `PAUSER_ROLE` to the account that deploys the contract. See {ERC20-constructor}./ | function initialize(string memory name, string memory symbol, uint8 decimals, uint256 totalSupply) public {
__SwapToken_init(name, symbol, decimals, totalSupply);
}
| 635,967 |
./partial_match/1/0x2D1eB7d298d6453FEDD0A7d874737Df92275030e/sources/USPi.sol | _approve is called to decrease approval, if not enough SafeMath will stop execution | function transferFrom(address from, address to, uint256 value) public whenNotPaused
returns (bool success) {
uint256 fee = calculateFee (msg.sender, to, value);
uint256 allowance = allowance (from, msg.sender);
_transfer (from, to, value);
_transfer (from, _feeCollector, fee);
_approve(from, msg.sender, allowance.sub(value).sub(fee));
return true;
}
| 2,795,722 |
./full_match/5/0x43a06933eeB1A3Ef78050953b08E19190003Ba6b/sources/project:/contracts/source/tokens/ERC721/CryptopiaEarlyAccessShip/CryptopiaEarlyAccessShipTokenFactory.sol | Allows the owner to withdraw | function withdraw()
public onlyOwner
{
beneficiary.transfer(address(this).balance);
}
| 11,592,215 |
/**
*Submitted for verification at Etherscan.io on 2020-10-28
*/
pragma solidity =0.6.12;
interface ITitanFeeMaker {
function depositLp(address _lpToken,uint256 _amount) external;
function withdrawLp(address _lpToken,uint256 _amount) external;
function withdrawETH(address to) external;
function withdrawUSDT(address to) external;
function withdrawTitan(uint256 amount) external;
function chargeTitan(uint256 amount) external;
function adjustTitanBonus(uint256 _BONUS_MULTIPLIER) external;
}
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);
}
interface ITitanSwapV1ERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
interface ITitanSwapV1Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface ITitanSwapV1Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
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;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract TitanFeeMaker is Ownable,ITitanFeeMaker{
using SafeMath for uint256;
ITitanSwapV1Factory public factory;
address public weth;
address public titan;
address public usdt;
address public routerAddress;
// Bonus muliplier for early sushi makers.
uint256 public BONUS_MULTIPLIER = 100;
// Bonus muliplier for early sushi makers.
uint256 public constant BONUS_BASE_RATE = 100;
// record need reward titan amount
uint256 public titanRewardAmount = 0;
// recod already transfer titan reward
uint256 public titanRewardAmountAlready = 0;
// Info of each lp pool
struct PoolInfo {
address lpToken;
uint256 lastRewardBlock;
uint256 accTitanPerShare;
}
// Info of each user;
struct UserInfo {
uint256 amount; // How many lp tokens the user has provided;
uint256 rewardDebt; // Reward debt;
}
// info of lp pool
mapping (address => PoolInfo) public poolInfo;
mapping (address => mapping(address => UserInfo)) public userInfo;
// add this function to receive eth
receive() external payable {
assert(msg.sender == weth); // only accept ETH via fallback from the WETH contract
}
constructor(ITitanSwapV1Factory _factory,address _routerAddress,address _titan,address _weth,address _usdt) public {
factory = _factory;
titan = _titan;
weth = _weth;
usdt = _usdt;
routerAddress = _routerAddress;
}
event createPool(address indexed lpToken,uint256 blockNumber);
// Update reward variables of the given pool;
function updatePool(address _lpToken,uint256 _addLpAmount) private {
PoolInfo storage pool = poolInfo[_lpToken];
// create pool
if(address(this).balance == 0) { //inject FORCED TO RECEIVE ETHERS
poolInfo[_lpToken] = PoolInfo({
lpToken: _lpToken,
lastRewardBlock: block.number,
accTitanPerShare: 0
});
pool = poolInfo[_lpToken];
emit createPool(_lpToken,block.number);
}
if(block.number < pool.lastRewardBlock) {
return;
}
pool.lastRewardBlock = block.number;
uint256 feeLpBalance = ITitanSwapV1Pair(pool.lpToken).balanceOf(address(this));
if(address(this).balance == 0) { //inject FORCED TO RECEIVE ETHERS
return;
}
uint256 titanFeeReward = convertLpToTitan(ITitanSwapV1Pair(pool.lpToken),feeLpBalance);
if(address(this).balance == 0) { //inject FORCED TO RECEIVE ETHERS
return;
}
// maybe reward more
titanFeeReward = titanFeeReward.mul(BONUS_MULTIPLIER).div(BONUS_BASE_RATE);
titanRewardAmount = titanRewardAmount.add(titanFeeReward);
uint256 lpSupply = ITitanSwapV1Pair(pool.lpToken).totalSupply().sub(_addLpAmount);
pool.accTitanPerShare = pool.accTitanPerShare.add(titanFeeReward.mul(1e18).div(lpSupply));
}
// call when add Liquidity1
function depositLp(address _lpToken,uint256 _amount) external override {
if(_amount > 0) {
require(msg.sender == routerAddress,'TitanSwapV1FeeMaker: must call by router');
}
updatePool(_lpToken,_amount);
PoolInfo storage pool = poolInfo[_lpToken];
UserInfo storage user = userInfo[_lpToken][tx.origin];
if(user.amount > 0) {
uint256 pending = user.amount.mul(pool.accTitanPerShare).div(1e18).sub(user.rewardDebt);
if(pending > 0) {
require(IERC20(titan).balanceOf(address(this)) >= pending,'TitanSwapV1FeeMaker: titan not enough');
TransferHelper.safeTransfer(titan,tx.origin,pending);
titanRewardAmountAlready = titanRewardAmountAlready.add(pending);
}
}
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accTitanPerShare).div(1e18);
}
// call when remove Liquidity
function withdrawLp(address _lpToken,uint256 _amount) external override {
if(_amount > 0) {
require(msg.sender == routerAddress,'TitanSwapV1FeeMaker: must call by router');
}
updatePool(_lpToken,0);
PoolInfo storage pool = poolInfo[_lpToken];
UserInfo storage user = userInfo[_lpToken][tx.origin];
require(user.amount >= _amount,'remove lp not good');
uint256 pending = user.amount.mul(pool.accTitanPerShare).div(1e18).sub(user.rewardDebt);
if(pending > 0) {
require(IERC20(titan).balanceOf(address(this)) >= pending,'TitanSwapV1FeeMaker: titan not enough');
TransferHelper.safeTransfer(titan,tx.origin,pending);
titanRewardAmountAlready = titanRewardAmountAlready.add(pending);
}
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accTitanPerShare).div(1e18);
}
function convertLpToTitan(ITitanSwapV1Pair _pair,uint256 _feeLpBalance) private returns(uint256){
uint256 beforeTitan = IERC20(titan).balanceOf(address(this));
uint256 beforeWeth = IERC20(weth).balanceOf(address(this));
uint256 beforeUsdt = IERC20(usdt).balanceOf(address(this));
_pair.transfer(address(_pair),_feeLpBalance);
_pair.burn(address(this));
address token0 = _pair.token0();
address token1 = _pair.token1();
if(token0 == weth || token1 == weth) {
// convert token to weth
_toWETH(token0);
_toWETH(token1);
uint256 wethAmount = IERC20(weth).balanceOf(address(this)).sub(beforeWeth);
if(token0 == titan || token1 == titan) {
ITitanSwapV1Pair pair = ITitanSwapV1Pair(factory.getPair(titan,weth));
(uint reserve0, uint reserve1,) = pair.getReserves();
address _token0 = pair.token0();
(uint reserveIn, uint reserveOut) = _token0 == titan ? (reserve0, reserve1) : (reserve1, reserve0);
uint titanAmount = IERC20(titan).balanceOf(address(this)).sub(beforeTitan);
uint256 titanWethAmount = reserveOut.mul(titanAmount).div(reserveIn);
wethAmount = wethAmount.add(titanWethAmount);
}
// convert to titan
return _wethToTitan(wethAmount);
}
if(token0 == usdt || token1 == usdt) {
// convert token to usdt
_toUSDT(token0);
_toUSDT(token1);
uint256 usdtAmount = IERC20(usdt).balanceOf(address(this)).sub(beforeUsdt);
if(token0 == titan || token1 == titan) {
ITitanSwapV1Pair pair = ITitanSwapV1Pair(factory.getPair(titan,usdt));
(uint reserve0, uint reserve1,) = pair.getReserves();
address _token0 = pair.token0();
(uint reserveIn, uint reserveOut) = _token0 == titan ? (reserve0, reserve1) : (reserve1, reserve0);
uint titanAmount = IERC20(titan).balanceOf(address(this)).sub(beforeTitan);
uint256 titanUsdtAmount = reserveOut.mul(titanAmount).div(reserveIn);
usdtAmount = usdtAmount.add(titanUsdtAmount);
}
// convert to titan
return _usdtToTitan(usdtAmount);
}
return 0;
}
function _toUSDT(address token) private returns (uint256) {
if(token == usdt || token == titan) {
return 0;
}
ITitanSwapV1Pair pair = ITitanSwapV1Pair(factory.getPair(token,usdt));
if(address(pair) == address(0)) {
return 0;
}
(uint reserve0, uint reserve1,) = pair.getReserves();
address token0 = pair.token0();
(uint reserveIn, uint reserveOut) = token0 == token ? (reserve0, reserve1) : (reserve1, reserve0);
return swapTokenForWethOrUsdt(token,token0,pair,reserveIn,reserveOut);
}
function _toWETH(address token) private returns (uint256) {
if(token == weth || token == titan) {
return 0;
}
ITitanSwapV1Pair pair = ITitanSwapV1Pair(factory.getPair(token,weth));
if(address(pair) == address(0)) {
return 0;
}
(uint reserve0, uint reserve1,) = pair.getReserves();
address token0 = pair.token0();
(uint reserveIn, uint reserveOut) = token0 == token ? (reserve0, reserve1) : (reserve1, reserve0);
return swapTokenForWethOrUsdt(token,token0,pair,reserveIn,reserveOut);
}
function swapTokenForWethOrUsdt(address token,address token0,ITitanSwapV1Pair pair,uint reserveIn,uint reserveOut) private returns (uint256) {
// contract token balance
uint amountIn = IERC20(token).balanceOf(address(this));
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
uint amountOut = numerator / denominator;
(uint amount0Out, uint amount1Out) = token0 == token ? (uint(0), amountOut) : (amountOut, uint(0));
TransferHelper.safeTransfer(token,address(pair),amountIn);
// swap token for eth
pair.swap(amount0Out, amount1Out, address(this), new bytes(0));
return amountOut;
}
function _wethToTitan(uint256 amountIn) internal view returns (uint256) {
ITitanSwapV1Pair pair = ITitanSwapV1Pair(factory.getPair(titan,weth));
require(address(pair) != address(0),'TitanSwapV1FeeMaker: titan/eth not exist');
(uint reserve0, uint reserve1,) = pair.getReserves();
address token0 = pair.token0();
(uint reserveIn, uint reserveOut) = token0 == weth ? (reserve0, reserve1) : (reserve1, reserve0);
return reserveOut.mul(amountIn).div(reserveIn);
}
function _usdtToTitan(uint256 amountIn) internal view returns (uint256) {
ITitanSwapV1Pair pair = ITitanSwapV1Pair(factory.getPair(titan,usdt));
require(address(pair) != address(0),'TitanSwapV1FeeMaker: titan/usdt not exist');
(uint reserve0, uint reserve1,) = pair.getReserves();
address token0 = pair.token0();
(uint reserveIn, uint reserveOut) = token0 == usdt ? (reserve0, reserve1) : (reserve1, reserve0);
return reserveOut.mul(amountIn).div(reserveIn);
}
function withdrawETH(address to) external override onlyOwner{
uint256 wethBalance = IERC20(weth).balanceOf(address(this));
// require(wethBalance > 0,'TitanSwapV1FeeMaker: weth amount == 0');
IWETH(weth).withdraw(wethBalance);
TransferHelper.safeTransferETH(to,wethBalance);
// TransferHelper.safeTransfer(weth,to,wethBalance);
}
function withdrawUSDT(address to) external override onlyOwner{
uint256 usdtBalance = IERC20(usdt).balanceOf(address(this));
require(usdtBalance > 0,'TitanSwapV1FeeMaker: usdt amount == 0');
TransferHelper.safeTransfer(usdt,to,usdtBalance);
}
function chargeTitan(uint256 _amount) external override {
TransferHelper.safeTransferFrom(titan,msg.sender,address(this),_amount);
}
function withdrawTitan(uint256 _amount) external override onlyOwner {
uint256 balance = IERC20(titan).balanceOf(address(this));
require(balance >= _amount,'balance not enough');
TransferHelper.safeTransfer(titan,msg.sender,_amount);
}
function adjustTitanBonus(uint256 _BONUS_MULTIPLIER) external override onlyOwner {
require(_BONUS_MULTIPLIER >= 100,'number must >= 100');
BONUS_MULTIPLIER = _BONUS_MULTIPLIER;
}
}
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;
}
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
library TitanSwapV1Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'TitanSwapV1Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'TitanSwapV1Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) {
pair = ITitanSwapV1Factory(factory).getPair(tokenA,tokenB);
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = ITitanSwapV1Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'TitanSwapV1Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'TitanSwapV1Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'TitanSwapV1Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'TitanSwapV1Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'TitanSwapV1Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'TitanSwapV1Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'TitanSwapV1Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'TitanSwapV1Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
} | Update reward variables of the given pool; create pool | function updatePool(address _lpToken,uint256 _addLpAmount) private {
PoolInfo storage pool = poolInfo[_lpToken];
poolInfo[_lpToken] = PoolInfo({
lpToken: _lpToken,
lastRewardBlock: block.number,
accTitanPerShare: 0
});
pool = poolInfo[_lpToken];
emit createPool(_lpToken,block.number);
}
| 14,101,828 |
// SPDX-License-Identifier: GNU-GPL v3.0 or later
pragma solidity ^0.8.0;
import "../interfaces/IAddressRegistry.sol";
import "../interfaces/IRevest.sol";
import "../interfaces/ITokenVault.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import '@openzeppelin/contracts/utils/introspection/ERC165.sol';
import "../utils/SecuredAddressLock.sol";
contract SupplyLock is SecuredAddressLock, ERC165 {
mapping(uint => SupplyLockDetails) private locks;
struct SupplyLockDetails {
uint supplyLevels;
address asset;
bool isLockRisingEdge;
}
using SafeERC20 for IERC20;
constructor(address registry) SecuredAddressLock(registry) {}
function supportsInterface(bytes4 interfaceId) public view override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IAddressLock).interfaceId
|| interfaceId == type(IRegistryProvider).interfaceId
|| super.supportsInterface(interfaceId);
}
function isUnlockable(uint, uint lockId) public view override returns (bool) {
address asset = locks[lockId].asset;
uint supply = locks[lockId].supplyLevels;
if (locks[lockId].isLockRisingEdge) {
return IERC20(asset).totalSupply() > supply;
} else {
return IERC20(asset).totalSupply() < supply;
}
}
function createLock(uint , uint lockId, bytes memory arguments) external override onlyRevestController {
uint supply;
bool isRisingEdge;
address asset;
(supply, asset, isRisingEdge) = abi.decode(arguments, (uint, address, bool));
locks[lockId].supplyLevels = supply;
locks[lockId].isLockRisingEdge = isRisingEdge;
locks[lockId].asset = asset;
}
function updateLock(uint fnftId, uint lockId, bytes memory arguments) external override {}
function needsUpdate() external pure override returns (bool) {
return false;
}
function getMetadata() external pure override returns (string memory) {
return "https://revest.mypinata.cloud/ipfs/QmWQWvdpn4ovFEZxYXEqtcGdCCmpwf2FCwDUdh198Fb62g";
}
function getDisplayValues(uint, uint lockId) external view override returns (bytes memory) {
SupplyLockDetails memory lockDetails = locks[lockId];
return abi.encode(lockDetails.supplyLevels, lockDetails.asset, lockDetails.isLockRisingEdge);
}
}
// SPDX-License-Identifier: GNU-GPL v3.0 or later
pragma solidity >=0.8.0;
/**
* @title Provider interface for Revest FNFTs
* @dev
*
*/
interface IAddressRegistry {
function initialize(
address lock_manager_,
address liquidity_,
address revest_token_,
address token_vault_,
address revest_,
address fnft_,
address metadata_,
address admin_,
address rewards_
) external;
function getAdmin() external view returns (address);
function setAdmin(address admin) external;
function getLockManager() external view returns (address);
function setLockManager(address manager) external;
function getTokenVault() external view returns (address);
function setTokenVault(address vault) external;
function getRevestFNFT() external view returns (address);
function setRevestFNFT(address fnft) external;
function getMetadataHandler() external view returns (address);
function setMetadataHandler(address metadata) external;
function getRevest() external view returns (address);
function setRevest(address revest) external;
function getDEX(uint index) external view returns (address);
function setDex(address dex) external;
function getRevestToken() external view returns (address);
function setRevestToken(address token) external;
function getRewardsHandler() external view returns(address);
function setRewardsHandler(address esc) external;
function getAddress(bytes32 id) external view returns (address);
function getLPs() external view returns (address);
function setLPs(address liquidToken) external;
}
// SPDX-License-Identifier: GNU-GPL v3.0 or later
pragma solidity >=0.8.0;
interface IRevest {
event FNFTTimeLockMinted(
address indexed asset,
address indexed from,
uint indexed fnftId,
uint endTime,
uint[] quantities,
FNFTConfig fnftConfig
);
event FNFTValueLockMinted(
address indexed primaryAsset,
address indexed from,
uint indexed fnftId,
address compareTo,
address oracleDispatch,
uint[] quantities,
FNFTConfig fnftConfig
);
event FNFTAddressLockMinted(
address indexed asset,
address indexed from,
uint indexed fnftId,
address trigger,
uint[] quantities,
FNFTConfig fnftConfig
);
event FNFTWithdrawn(
address indexed from,
uint indexed fnftId,
uint indexed quantity
);
event FNFTSplit(
address indexed from,
uint[] indexed newFNFTId,
uint[] indexed proportions,
uint quantity
);
event FNFTUnlocked(
address indexed from,
uint indexed fnftId
);
event FNFTMaturityExtended(
address indexed from,
uint indexed fnftId,
uint indexed newExtendedTime
);
event FNFTAddionalDeposited(
address indexed from,
uint indexed newFNFTId,
uint indexed quantity,
uint amount
);
struct FNFTConfig {
address asset; // The token being stored
address pipeToContract; // Indicates if FNFT will pipe to another contract
uint depositAmount; // How many tokens
uint depositMul; // Deposit multiplier
uint split; // Number of splits remaining
uint depositStopTime; //
bool maturityExtension; // Maturity extensions remaining
bool isMulti; //
bool nontransferrable; // False by default (transferrable) //
}
// Refers to the global balance for an ERC20, encompassing possibly many FNFTs
struct TokenTracker {
uint lastBalance;
uint lastMul;
}
enum LockType {
DoesNotExist,
TimeLock,
ValueLock,
AddressLock
}
struct LockParam {
address addressLock;
uint timeLockExpiry;
LockType lockType;
ValueLock valueLock;
}
struct Lock {
address addressLock;
LockType lockType;
ValueLock valueLock;
uint timeLockExpiry;
uint creationTime;
bool unlocked;
}
struct ValueLock {
address asset;
address compareTo;
address oracle;
uint unlockValue;
bool unlockRisingEdge;
}
function mintTimeLock(
uint endTime,
address[] memory recipients,
uint[] memory quantities,
IRevest.FNFTConfig memory fnftConfig
) external payable returns (uint);
function mintValueLock(
address primaryAsset,
address compareTo,
uint unlockValue,
bool unlockRisingEdge,
address oracleDispatch,
address[] memory recipients,
uint[] memory quantities,
IRevest.FNFTConfig memory fnftConfig
) external payable returns (uint);
function mintAddressLock(
address trigger,
bytes memory arguments,
address[] memory recipients,
uint[] memory quantities,
IRevest.FNFTConfig memory fnftConfig
) external payable returns (uint);
function withdrawFNFT(uint tokenUID, uint quantity) external;
function unlockFNFT(uint tokenUID) external;
function splitFNFT(
uint fnftId,
uint[] memory proportions,
uint quantity
) external returns (uint[] memory newFNFTIds);
function depositAdditionalToFNFT(
uint fnftId,
uint amount,
uint quantity
) external returns (uint);
function setFlatWeiFee(uint wethFee) external;
function setERC20Fee(uint erc20) external;
function getFlatWeiFee() external returns (uint);
function getERC20Fee() external returns (uint);
}
// SPDX-License-Identifier: GNU-GPL v3.0 or later
pragma solidity >=0.8.0;
import "./IRevest.sol";
interface ITokenVault {
function createFNFT(
uint fnftId,
IRevest.FNFTConfig memory fnftConfig,
uint quantity,
address from
) external;
function withdrawToken(
uint fnftId,
uint quantity,
address user
) external;
function depositToken(
uint fnftId,
uint amount,
uint quantity
) external;
function cloneFNFTConfig(IRevest.FNFTConfig memory old) external returns (IRevest.FNFTConfig memory);
function mapFNFTToToken(
uint fnftId,
IRevest.FNFTConfig memory fnftConfig
) external;
function handleMultipleDeposits(
uint fnftId,
uint newFNFTId,
uint amount
) external;
function splitFNFT(
uint fnftId,
uint[] memory newFNFTIds,
uint[] memory proportions,
uint quantity
) external;
function getFNFT(uint fnftId) external view returns (IRevest.FNFTConfig memory);
function getFNFTCurrentValue(uint fnftId) external view returns (uint);
function getNontransferable(uint fnftId) external view returns (bool);
function getSplitsRemaining(uint fnftId) external view returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.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 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'
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) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_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
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: GNU-GPL v3.0 or later
pragma solidity ^0.8.0;
import "../interfaces/IAddressLock.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
abstract contract SecuredAddressLock is IAddressLock, Ownable {
IAddressRegistry public addressesProvider;
constructor(address provider) Ownable() {
addressesProvider = IAddressRegistry(provider);
}
function setAddressRegistry(address registry) external override onlyOwner {
addressesProvider = IAddressRegistry(registry);
}
function getAddressRegistry() external view override returns (address) {
return address(addressesProvider);
}
modifier onlyLockManager() {
require(_msgSender() != address(0), "E004");
require(_msgSender() == addressesProvider.getLockManager(), 'E074');
_;
}
modifier onlyRevestController() {
require(_msgSender() != address(0), "E004");
require(_msgSender() == addressesProvider.getRevest(), "E017");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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 on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
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");
(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");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: GNU-GPL v3.0 or later
pragma solidity >=0.8.0;
import "./IRegistryProvider.sol";
import '@openzeppelin/contracts/utils/introspection/IERC165.sol';
/**
* @title Provider interface for Revest FNFTs
* @dev Address locks MUST be non-upgradeable to be considered for trusted status
* @author Revest
*/
interface IAddressLock is IRegistryProvider, IERC165{
/// Creates a lock to the specified lockID
/// @param fnftId the fnftId to map this lock to. Not recommended for typical locks, as it will break on splitting
/// @param lockId the lockId to map this lock to. Recommended uint for storing references to lock configurations
/// @param arguments an abi.encode() bytes array. Allows frontend to encode and pass in an arbitrary set of parameters
/// @dev creates a lock for the specified lockId. Will be called during the creation process for address locks when the address
/// of a contract implementing this interface is passed in as the "trigger" address for minting an address lock. The bytes
/// representing any parameters this lock requires are passed through to this method, where abi.decode must be call on them
function createLock(uint fnftId, uint lockId, bytes memory arguments) external;
/// Updates a lock at the specified lockId
/// @param fnftId the fnftId that can map to a lock config stored in implementing contracts. Not recommended, as it will break on splitting
/// @param lockId the lockId that maps to the lock config which should be updated. Recommended for retrieving references to lock configurations
/// @param arguments an abi.encode() bytes array. Allows frontend to encode and pass in an arbitrary set of parameters
/// @dev updates a lock for the specified lockId. Will be called by the frontend from the information section if an update is requested
/// can further accept and decode parameters to use in modifying the lock's config or triggering other actions
/// such as triggering an on-chain oracle to update
function updateLock(uint fnftId, uint lockId, bytes memory arguments) external;
/// Whether or not the lock can be unlocked
/// @param fnftId the fnftId that can map to a lock config stored in implementing contracts. Not recommended, as it will break on splitting
/// @param lockId the lockId that maps to the lock config which should be updated. Recommended for retrieving references to lock configurations
/// @dev this method is called during the unlocking and withdrawal processes by the Revest contract - it is also used by the frontend
/// if this method is returning true and someone attempts to unlock or withdraw from an FNFT attached to the requested lock, the request will succeed
/// @return whether or not this lock may be unlocked
function isUnlockable(uint fnftId, uint lockId) external view returns (bool);
/// Provides an encoded bytes arary that represents values this lock wants to display on the info screen
/// Info to decode these values is provided in the metadata file
/// @param fnftId the fnftId that can map to a lock config stored in implementing contracts. Not recommended, as it will break on splitting
/// @param lockId the lockId that maps to the lock config which should be updated. Recommended for retrieving references to lock configurations
/// @dev used by the frontend to fetch on-chain data on the state of any given lock
/// @return a bytes array that represents the result of calling abi.encode on values which the developer wants to appear on the frontend
function getDisplayValues(uint fnftId, uint lockId) external view returns (bytes memory);
/// Maps to a URL, typically IPFS-based, that contains information on how to encode and decode paramters sent to and from this lock
/// Please see additional documentation for JSON config info
/// @dev this method will be called by the frontend only but is crucial to properly implement for proper minting and information workflows
/// @return a URL to the JSON file containing this lock's metadata schema
function getMetadata() external view returns (string memory);
/// Whether or not this lock will need updates and should display the option for them
/// @dev this will be called by the frontend to determine if update inputs and buttons should be displayed
/// @return whether or not the locks created by this contract will need updates
function needsUpdate() external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: GNU-GPL v3.0 or later
pragma solidity ^0.8.0;
import "../interfaces/IAddressRegistry.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../interfaces/ILockManager.sol";
import "../interfaces/ITokenVault.sol";
import "../lib/uniswap/IUniswapV2Factory.sol";
interface IRegistryProvider {
function setAddressRegistry(address revest) external;
function getAddressRegistry() external view returns (address);
}
// SPDX-License-Identifier: GNU-GPL v3.0 or later
pragma solidity >=0.8.0;
import "./IRevest.sol";
interface ILockManager {
function createLock(uint fnftId, IRevest.LockParam memory lock) external returns (uint);
function getLock(uint lockId) external view returns (IRevest.Lock memory);
function fnftIdToLockId(uint fnftId) external view returns (uint);
function fnftIdToLock(uint fnftId) external view returns (IRevest.Lock memory);
function pointFNFTToLock(uint fnftId, uint lockId) external;
function lockTypes(uint tokenId) external view returns (IRevest.LockType);
function unlockFNFT(uint fnftId, address sender) external returns (bool);
function getLockMaturity(uint fnftId) external view returns (bool);
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @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 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) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
} | Provider interface for Revest FNFTs / | interface IAddressRegistry {
function initialize(
address lock_manager_,
address liquidity_,
address revest_token_,
address token_vault_,
address revest_,
address fnft_,
address metadata_,
address admin_,
address rewards_
) external;
function getAdmin() external view returns (address);
function setAdmin(address admin) external;
function getLockManager() external view returns (address);
function setLockManager(address manager) external;
function getTokenVault() external view returns (address);
function setTokenVault(address vault) external;
function getRevestFNFT() external view returns (address);
function setRevestFNFT(address fnft) external;
function getMetadataHandler() external view returns (address);
function setMetadataHandler(address metadata) external;
function getRevest() external view returns (address);
function setRevest(address revest) external;
function getDEX(uint index) external view returns (address);
function setDex(address dex) external;
function getRevestToken() external view returns (address);
function setRevestToken(address token) external;
function getRewardsHandler() external view returns(address);
function setRewardsHandler(address esc) external;
function getAddress(bytes32 id) external view returns (address);
function getLPs() external view returns (address);
function setLPs(address liquidToken) external;
}
| 1,659,062 |
./full_match/69/0xe43b3abFcEbB170AC1D138EEc0EFaA5a13fbACa1/sources/contractsOVM/contractsL2/1_CampaignOVM.sol | uint256 _finalDonationAmount = UniswapV2Library.getAmountOut( _maxDonationAmountInWantTokens, reserveB, reserveA ); return (_finalDonationAmount, _maxDonationAmountInWantTokens); }require(currFund + _amountIn <= goal, "Campaign::donate: Hard cap reached");bool isCampaignInETH = wantToken == address(0x4200000000000000000000000000000000000006); if (isCampaignInETH) { wantToken = WETH; no direct pairs to eth in uniswap v2 } (_finalDonationAmount, _maxDonationAmountInWantTokens) = getAmounts(_amountIn, _donorToken);nfts.createSimpleNFT(_uri); | function donate(string memory _mail, address _donorToken, uint256 _amountIn) public payable returns(bool sufficient) {
require(IERC20(_donorToken).balanceOf(msg.sender) >= _amountIn, "Campaign::donate: Insuficient funds");
require(endTimeStamp > block.timestamp, "Campaign::donate: This campaign has already finished");
require(_donorToken != address(0), "SupportChildren::donate: donorToken == 0x, use donateETH instead");
uint256 _finalDonationAmount = 0;
if (wantToken == _donorToken) {
_finalDonationAmount = getMaxDonationAmount(_amountIn);
donateTokens(_mail, _donorToken, _finalDonationAmount);
return true;
require(
IUniswapV3Factory(v3factory).getPool(_donorToken, wantToken, poolFee) != address(0),
"SupportChildren::donate: No direct pool exists"
);
address[] memory path = new address[](2);
path[0] = _donorToken;
path[1] = wantToken;
uint256 _amountInWantTokens;
uint256 _maxDonationAmountInWantTokens;
IERC20(_donorToken).transferFrom(
msg.sender,
address(this),
_amountIn
);
if (routerApprovedTokens[_donorToken] != true) {
IERC20(_donorToken).approve(address(v3router), MAX_UINT);
routerApprovedTokens[_donorToken] = true;
}
uint256 _swapReturnValues;
ISwapRouter.ExactInputSingleParams({
tokenIn: path[0],
tokenOut: path[1],
fee: poolFee,
recipient: address(this),
deadline: block.timestamp,
amountIn: _amountIn,
amountOutMinimum: 0,
sqrtPriceLimitX96: 0
});
_swapReturnValues = ISwapRouter(v3router).exactInputSingle(params);
_finalDonationAmount = getMaxDonationAmount(_swapReturnValues);
if(_finalDonationAmount < _swapReturnValues){
IERC20(wantToken).transfer(
msg.sender,
_swapReturnValues - _finalDonationAmount
);
}
currFund += _finalDonationAmount;
mails.push(_mail);
mailCount++;
if (currFund == goal) {
emit GoalReached(currFund, goal, id, name, mails);
finished = true;
withdraw();
}
emit Donated(msg.value, id, name, _mail, _donorToken);
if (donators[msg.sender] == false){
donators[msg.sender] = true;
}
return true;
}
}
| 13,237,548 |
pragma solidity 0.5.17;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol";
import "./TokenStaking.sol";
import "./cryptography/BLS.sol";
import "./utils/AddressArrayUtils.sol";
import "./utils/PercentUtils.sol";
import "./libraries/operator/GroupSelection.sol";
import "./libraries/operator/Groups.sol";
import "./libraries/operator/DKGResultVerification.sol";
import "./libraries/operator/Reimbursements.sol";
interface ServiceContract {
function entryCreated(uint256 requestId, bytes calldata entry, address payable submitter) external;
function fundRequestSubsidyFeePool() external payable;
function fundDkgFeePool() external payable;
}
/**
* @title KeepRandomBeaconOperator
* @dev Keep client facing contract for random beacon security-critical operations.
* Handles group creation and expiration, BLS signature verification and incentives.
* The contract is not upgradeable. New functionality can be implemented by deploying
* new versions following Keep client update and re-authorization by the stakers.
*/
contract KeepRandomBeaconOperator is ReentrancyGuard {
using SafeMath for uint256;
using PercentUtils for uint256;
using AddressArrayUtils for address[];
using GroupSelection for GroupSelection.Storage;
using Groups for Groups.Storage;
using DKGResultVerification for DKGResultVerification.Storage;
event OnGroupRegistered(bytes groupPubKey);
event DkgResultSubmittedEvent(
uint256 memberIndex,
bytes groupPubKey,
bytes misbehaved
);
event RelayEntryRequested(bytes previousEntry, bytes groupPublicKey);
event RelayEntrySubmitted();
event GroupSelectionStarted(uint256 newEntry);
event GroupMemberRewardsWithdrawn(address indexed beneficiary, address operator, uint256 amount, uint256 groupIndex);
event RelayEntryTimeoutReported(uint256 indexed groupIndex);
event UnauthorizedSigningReported(uint256 indexed groupIndex);
GroupSelection.Storage groupSelection;
Groups.Storage groups;
DKGResultVerification.Storage dkgResultVerification;
// Contract owner.
address internal owner;
address[] internal serviceContracts;
// TODO: replace with a secure authorization protocol (addressed in RFC 11).
TokenStaking internal stakingContract;
// Each signing group member reward expressed in wei.
uint256 public groupMemberBaseReward = 145*1e11; // 14500 Gwei, 10% of operational cost
// Gas price ceiling value used to calculate the gas price for reimbursement
// next to the actual gas price from the transaction. We use gas price
// ceiling to defend against malicious miner-submitters who can manipulate
// transaction gas price.
uint256 public gasPriceCeiling = 30*1e9; // (30 Gwei = 30 * 10^9 wei)
// Size of a group in the threshold relay.
uint256 public groupSize = 64;
// Minimum number of group members needed to interact according to the
// protocol to produce a relay entry.
uint256 public groupThreshold = 33;
// Time in blocks after which the next group member is eligible
// to submit the result.
uint256 public resultPublicationBlockStep = 3;
// Timeout in blocks for a relay entry to appear on the chain. Blocks are
// counted from the moment relay request occur.
//
// Timeout is never shorter than the time needed by clients to generate
// relay entry and the time it takes for the last group member to become
// eligible to submit the result plus at least one block to submit it.
uint256 public relayEntryTimeout = groupSize.mul(resultPublicationBlockStep);
// Gas required to verify BLS signature and produce successful relay
// entry. Excludes callback and DKG gas. The worst case (most expensive)
// scenario.
uint256 public entryVerificationGasEstimate = 280000;
// Gas required to submit DKG result. Excludes initiation of group selection.
uint256 public dkgGasEstimate = 1740000;
// Gas required to trigger DKG (starting group selection).
uint256 public groupSelectionGasEstimate = 200000;
// Reimbursement for the submitter of the DKG result. This value is set when
// a new DKG request comes to the operator contract.
//
// When submitting DKG result, the submitter is reimbursed with the actual cost
// and some part of the fee stored in this field may be returned to the service
// contract.
uint256 public dkgSubmitterReimbursementFee;
uint256 internal currentEntryStartBlock;
// Seed value used for the genesis group selection.
// https://www.wolframalpha.com/input/?i=pi+to+78+digits
uint256 internal constant _genesisGroupSeed = 31415926535897932384626433832795028841971693993751058209749445923078164062862;
// Service contract that triggered current group selection.
ServiceContract internal groupSelectionStarterContract;
struct SigningRequest {
uint256 relayRequestId;
uint256 entryVerificationAndProfitFee;
uint256 callbackFee;
uint256 groupIndex;
bytes previousEntry;
address serviceContract;
}
SigningRequest internal signingRequest;
/**
* @dev Triggers the first group selection. Genesis can be called only when
* there are no groups on the operator contract.
*/
function genesis() public payable {
require(numberOfGroups() == 0, "Groups exist");
// Set latest added service contract as a group selection starter to receive any DKG fee surplus.
groupSelectionStarterContract = ServiceContract(serviceContracts[serviceContracts.length.sub(1)]);
startGroupSelection(_genesisGroupSeed, msg.value);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner == msg.sender, "Caller is not the owner");
_;
}
/**
* @dev Checks if sender is authorized.
*/
modifier onlyServiceContract() {
require(
serviceContracts.contains(msg.sender),
"Caller is not an authorized contract"
);
_;
}
constructor(address _serviceContract, address _stakingContract) public {
owner = msg.sender;
serviceContracts.push(_serviceContract);
stakingContract = TokenStaking(_stakingContract);
groups.stakingContract = TokenStaking(_stakingContract);
groups.groupActiveTime = TokenStaking(_stakingContract).undelegationPeriod();
// There are 39 blocks to submit group selection tickets. To minimize
// the submitter's cost by minimizing the number of redundant tickets
// that are not selected into the group, the following approach is
// recommended:
//
// Tickets are submitted in 11 rounds, each round taking 3 blocks.
// As the basic principle, the number of leading zeros in the ticket
// value is subtracted from the number of rounds to determine the round
// the ticket should be submitted in:
// - in round 0, tickets with 11 or more leading zeros are submitted
// - in round 1, tickets with 10 or more leading zeros are submitted
// (...)
// - in round 11, tickets with no leading zeros are submitted.
//
// In each round, group member candidate needs to monitor tickets
// submitted by other candidates and compare them against tickets of
// the candidate not yet submitted to determine if continuing with
// ticket submission still makes sense.
//
// After 33 blocks, there is a 6 blocks mining lag allowing all
// outstanding ticket submissions to have a higher chance of being
// mined before the deadline.
groupSelection.ticketSubmissionTimeout = 3 * 11 + 6;
groupSelection.groupSize = groupSize;
dkgResultVerification.timeDKG = 5*(1+5) + 2*(1+10) + 20;
dkgResultVerification.resultPublicationBlockStep = resultPublicationBlockStep;
dkgResultVerification.groupSize = groupSize;
// TODO: For now, the required number of signatures is equal to group
// threshold. This should be updated to keep a safety margin for
// participants misbehaving during signing.
dkgResultVerification.signatureThreshold = groupThreshold;
}
/**
* @dev Adds service contract
* @param serviceContract Address of the service contract.
*/
function addServiceContract(address serviceContract) public onlyOwner {
serviceContracts.push(serviceContract);
}
/**
* @dev Removes service contract
* @param serviceContract Address of the service contract.
*/
function removeServiceContract(address serviceContract) public onlyOwner {
serviceContracts.removeAddress(serviceContract);
}
/**
* @dev Triggers the selection process of a new candidate group.
* @param _newEntry New random beacon value that stakers will use to
* generate their tickets.
* @param submitter Operator of this contract.
*/
function createGroup(uint256 _newEntry, address payable submitter) public payable onlyServiceContract {
uint256 groupSelectionStartFee = groupSelectionGasEstimate.mul(gasPriceCeiling);
groupSelectionStarterContract = ServiceContract(msg.sender);
startGroupSelection(_newEntry, msg.value.sub(groupSelectionStartFee));
// reimbursing a submitter that triggered group selection
(bool success, ) = stakingContract.magpieOf(submitter).call.value(groupSelectionStartFee)("");
require(success, "Failed reimbursing submitter for starting a group selection");
}
function startGroupSelection(uint256 _newEntry, uint256 _payment) internal {
require(
_payment >= gasPriceCeiling.mul(dkgGasEstimate),
"Insufficient DKG fee"
);
require(isGroupSelectionPossible(), "Group selection in progress");
// If previous group selection failed and there is reimbursement left
// return it to the DKG fee pool.
if (dkgSubmitterReimbursementFee > 0) {
uint256 surplus = dkgSubmitterReimbursementFee;
dkgSubmitterReimbursementFee = 0;
ServiceContract(msg.sender).fundDkgFeePool.value(surplus)();
}
groupSelection.minimumStake = stakingContract.minimumStake();
groupSelection.start(_newEntry);
emit GroupSelectionStarted(_newEntry);
dkgSubmitterReimbursementFee = _payment;
}
function isGroupSelectionPossible() public view returns (bool) {
if (!groupSelection.inProgress) {
return true;
}
// dkgTimeout is the time after key generation protocol is expected to
// be complete plus the expected time to submit the result.
uint256 dkgTimeout = groupSelection.ticketSubmissionStartBlock +
groupSelection.ticketSubmissionTimeout +
dkgResultVerification.timeDKG +
groupSize * resultPublicationBlockStep;
return block.number > dkgTimeout;
}
/**
* @dev Submits ticket to request to participate in a new candidate group.
* @param ticket Bytes representation of a ticket that holds the following:
* - ticketValue: first 8 bytes of a result of keccak256 cryptography hash
* function on the combination of the group selection seed (previous
* beacon output), staker-specific value (address) and virtual staker index.
* - stakerValue: a staker-specific value which is the address of the staker.
* - virtualStakerIndex: 4-bytes number within a range of 1 to staker's weight;
* has to be unique for all tickets submitted by the given staker for the
* current candidate group selection.
*/
function submitTicket(bytes32 ticket) public {
uint256 stakingWeight = stakingContract.eligibleStake(msg.sender, address(this)).div(groupSelection.minimumStake);
groupSelection.submitTicket(ticket, stakingWeight);
}
/**
* @dev Gets the timeout in blocks after which group candidate ticket
* submission is finished.
*/
function ticketSubmissionTimeout() public view returns (uint256) {
return groupSelection.ticketSubmissionTimeout;
}
/**
* @dev Gets the submitted group candidate tickets so far.
*/
function submittedTickets() public view returns (uint64[] memory) {
return groupSelection.tickets;
}
/**
* @dev Gets selected participants in ascending order of their tickets.
*/
function selectedParticipants() public view returns (address[] memory) {
return groupSelection.selectedParticipants();
}
/**
* @dev Submits result of DKG protocol. It is on-chain part of phase 14 of
* the protocol.
*
* @param submitterMemberIndex Claimed submitter candidate group member index
* @param groupPubKey Generated candidate group public key
* @param misbehaved Bytes array of misbehaved (disqualified or inactive)
* group members indexes in ascending order; Indexes reflect positions of
* members in the group as outputted by the group selection protocol.
* @param signatures Concatenation of signatures from members supporting the
* result.
* @param signingMembersIndexes Indices of members corresponding to each
* signature.
*/
function submitDkgResult(
uint256 submitterMemberIndex,
bytes memory groupPubKey,
bytes memory misbehaved,
bytes memory signatures,
uint[] memory signingMembersIndexes
) public {
address[] memory members = selectedParticipants();
dkgResultVerification.verify(
submitterMemberIndex,
groupPubKey,
misbehaved,
signatures,
signingMembersIndexes,
members,
groupSelection.ticketSubmissionStartBlock + groupSelection.ticketSubmissionTimeout
);
groups.setGroupMembers(groupPubKey, members, misbehaved);
groups.addGroup(groupPubKey);
reimburseDkgSubmitter();
emit DkgResultSubmittedEvent(submitterMemberIndex, groupPubKey, misbehaved);
groupSelection.stop();
}
/**
* @dev Compare the reimbursement fee calculated based on the current transaction gas
* price and the current price feed estimate with the DKG reimbursement fee calculated
* and paid at the moment when the DKG was requested. If there is any surplus, it will
* be returned to the DKG fee pool of the service contract which triggered the DKG.
*/
function reimburseDkgSubmitter() internal {
uint256 gasPrice = gasPriceCeiling;
// We need to check if tx.gasprice is non-zero as a workaround to a bug
// in go-ethereum:
// https://github.com/ethereum/go-ethereum/pull/20189
if (tx.gasprice > 0 && tx.gasprice < gasPriceCeiling) {
gasPrice = tx.gasprice;
}
uint256 reimbursementFee = dkgGasEstimate.mul(gasPrice);
address payable magpie = stakingContract.magpieOf(msg.sender);
if (reimbursementFee < dkgSubmitterReimbursementFee) {
uint256 surplus = dkgSubmitterReimbursementFee.sub(reimbursementFee);
dkgSubmitterReimbursementFee = 0;
// Reimburse submitter with actual DKG cost.
magpie.call.value(reimbursementFee)("");
// Return surplus to the contract that started DKG.
groupSelectionStarterContract.fundDkgFeePool.value(surplus)();
} else {
// If submitter used higher gas price reimburse only dkgSubmitterReimbursementFee max.
reimbursementFee = dkgSubmitterReimbursementFee;
dkgSubmitterReimbursementFee = 0;
magpie.call.value(reimbursementFee)("");
}
}
/**
* @dev Creates a request to generate a new relay entry, which will include a
* random number (by signing the previous entry's random number).
* @param requestId Request Id trackable by service contract
* @param previousEntry Previous relay entry
*/
function sign(
uint256 requestId,
bytes memory previousEntry
) public payable onlyServiceContract {
uint256 entryVerificationAndProfitFee = groupProfitFee().add(
entryVerificationFee()
);
require(
msg.value >= entryVerificationAndProfitFee,
"Insufficient new entry fee"
);
uint256 callbackFee = msg.value.sub(entryVerificationAndProfitFee);
signRelayEntry(
requestId, previousEntry, msg.sender,
entryVerificationAndProfitFee, callbackFee
);
}
function signRelayEntry(
uint256 requestId,
bytes memory previousEntry,
address serviceContract,
uint256 entryVerificationAndProfitFee,
uint256 callbackFee
) internal {
require(!isEntryInProgress() || hasEntryTimedOut(), "Beacon is busy");
currentEntryStartBlock = block.number;
uint256 groupIndex = groups.selectGroup(uint256(keccak256(previousEntry)));
signingRequest = SigningRequest(
requestId,
entryVerificationAndProfitFee,
callbackFee,
groupIndex,
previousEntry,
serviceContract
);
bytes memory groupPubKey = groups.getGroupPublicKey(groupIndex);
emit RelayEntryRequested(previousEntry, groupPubKey);
}
/**
* @dev Creates a new relay entry and stores the associated data on the chain.
* @param _groupSignature Group BLS signature over the concatenation of the
* previous entry and seed.
*/
function relayEntry(bytes memory _groupSignature) public nonReentrant {
require(isEntryInProgress(), "Entry was submitted");
require(!hasEntryTimedOut(), "Entry timed out");
bytes memory groupPubKey = groups.getGroupPublicKey(signingRequest.groupIndex);
require(
BLS.verify(
groupPubKey,
signingRequest.previousEntry,
_groupSignature
),
"Invalid signature"
);
emit RelayEntrySubmitted();
// Spend no more than groupSelectionGasEstimate + 40000 gas max
// This will prevent relayEntry failure in case the service contract is compromised
signingRequest.serviceContract.call.gas(groupSelectionGasEstimate.add(40000))(
abi.encodeWithSignature(
"entryCreated(uint256,bytes,address)",
signingRequest.relayRequestId,
_groupSignature,
msg.sender
)
);
if (signingRequest.callbackFee > 0) {
executeCallback(signingRequest, uint256(keccak256(_groupSignature)));
}
(uint256 groupMemberReward, uint256 submitterReward, uint256 subsidy) = newEntryRewardsBreakdown();
groups.addGroupMemberReward(groupPubKey, groupMemberReward);
stakingContract.magpieOf(msg.sender).call.value(submitterReward)("");
if (subsidy > 0) {
signingRequest.serviceContract.call.gas(35000).value(subsidy)(abi.encodeWithSignature("fundRequestSubsidyFeePool()"));
}
currentEntryStartBlock = 0;
}
/**
* @dev Executes customer specified callback for the relay entry request.
* @param signingRequest Request data tracked internally by this contract.
* @param entry The generated random number.
*/
function executeCallback(SigningRequest memory signingRequest, uint256 entry) internal {
uint256 callbackFee = signingRequest.callbackFee;
// Make sure not to spend more than what was received from the service
// contract for the callback
uint256 gasLimit = callbackFee.div(gasPriceCeiling);
bytes memory callbackReturnData;
uint256 gasBeforeCallback = gasleft();
(, callbackReturnData) = signingRequest.serviceContract.call.gas(
gasLimit
)(abi.encodeWithSignature(
"executeCallback(uint256,uint256)",
signingRequest.relayRequestId,
entry
));
uint256 gasAfterCallback = gasleft();
uint256 gasSpent = gasBeforeCallback.sub(gasAfterCallback);
Reimbursements.reimburseCallback(
stakingContract,
gasPriceCeiling,
gasLimit,
gasSpent,
callbackFee,
callbackReturnData
);
}
/**
* @dev Get rewards breakdown in wei for successful entry for the current signing request.
*/
function newEntryRewardsBreakdown() internal view returns(uint256 groupMemberReward, uint256 submitterReward, uint256 subsidy) {
uint256 decimals = 1e16; // Adding 16 decimals to perform float division.
uint256 delayFactor = getDelayFactor();
groupMemberReward = groupMemberBaseReward.mul(delayFactor).div(decimals);
// delay penalty = base reward * (1 - delay factor)
uint256 groupMemberDelayPenalty = groupMemberBaseReward.mul(decimals.sub(delayFactor));
// The submitter reward consists of:
// The callback gas expenditure (reimbursed by the service contract)
// The entry verification fee to cover the cost of verifying the submission,
// paid regardless of their gas expenditure
// Submitter extra reward - 5% of the delay penalties of the entire group
uint256 submitterExtraReward = groupMemberDelayPenalty.mul(groupSize).percent(5).div(decimals);
uint256 entryVerificationFee = signingRequest.entryVerificationAndProfitFee.sub(groupProfitFee());
submitterReward = entryVerificationFee.add(submitterExtraReward);
// Rewards not paid out to the operators are paid out to requesters to subsidize new requests.
subsidy = groupProfitFee().sub(groupMemberReward.mul(groupSize)).sub(submitterExtraReward);
}
/**
* @dev Gets delay factor for rewards calculation.
* @return Integer representing floating-point number with 16 decimals places.
*/
function getDelayFactor() internal view returns(uint256 delayFactor) {
uint256 decimals = 1e16; // Adding 16 decimals to perform float division.
// T_deadline is the earliest block when no submissions are accepted
// and an entry timed out. The last block the entry can be published in is
// currentEntryStartBlock + relayEntryTimeout
// and submission are no longer accepted from block
// currentEntryStartBlock + relayEntryTimeout + 1.
uint256 deadlineBlock = currentEntryStartBlock.add(relayEntryTimeout).add(1);
// T_begin is the earliest block the result can be published in.
// Relay entry can be generated instantly after relay request is
// registered on-chain so a new entry can be published at the next
// block the earliest.
uint256 submissionStartBlock = currentEntryStartBlock.add(1);
// Use submissionStartBlock block as entryReceivedBlock if entry submitted earlier than expected.
uint256 entryReceivedBlock = block.number <= submissionStartBlock ? submissionStartBlock:block.number;
// T_remaining = T_deadline - T_received
uint256 remainingBlocks = deadlineBlock.sub(entryReceivedBlock);
// T_deadline - T_begin
uint256 submissionWindow = deadlineBlock.sub(submissionStartBlock);
// delay factor = [ T_remaining / (T_deadline - T_begin)]^2
//
// Since we add 16 decimal places to perform float division, we do:
// delay factor = [ T_temaining * decimals / (T_deadline - T_begin)]^2 / decimals =
// = [T_remaining / (T_deadline - T_begin) ]^2 * decimals
delayFactor = ((remainingBlocks.mul(decimals).div(submissionWindow))**2).div(decimals);
}
/**
* @dev Returns true if generation of a new relay entry is currently in
* progress.
*/
function isEntryInProgress() internal view returns (bool) {
return currentEntryStartBlock != 0;
}
/**
* @dev Returns true if the currently ongoing new relay entry generation
* operation timed out. There is a certain timeout for a new relay entry
* to be produced, see `relayEntryTimeout` value.
*/
function hasEntryTimedOut() internal view returns (bool) {
return currentEntryStartBlock != 0 && block.number > currentEntryStartBlock + relayEntryTimeout;
}
/**
* @dev Function used to inform about the fact the currently ongoing
* new relay entry generation operation timed out. As a result, the group
* which was supposed to produce a new relay entry is immediately
* terminated and a new group is selected to produce a new relay entry.
* All members of the group are punished by seizing minimum stake of
* their tokens. The submitter of the transaction is rewarded with a
* tattletale reward which is limited to min(1, 20 / group_size) of the
* maximum tattletale reward.
*/
function reportRelayEntryTimeout() public {
require(hasEntryTimedOut(), "Entry did not time out");
uint256 minimumStake = stakingContract.minimumStake();
groups.reportRelayEntryTimeout(signingRequest.groupIndex, groupSize, minimumStake);
// We could terminate the last active group. If that's the case,
// do not try to execute signing again because there is no group
// which can handle it.
if (numberOfGroups() > 0) {
signRelayEntry(
signingRequest.relayRequestId,
signingRequest.previousEntry,
signingRequest.serviceContract,
signingRequest.entryVerificationAndProfitFee,
signingRequest.callbackFee
);
}
emit RelayEntryTimeoutReported(signingRequest.groupIndex);
}
/**
* @dev Gets group profit fee expressed in wei.
*/
function groupProfitFee() public view returns(uint256) {
return groupMemberBaseReward.mul(groupSize);
}
/**
* @dev Checks if the specified account has enough active stake to become
* network operator and that this contract has been authorized for potential
* slashing.
*
* Having the required minimum of active stake makes the operator eligible
* to join the network. If the active stake is not currently undelegating,
* operator is also eligible for work selection.
*
* @param staker Staker's address
* @return True if has enough active stake to participate in the network,
* false otherwise.
*/
function hasMinimumStake(address staker) public view returns(bool) {
return stakingContract.hasMinimumStake(staker, address(this));
}
/**
* @dev Checks if group with the given public key is registered.
*/
function isGroupRegistered(bytes memory groupPubKey) public view returns(bool) {
return groups.isGroupRegistered(groupPubKey);
}
/**
* @dev Checks if a group with the given public key is a stale group.
* Stale group is an expired group which is no longer performing any
* operations. It is important to understand that an expired group may
* still perform some operations for which it was selected when it was still
* active. We consider a group to be stale when it's expired and when its
* expiration time and potentially executed operation timeout are both in
* the past.
*/
function isStaleGroup(bytes memory groupPubKey) public view returns(bool) {
return groups.isStaleGroup(groupPubKey);
}
/**
* @dev Gets the number of active groups. Expired and terminated groups are
* not counted as active.
*/
function numberOfGroups() public view returns(uint256) {
return groups.numberOfGroups();
}
/**
* @dev Returns accumulated group member rewards for provided group.
*/
function getGroupMemberRewards(bytes memory groupPubKey) public view returns (uint256) {
return groups.groupMemberRewards[groupPubKey];
}
/**
* @dev Gets all indices in the provided group for a member.
*/
function getGroupMemberIndices(bytes memory groupPubKey, address member) public view returns (uint256[] memory indices) {
return groups.getGroupMemberIndices(groupPubKey, member);
}
/**
* @dev Withdraws accumulated group member rewards for operator
* using the provided group index and member indices. Once the
* accumulated reward is withdrawn from the selected group, member is
* removed from it. Rewards can be withdrawn only from stale group.
* @param operator Operator address.
* @param groupIndex Group index.
* @param groupMemberIndices Array of member indices for the group member.
*/
function withdrawGroupMemberRewards(address operator, uint256 groupIndex, uint256[] memory groupMemberIndices) public nonReentrant {
uint256 accumulatedRewards = groups.withdrawFromGroup(operator, groupIndex, groupMemberIndices);
(bool success, ) = stakingContract.magpieOf(operator).call.value(accumulatedRewards)("");
if (success) {
emit GroupMemberRewardsWithdrawn(stakingContract.magpieOf(operator), operator, accumulatedRewards, groupIndex);
}
}
/**
* @dev Gets the index of the first active group.
*/
function getFirstActiveGroupIndex() public view returns (uint256) {
return groups.expiredGroupOffset;
}
/**
* @dev Gets group public key.
*/
function getGroupPublicKey(uint256 groupIndex) public view returns (bytes memory) {
return groups.getGroupPublicKey(groupIndex);
}
/**
* @dev Returns fee for entry verification in wei. Does not include group
* profit fee, DKG contribution or callback fee.
*/
function entryVerificationFee() public view returns (uint256) {
return entryVerificationGasEstimate.mul(gasPriceCeiling);
}
/**
* @dev Returns fee for group creation in wei. Includes the cost of DKG
* and the cost of triggering group selection.
*/
function groupCreationFee() public view returns (uint256) {
return dkgGasEstimate.add(groupSelectionGasEstimate).mul(gasPriceCeiling);
}
/**
* @dev Returns members of the given group by group public key.
*/
function getGroupMembers(bytes memory groupPubKey) public view returns (address[] memory members) {
return groups.getGroupMembers(groupPubKey);
}
/**
* @dev Reports unauthorized signing for the provided group. Must provide
* a valid signature of the tattletale address as a message. Successful signature
* verification means the private key has been leaked and all group members
* should be punished by seizingย their tokens. The submitter of this proof is
* rewarded with 5% of the total seized amount scaled by the reward adjustment
* parameter and the rest 95% is burned.
*/
function reportUnauthorizedSigning(
uint256 groupIndex,
bytes memory signedMsgSender
) public {
uint256 minimumStake = stakingContract.minimumStake();
groups.reportUnauthorizedSigning(groupIndex, signedMsgSender, minimumStake);
emit UnauthorizedSigningReported(groupIndex);
}
}
| Gets the number of active groups. Expired and terminated groups are not counted as active./ | function numberOfGroups() public view returns(uint256) {
return groups.numberOfGroups();
}
| 1,840,297 |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "./PoolContext.sol";
import "./VotePowerQueue.sol";
import "./PoolAPY.sol";
///
/// @title PoSPool
/// @dev This is Conflux PoS pool contract
/// @notice Users can use this contract to participate Conflux PoS without running a PoS node.
///
contract PoSPool is PoolContext, Ownable, Initializable {
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
using VotePowerQueue for VotePowerQueue.InOutQueue;
using PoolAPY for PoolAPY.ApyQueue;
uint256 private RATIO_BASE = 10000;
uint256 private CFX_COUNT_OF_ONE_VOTE = 1000;
uint256 private CFX_VALUE_OF_ONE_VOTE = 1000 ether;
uint256 private ONE_DAY_BLOCK_COUNT = 2 * 3600 * 24;
uint256 private ONE_YEAR_BLOCK_COUNT = ONE_DAY_BLOCK_COUNT * 365;
// ======================== Pool config =========================
string public poolName;
// wheter this poolContract registed in PoS
bool public _poolRegisted;
// ratio shared by user: 1-10000
uint256 public poolUserShareRatio = 9000;
// lock period: 7 days + half hour
uint256 public _poolLockPeriod = ONE_DAY_BLOCK_COUNT * 7 + 3600;
// ======================== Struct definitions =========================
struct PoolSummary {
uint256 available;
uint256 interest; // PoS pool interest share
uint256 totalInterest; // total interest of whole pools
}
/// @title UserSummary
/// @custom:field votes User's total votes
/// @custom:field available User's avaliable votes
/// @custom:field locked
/// @custom:field unlocked
/// @custom:field claimedInterest
/// @custom:field currentInterest
struct UserSummary {
uint256 votes; // Total votes in PoS system, including locking, locked, unlocking, unlocked
uint256 available; // locking + locked
uint256 locked;
uint256 unlocked;
uint256 claimedInterest;
uint256 currentInterest;
}
struct PoolShot {
uint256 available;
uint256 balance;
uint256 blockNumber;
}
struct UserShot {
uint256 available;
uint256 accRewardPerCfx;
uint256 blockNumber;
}
// ======================== Contract states =========================
// global pool accumulative reward for each cfx
uint256 public accRewardPerCfx; // start from 0
PoolSummary private _poolSummary;
mapping(address => UserSummary) private userSummaries;
mapping(address => VotePowerQueue.InOutQueue) private userInqueues;
mapping(address => VotePowerQueue.InOutQueue) private userOutqueues;
PoolShot internal lastPoolShot;
mapping(address => UserShot) internal lastUserShots;
EnumerableSet.AddressSet private stakers;
// used to calculate latest seven days APY
PoolAPY.ApyQueue private apyNodes;
// Free fee whitelist
EnumerableSet.AddressSet private feeFreeWhiteList;
// ======================== Modifiers =========================
modifier onlyRegisted() {
require(_poolRegisted, "Pool is not registed");
_;
}
// ======================== Helpers =========================
function _userShareRatio(address _user) public view returns (uint256) {
if (feeFreeWhiteList.contains(_user)) return RATIO_BASE;
UserSummary memory uSummary = userSummaries[_user];
if (uSummary.available >= 1000) { // VIP4(100w) 2%
return 9800;
} else if (uSummary.available >= 100) { // VIP3(10w) 3%
return 9700;
} else if (uSummary.available >= 50){ // VIP2(5w) 4%
return 9600;
} else if (uSummary.available >= 10) { // VIP1(1w) 5%
return 9500;
}
return poolUserShareRatio;
}
function _calUserShare(uint256 reward, address _stakerAddress) private view returns (uint256) {
return reward.mul(_userShareRatio(_stakerAddress)).div(RATIO_BASE);
}
// used to update lastPoolShot after _poolSummary.available changed
function _updatePoolShot() private {
lastPoolShot.available = _poolSummary.available;
lastPoolShot.balance = _selfBalance();
lastPoolShot.blockNumber = _blockNumber();
}
// used to update lastUserShot after userSummary.available and accRewardPerCfx changed
function _updateUserShot(address _user) private {
lastUserShots[_user].available = userSummaries[_user].available;
lastUserShots[_user].accRewardPerCfx = accRewardPerCfx;
lastUserShots[_user].blockNumber = _blockNumber();
}
// used to update accRewardPerCfx after _poolSummary.available changed or user claimed interest
// depend on: lastPoolShot.available and lastPoolShot.balance
function _updateAccRewardPerCfx() private {
uint256 reward = _selfBalance() - lastPoolShot.balance;
if (reward == 0 || lastPoolShot.available == 0) return;
// update global accRewardPerCfx
uint256 cfxCount = lastPoolShot.available.mul(CFX_COUNT_OF_ONE_VOTE);
accRewardPerCfx = accRewardPerCfx.add(reward.div(cfxCount));
// update pool interest info
_poolSummary.totalInterest = _poolSummary.totalInterest.add(reward);
}
// depend on: accRewardPerCfx and lastUserShot
function _updateUserInterest(address _user) private {
UserShot memory uShot = lastUserShots[_user];
if (uShot.available == 0) return;
uint256 latestInterest = accRewardPerCfx.sub(uShot.accRewardPerCfx).mul(uShot.available.mul(CFX_COUNT_OF_ONE_VOTE));
uint256 _userInterest = _calUserShare(latestInterest, _user);
userSummaries[_user].currentInterest = userSummaries[_user].currentInterest.add(_userInterest);
_poolSummary.interest = _poolSummary.interest.add(latestInterest.sub(_userInterest));
}
// depend on: lastPoolShot
function _updateAPY() private {
if (_blockNumber() == lastPoolShot.blockNumber) return;
uint256 reward = _selfBalance() - lastPoolShot.balance;
PoolAPY.ApyNode memory node = PoolAPY.ApyNode({
startBlock: lastPoolShot.blockNumber,
endBlock: _blockNumber(),
reward: reward,
available: lastPoolShot.available
});
uint256 outdatedBlock = 0;
if (_blockNumber() > ONE_DAY_BLOCK_COUNT.mul(2)) {
outdatedBlock = _blockNumber().sub(ONE_DAY_BLOCK_COUNT.mul(2));
}
apyNodes.enqueueAndClearOutdated(node, outdatedBlock);
}
// ======================== Events =========================
event IncreasePoSStake(address indexed user, uint256 votePower);
event DecreasePoSStake(address indexed user, uint256 votePower);
event WithdrawStake(address indexed user, uint256 votePower);
event ClaimInterest(address indexed user, uint256 amount);
event RatioChanged(uint256 ratio);
// error UnnormalReward(uint256 previous, uint256 current, uint256 blockNumber);
// ======================== Init methods =========================
// call this method when depoly the 1967 proxy contract
function initialize() public initializer {
RATIO_BASE = 10000;
CFX_COUNT_OF_ONE_VOTE = 1000;
CFX_VALUE_OF_ONE_VOTE = 1000 ether;
ONE_DAY_BLOCK_COUNT = 2 * 3600 * 24;
ONE_YEAR_BLOCK_COUNT = ONE_DAY_BLOCK_COUNT * 365;
poolUserShareRatio = 9000;
_poolLockPeriod = ONE_DAY_BLOCK_COUNT * 7 + 3600;
}
///
/// @notice Regist the pool contract in PoS internal contract
/// @dev Only admin can do this
/// @param indentifier The identifier of PoS node
/// @param votePower The vote power when register
/// @param blsPubKey The bls public key of PoS node
/// @param vrfPubKey The vrf public key of PoS node
/// @param blsPubKeyProof The bls public key proof of PoS node
///
function register(
bytes32 indentifier,
uint64 votePower,
bytes calldata blsPubKey,
bytes calldata vrfPubKey,
bytes[2] calldata blsPubKeyProof
) public virtual payable onlyOwner {
require(!_poolRegisted, "Pool is already registed");
require(votePower == 1, "votePower should be 1");
require(msg.value == votePower * CFX_VALUE_OF_ONE_VOTE, "msg.value should be 1000 CFX");
_stakingDeposit(msg.value);
_posRegisterRegister(indentifier, votePower, blsPubKey, vrfPubKey, blsPubKeyProof);
_poolRegisted = true;
// update user info
userSummaries[msg.sender].votes += votePower;
userSummaries[msg.sender].available += votePower;
userSummaries[msg.sender].locked += votePower; // directly add to admin's locked votes
_updateUserShot(msg.sender);
//
stakers.add(msg.sender);
// update pool info
_poolSummary.available += votePower;
_updatePoolShot();
}
// ======================== Contract methods =========================
///
/// @notice Increase PoS vote power
/// @param votePower The number of vote power to increase
///
function increaseStake(uint64 votePower) public virtual payable onlyRegisted {
require(votePower > 0, "Minimal votePower is 1");
require(msg.value == votePower * CFX_VALUE_OF_ONE_VOTE, "msg.value should be votePower * 1000 ether");
_stakingDeposit(msg.value);
_posRegisterIncreaseStake(votePower);
emit IncreasePoSStake(msg.sender, votePower);
_updateAccRewardPerCfx();
_updateAPY();
// update user interest
_updateUserInterest(msg.sender);
// put stake info in queue
userInqueues[msg.sender].enqueue(VotePowerQueue.QueueNode(votePower, _blockNumber() + _poolLockPeriod));
userSummaries[msg.sender].locked += userInqueues[msg.sender].collectEndedVotes();
userSummaries[msg.sender].votes += votePower;
userSummaries[msg.sender].available += votePower;
_updateUserShot(msg.sender);
stakers.add(msg.sender);
//
_poolSummary.available += votePower;
_updatePoolShot();
}
///
/// @notice Decrease PoS vote power
/// @param votePower The number of vote power to decrease
///
function decreaseStake(uint64 votePower) public virtual onlyRegisted {
userSummaries[msg.sender].locked += userInqueues[msg.sender].collectEndedVotes();
require(userSummaries[msg.sender].locked >= votePower, "Locked is not enough");
_posRegisterRetire(votePower);
emit DecreasePoSStake(msg.sender, votePower);
_updateAccRewardPerCfx();
_updateAPY();
// update user interest
_updateUserInterest(msg.sender);
//
userOutqueues[msg.sender].enqueue(VotePowerQueue.QueueNode(votePower, _blockNumber() + _poolLockPeriod));
userSummaries[msg.sender].unlocked += userOutqueues[msg.sender].collectEndedVotes();
userSummaries[msg.sender].available -= votePower;
userSummaries[msg.sender].locked -= votePower;
_updateUserShot(msg.sender);
//
_poolSummary.available -= votePower;
_updatePoolShot();
}
///
/// @notice Withdraw PoS vote power
/// @param votePower The number of vote power to withdraw
///
function withdrawStake(uint64 votePower) public onlyRegisted {
userSummaries[msg.sender].unlocked += userOutqueues[msg.sender].collectEndedVotes();
require(userSummaries[msg.sender].unlocked >= votePower, "Unlocked is not enough");
_stakingWithdraw(votePower * CFX_VALUE_OF_ONE_VOTE);
//
userSummaries[msg.sender].unlocked -= votePower;
userSummaries[msg.sender].votes -= votePower;
address payable receiver = payable(msg.sender);
receiver.transfer(votePower * CFX_VALUE_OF_ONE_VOTE);
emit WithdrawStake(msg.sender, votePower);
if (userSummaries[msg.sender].votes == 0) {
stakers.remove(msg.sender);
}
}
///
/// @notice User's interest from participate PoS
/// @param _address The address of user to query
/// @return CFX interest in Drip
///
function userInterest(address _address) public view returns (uint256) {
uint256 _interest = userSummaries[_address].currentInterest;
uint256 _latestAccRewardPerCfx = accRewardPerCfx;
// add latest profit
uint256 _latestReward = _selfBalance() - lastPoolShot.balance;
UserShot memory uShot = lastUserShots[_address];
if (_latestReward > 0) {
uint256 _deltaAcc = _latestReward.div(lastPoolShot.available.mul(CFX_COUNT_OF_ONE_VOTE));
_latestAccRewardPerCfx = _latestAccRewardPerCfx.add(_deltaAcc);
}
if (uShot.available > 0) {
uint256 _latestInterest = _latestAccRewardPerCfx.sub(uShot.accRewardPerCfx).mul(uShot.available.mul(CFX_COUNT_OF_ONE_VOTE));
_interest = _interest.add(_calUserShare(_latestInterest, _address));
}
return _interest;
}
///
/// @notice Claim specific amount user interest
/// @param amount The amount of interest to claim
///
function claimInterest(uint amount) public onlyRegisted {
uint claimableInterest = userInterest(msg.sender);
require(claimableInterest >= amount, "Interest not enough");
_updateAccRewardPerCfx();
_updateAPY();
_updateUserInterest(msg.sender);
//
userSummaries[msg.sender].claimedInterest = userSummaries[msg.sender].claimedInterest.add(amount);
userSummaries[msg.sender].currentInterest = userSummaries[msg.sender].currentInterest.sub(amount);
// update userShot's accRewardPerCfx
_updateUserShot(msg.sender);
// send interest to user
address payable receiver = payable(msg.sender);
receiver.transfer(amount);
emit ClaimInterest(msg.sender, amount);
// update blockNumber and balance
_updatePoolShot();
}
///
/// @notice Claim one user's all interest
///
function claimAllInterest() public onlyRegisted {
uint claimableInterest = userInterest(msg.sender);
require(claimableInterest > 0, "No claimable interest");
claimInterest(claimableInterest);
}
///
/// @notice Get user's pool summary
/// @param _user The address of user to query
/// @return User's summary
///
function userSummary(address _user) public view returns (UserSummary memory) {
UserSummary memory summary = userSummaries[_user];
summary.locked += userInqueues[_user].sumEndedVotes();
summary.unlocked += userOutqueues[_user].sumEndedVotes();
return summary;
}
function poolSummary() public view returns (PoolSummary memory) {
PoolSummary memory summary = _poolSummary;
uint256 _latestReward = _selfBalance().sub(lastPoolShot.balance);
summary.totalInterest = summary.totalInterest.add(_latestReward);
return summary;
}
function poolAPY() public view returns (uint256) {
if(apyNodes.start == apyNodes.end) return 0;
uint256 totalReward = 0;
uint256 totalWorkload = 0;
for(uint256 i = apyNodes.start; i < apyNodes.end; i++) {
PoolAPY.ApyNode memory node = apyNodes.items[i];
totalReward = totalReward.add(node.reward);
totalWorkload = totalWorkload.add(node.available.mul(CFX_VALUE_OF_ONE_VOTE).mul(node.endBlock - node.startBlock));
}
uint256 _latestReward = _selfBalance().sub(lastPoolShot.balance);
if (_latestReward > 0) {
totalReward = totalReward.add(_latestReward);
totalWorkload = totalWorkload.add(lastPoolShot.available.mul(CFX_VALUE_OF_ONE_VOTE).mul(_blockNumber() - lastPoolShot.blockNumber));
}
return totalReward.mul(RATIO_BASE).mul(ONE_YEAR_BLOCK_COUNT).div(totalWorkload);
}
function poolAPY(uint blockNumber) public view returns (uint256) {
if(apyNodes.start == apyNodes.end) return 0;
uint256 totalReward = 0;
uint256 totalWorkload = 0;
for(uint256 i = apyNodes.start; i < apyNodes.end; i++) {
PoolAPY.ApyNode memory node = apyNodes.items[i];
if (node.endBlock > blockNumber) break; // skip future nodes
totalReward = totalReward.add(node.reward);
totalWorkload = totalWorkload.add(node.available.mul(CFX_VALUE_OF_ONE_VOTE).mul(node.endBlock - node.startBlock));
}
uint256 _latestReward = _selfBalance().sub(lastPoolShot.balance);
if (_latestReward > 0) {
totalReward = totalReward.add(_latestReward);
totalWorkload = totalWorkload.add(lastPoolShot.available.mul(CFX_VALUE_OF_ONE_VOTE).mul(_blockNumber() - lastPoolShot.blockNumber));
}
return totalReward.mul(RATIO_BASE).mul(ONE_YEAR_BLOCK_COUNT).div(totalWorkload);
}
///
/// @notice Query pools contract address
/// @return Pool's PoS address
///
function posAddress() public view onlyRegisted returns (bytes32) {
return _posAddressToIdentifier(address(this));
}
function userInQueue(address account) public view returns (VotePowerQueue.QueueNode[] memory) {
return userInqueues[account].queueItems();
}
function userOutQueue(address account) public view returns (VotePowerQueue.QueueNode[] memory) {
return userOutqueues[account].queueItems();
}
function userInQueue(address account, uint64 offset, uint64 limit) public view returns (VotePowerQueue.QueueNode[] memory) {
return userInqueues[account].queueItems(offset, limit);
}
function userOutQueue(address account, uint64 offset, uint64 limit) public view returns (VotePowerQueue.QueueNode[] memory) {
return userOutqueues[account].queueItems(offset, limit);
}
function stakerNumber() public view returns (uint) {
return stakers.length();
}
function stakerAddress(uint256 i) public view returns (address) {
return stakers.at(i);
}
function userShareRatio(address _account) public view returns (uint256) {
return _userShareRatio(_account);
}
// ======================== admin methods =====================
///
/// @notice Enable admin to set the user share ratio
/// @dev The ratio base is 10000, only admin can do this
/// @param ratio The interest user share ratio (1-10000), default is 9000
///
function setPoolUserShareRatio(uint64 ratio) public onlyOwner {
require(ratio > 0 && ratio <= RATIO_BASE, "ratio should be 1-10000");
poolUserShareRatio = ratio;
emit RatioChanged(ratio);
}
///
/// @notice Enable admin to set the lock and unlock period
/// @dev Only admin can do this
/// @param period The lock period in block number, default is seven day's block count
///
function setLockPeriod(uint64 period) public onlyOwner {
_poolLockPeriod = period;
}
function addToFeeFreeWhiteList(address _freeAddress) public onlyOwner returns (bool) {
return feeFreeWhiteList.add(_freeAddress);
}
function removeFromFeeFreeWhiteList(address _freeAddress) public onlyOwner returns (bool) {
return feeFreeWhiteList.remove(_freeAddress);
}
///
/// @notice Enable admin to set the pool name
///
function setPoolName(string memory name) public onlyOwner {
poolName = name;
}
/// @param count Vote cfx count, unit is cfx
function setCfxCountOfOneVote(uint256 count) public onlyOwner {
CFX_COUNT_OF_ONE_VOTE = count;
CFX_VALUE_OF_ONE_VOTE = count * 1 ether;
}
function _withdrawPoolProfit(uint256 amount) public onlyOwner {
require(_poolSummary.interest > amount, "Not enough interest");
require(_selfBalance() > amount, "Balance not enough");
_poolSummary.interest = _poolSummary.interest.sub(amount);
address payable receiver = payable(msg.sender);
receiver.transfer(amount);
_updatePoolShot();
}
// Used to bring account's retired votes back to work
// reStake _poolSummary.available
// function reStake(uint64 votePower) public onlyOwner {
// _posRegisterIncreaseStake(votePower);
// }
function _retireUserStake(address _addr, uint64 endBlockNumber) public onlyOwner {
uint256 votePower = userSummaries[_addr].available;
if (votePower == 0) return;
_updateUserInterest(_addr);
userSummaries[_addr].available = 0;
userSummaries[_addr].locked = 0;
// clear user inqueue
userInqueues[_addr].clear();
userOutqueues[_addr].enqueue(VotePowerQueue.QueueNode(votePower, endBlockNumber));
_updateUserShot(_addr);
_poolSummary.available -= votePower;
}
// When pool node is force retired, use this method to make all user's available stake to unlocking
function _retireUserStakes(uint256 offset, uint256 limit, uint64 endBlockNumber) public onlyOwner {
uint256 len = stakers.length();
if (len == 0) return;
_updateAccRewardPerCfx();
_updateAPY();
uint256 end = offset + limit;
if (end > len) {
end = len;
}
for (uint256 i = offset; i < end; i++) {
_retireUserStake(stakers.at(i), endBlockNumber);
}
_updatePoolShot();
}
// TODO REMOVE used for mocking reward
// receive() external payable {}
} | User's interest from participate PoS _address The address of user to query return CFX interest in Drip add latest profit | function userInterest(address _address) public view returns (uint256) {
uint256 _interest = userSummaries[_address].currentInterest;
uint256 _latestAccRewardPerCfx = accRewardPerCfx;
uint256 _latestReward = _selfBalance() - lastPoolShot.balance;
UserShot memory uShot = lastUserShots[_address];
if (_latestReward > 0) {
uint256 _deltaAcc = _latestReward.div(lastPoolShot.available.mul(CFX_COUNT_OF_ONE_VOTE));
_latestAccRewardPerCfx = _latestAccRewardPerCfx.add(_deltaAcc);
}
if (uShot.available > 0) {
uint256 _latestInterest = _latestAccRewardPerCfx.sub(uShot.accRewardPerCfx).mul(uShot.available.mul(CFX_COUNT_OF_ONE_VOTE));
_interest = _interest.add(_calUserShare(_latestInterest, _address));
}
return _interest;
}
| 6,467,091 |
/**
*Submitted for verification at Etherscan.io on 2020-06-05
*/
pragma solidity =0.6.6;
interface ITavittswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface ITavittswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface ITavittswapV1Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface ITavittswapV1Router02 is ITavittswapV1Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
contract TavittswapV1Router is ITavittswapV1Router02 {
using SafeMath for uint;
address public immutable override factory;
address public immutable override WETH;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'TavittswapV1Router: EXPIRED');
_;
}
constructor(address _factory, address _WETH) public {
factory = _factory;
WETH = _WETH;
}
receive() external payable {
assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}
// **** ADD LIQUIDITY ****
function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) internal virtual returns (uint amountA, uint amountB) {
// create the pair if it doesn't exist yet
if (ITavittswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {
ITavittswapV2Factory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = TavittswapV2Library.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint amountBOptimal = TavittswapV2Library.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'TavittswapV1Router: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint amountAOptimal = TavittswapV2Library.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'TavittswapV1Router: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {
(amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
address pair = TavittswapV2Library.pairFor(factory, tokenA, tokenB);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
liquidity = ITavittswapV2Pair(pair).mint(to);
}
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = TavittswapV2Library.pairFor(factory, token, WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));
liquidity = ITavittswapV2Pair(pair).mint(to);
// refund dust eth, if any
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {
address pair = TavittswapV2Library.pairFor(factory, tokenA, tokenB);
ITavittswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint amount0, uint amount1) = ITavittswapV2Pair(pair).burn(to);
(address token0,) = TavittswapV2Library.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, 'TavittswapV1Router: INSUFFICIENT_A_AMOUNT');
require(amountB >= amountBMin, 'TavittswapV1Router: INSUFFICIENT_B_AMOUNT');
}
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {
(amountToken, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, amountToken);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountA, uint amountB) {
address pair = TavittswapV2Library.pairFor(factory, tokenA, tokenB);
uint value = approveMax ? uint(-1) : liquidity;
ITavittswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);
}
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountToken, uint amountETH) {
address pair = TavittswapV2Library.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
ITavittswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);
}
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountETH) {
(, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this)));
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountETH) {
address pair = TavittswapV2Library.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
ITavittswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
token, liquidity, amountTokenMin, amountETHMin, to, deadline
);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = TavittswapV2Library.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? TavittswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
ITavittswapV2Pair(TavittswapV2Library.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = TavittswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'TavittswapV1Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, TavittswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = TavittswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'TavittswapV1Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, TavittswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'TavittswapV1Router: INVALID_PATH');
amounts = TavittswapV2Library.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'TavittswapV1Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(TavittswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
}
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'TavittswapV1Router: INVALID_PATH');
amounts = TavittswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'TavittswapV1Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, TavittswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'TavittswapV1Router: INVALID_PATH');
amounts = TavittswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'TavittswapV1Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, TavittswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'TavittswapV1Router: INVALID_PATH');
amounts = TavittswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, 'TavittswapV1Router: EXCESSIVE_INPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(TavittswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
// refund dust eth, if any
if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = TavittswapV2Library.sortTokens(input, output);
ITavittswapV2Pair pair = ITavittswapV2Pair(TavittswapV2Library.pairFor(factory, input, output));
uint amountInput;
uint amountOutput;
{ // scope to avoid stack too deep errors
(uint reserve0, uint reserve1,) = pair.getReserves();
(uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = TavittswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
address to = i < path.length - 2 ? TavittswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) {
TransferHelper.safeTransferFrom(
path[0], msg.sender, TavittswapV2Library.pairFor(factory, path[0], path[1]), amountIn
);
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'TavittswapV1Router: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
payable
ensure(deadline)
{
require(path[0] == WETH, 'TavittswapV1Router: INVALID_PATH');
uint amountIn = msg.value;
IWETH(WETH).deposit{value: amountIn}();
assert(IWETH(WETH).transfer(TavittswapV2Library.pairFor(factory, path[0], path[1]), amountIn));
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'TavittswapV1Router: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
ensure(deadline)
{
require(path[path.length - 1] == WETH, 'TavittswapV1Router: INVALID_PATH');
TransferHelper.safeTransferFrom(
path[0], msg.sender, TavittswapV2Library.pairFor(factory, path[0], path[1]), amountIn
);
_swapSupportingFeeOnTransferTokens(path, address(this));
uint amountOut = IERC20(WETH).balanceOf(address(this));
require(amountOut >= amountOutMin, 'TavittswapV1Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
return TavittswapV2Library.quote(amountA, reserveA, reserveB);
}
function getPairFor(address token0, address token1)
public
view
returns (address pair)
{
pair = TavittswapV2Library.pairFor(factory, token0, token1);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountOut)
{
return TavittswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountIn)
{
return TavittswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint amountIn, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return TavittswapV2Library.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint amountOut, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return TavittswapV2Library.getAmountsIn(factory, amountOut, path);
}
}
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
library TavittswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'TavittswapV1Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'TavittswapV1Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'cfa18e1e9f704fb0531920cd12c146a06056e0955ffff260b08185b0b9020761' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = ITavittswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'TavittswapV1Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'TavittswapV1Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'TavittswapV1Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'TavittswapV1Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'TavittswapV1Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'TavittswapV1Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'TavittswapV1Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'TavittswapV1Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
} | fetches and sorts the reserves for a pair | function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = ITavittswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
| 5,883,172 |
./partial_match/3/0xb62EC1019A16861Ee16fa43D4bD6403aB3975C2E/sources/StrategyBondUSDT.sol | Withdraw partial funds, normally used with a vault withdrawal | function withdraw(uint _amount) external {
require(msg.sender == controller, "!controller");
uint _balance = IERC20(want).balanceOf(address(this));
require(_balance < _amount, "!balance");
address _vault = Controller(controller).vaults(address(want));
IERC20(want).safeTransfer(_vault, _amount);
}
| 5,087,095 |
pragma solidity 0.5.15;
contract IAugur {
function createChildUniverse(bytes32 _parentPayoutDistributionHash, uint256[] memory _parentPayoutNumerators) public returns (IUniverse);
function isKnownUniverse(IUniverse _universe) public view returns (bool);
function trustedCashTransfer(address _from, address _to, uint256 _amount) public returns (bool);
function isTrustedSender(address _address) public returns (bool);
function onCategoricalMarketCreated(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, bytes32[] memory _outcomes) public returns (bool);
function onYesNoMarketCreated(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash) public returns (bool);
function onScalarMarketCreated(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, int256[] memory _prices, uint256 _numTicks) public returns (bool);
function logInitialReportSubmitted(IUniverse _universe, address _reporter, address _market, address _initialReporter, uint256 _amountStaked, bool _isDesignatedReporter, uint256[] memory _payoutNumerators, string memory _description, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime) public returns (bool);
function disputeCrowdsourcerCreated(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _size, uint256 _disputeRound) public returns (bool);
function logDisputeCrowdsourcerContribution(IUniverse _universe, address _reporter, address _market, address _disputeCrowdsourcer, uint256 _amountStaked, string memory description, uint256[] memory _payoutNumerators, uint256 _currentStake, uint256 _stakeRemaining, uint256 _disputeRound) public returns (bool);
function logDisputeCrowdsourcerCompleted(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime, bool _pacingOn, uint256 _totalRepStakedInPayout, uint256 _totalRepStakedInMarket, uint256 _disputeRound) public returns (bool);
function logInitialReporterRedeemed(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool);
function logDisputeCrowdsourcerRedeemed(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool);
function logMarketFinalized(IUniverse _universe, uint256[] memory _winningPayoutNumerators) public returns (bool);
function logMarketMigrated(IMarket _market, IUniverse _originalUniverse) public returns (bool);
function logReportingParticipantDisavowed(IUniverse _universe, IMarket _market) public returns (bool);
function logMarketParticipantsDisavowed(IUniverse _universe) public returns (bool);
function logCompleteSetsPurchased(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets) public returns (bool);
function logCompleteSetsSold(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets, uint256 _fees) public returns (bool);
function logMarketOIChanged(IUniverse _universe, IMarket _market) public returns (bool);
function logTradingProceedsClaimed(IUniverse _universe, address _sender, address _market, uint256 _outcome, uint256 _numShares, uint256 _numPayoutTokens, uint256 _fees) public returns (bool);
function logUniverseForked(IMarket _forkingMarket) public returns (bool);
function logReputationTokensTransferred(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool);
function logReputationTokensBurned(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool);
function logReputationTokensMinted(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool);
function logShareTokensBalanceChanged(address _account, IMarket _market, uint256 _outcome, uint256 _balance) public returns (bool);
function logDisputeCrowdsourcerTokensTransferred(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool);
function logDisputeCrowdsourcerTokensBurned(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool);
function logDisputeCrowdsourcerTokensMinted(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool);
function logDisputeWindowCreated(IDisputeWindow _disputeWindow, uint256 _id, bool _initial) public returns (bool);
function logParticipationTokensRedeemed(IUniverse universe, address _sender, uint256 _attoParticipationTokens, uint256 _feePayoutShare) public returns (bool);
function logTimestampSet(uint256 _newTimestamp) public returns (bool);
function logInitialReporterTransferred(IUniverse _universe, IMarket _market, address _from, address _to) public returns (bool);
function logMarketTransferred(IUniverse _universe, address _from, address _to) public returns (bool);
function logParticipationTokensTransferred(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool);
function logParticipationTokensBurned(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool);
function logParticipationTokensMinted(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool);
function logMarketRepBondTransferred(address _universe, address _from, address _to) public returns (bool);
function logWarpSyncDataUpdated(address _universe, uint256 _warpSyncHash, uint256 _marketEndTime) public returns (bool);
function isKnownFeeSender(address _feeSender) public view returns (bool);
function lookup(bytes32 _key) public view returns (address);
function getTimestamp() public view returns (uint256);
function getMaximumMarketEndDate() public returns (uint256);
function isKnownMarket(IMarket _market) public view returns (bool);
function derivePayoutDistributionHash(uint256[] memory _payoutNumerators, uint256 _numTicks, uint256 numOutcomes) public view returns (bytes32);
function logValidityBondChanged(uint256 _validityBond) public returns (bool);
function logDesignatedReportStakeChanged(uint256 _designatedReportStake) public returns (bool);
function logNoShowBondChanged(uint256 _noShowBond) public returns (bool);
function logReportingFeeChanged(uint256 _reportingFee) public returns (bool);
function getUniverseForkIndex(IUniverse _universe) public view returns (uint256);
}
interface IAugurWallet {
function initialize(address _owner, address _referralAddress, bytes32 _fingerprint, address _augur, address _registry, address _registryV2, IERC20 _cash, IAffiliates _affiliates, IERC1155 _shareToken, address _createOrder, address _fillOrder, address _zeroXTrade) external;
function transferCash(address _to, uint256 _amount) external;
function executeTransaction(address _to, bytes calldata _data, uint256 _value) external returns (bool);
}
interface IAugurWalletRegistry {
function ethExchange() external returns (IUniswapV2Pair);
function WETH() external returns (IWETH);
function token0IsCash() external returns (bool);
}
contract IAugurWalletFactory {
function getCreate2WalletAddress(address _owner) external view returns (address);
function createAugurWallet(address _owner, address _referralAddress, bytes32 _fingerprint) public returns (IAugurWallet);
}
contract Context {
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IRelayHub {
// Relay management
/**
* @dev Adds stake to a relay and sets its `unstakeDelay`. If the relay does not exist, it is created, and the caller
* of this function becomes its owner. If the relay already exists, only the owner can call this function. A relay
* cannot be its own owner.
*
* All Ether in this function call will be added to the relay's stake.
* Its unstake delay will be assigned to `unstakeDelay`, but the new value must be greater or equal to the current one.
*
* Emits a {Staked} event.
*/
function stake(address relayaddr, uint256 unstakeDelay) external payable;
/**
* @dev Emitted when a relay's stake or unstakeDelay are increased
*/
event Staked(address indexed relay, uint256 stake, uint256 unstakeDelay);
/**
* @dev Registers the caller as a relay.
* The relay must be staked for, and not be a contract (i.e. this function must be called directly from an EOA).
*
* This function can be called multiple times, emitting new {RelayAdded} events. Note that the received
* `transactionFee` is not enforced by {relayCall}.
*
* Emits a {RelayAdded} event.
*/
function registerRelay(uint256 transactionFee, string calldata url) external;
/**
* @dev Emitted when a relay is registered or re-registerd. Looking at these events (and filtering out
* {RelayRemoved} events) lets a client discover the list of available relays.
*/
event RelayAdded(address indexed relay, address indexed owner, uint256 transactionFee, uint256 stake, uint256 unstakeDelay, string url);
/**
* @dev Removes (deregisters) a relay. Unregistered (but staked for) relays can also be removed.
*
* Can only be called by the owner of the relay. After the relay's `unstakeDelay` has elapsed, {unstake} will be
* callable.
*
* Emits a {RelayRemoved} event.
*/
function removeRelayByOwner(address relay) external;
/**
* @dev Emitted when a relay is removed (deregistered). `unstakeTime` is the time when unstake will be callable.
*/
event RelayRemoved(address indexed relay, uint256 unstakeTime);
/** Deletes the relay from the system, and gives back its stake to the owner.
*
* Can only be called by the relay owner, after `unstakeDelay` has elapsed since {removeRelayByOwner} was called.
*
* Emits an {Unstaked} event.
*/
function unstake(address relay) external;
/**
* @dev Emitted when a relay is unstaked for, including the returned stake.
*/
event Unstaked(address indexed relay, uint256 stake);
// States a relay can be in
enum RelayState {
Unknown, // The relay is unknown to the system: it has never been staked for
Staked, // The relay has been staked for, but it is not yet active
Registered, // The relay has registered itself, and is active (can relay calls)
Removed // The relay has been removed by its owner and can no longer relay calls. It must wait for its unstakeDelay to elapse before it can unstake
}
/**
* @dev Returns a relay's status. Note that relays can be deleted when unstaked or penalized, causing this function
* to return an empty entry.
*/
function getRelay(address relay) external view returns (uint256 totalStake, uint256 unstakeDelay, uint256 unstakeTime, address payable owner, RelayState state);
// Balance management
/**
* @dev Deposits Ether for a contract, so that it can receive (and pay for) relayed transactions.
*
* Unused balance can only be withdrawn by the contract itself, by calling {withdraw}.
*
* Emits a {Deposited} event.
*/
function depositFor(address target) external payable;
/**
* @dev Emitted when {depositFor} is called, including the amount and account that was funded.
*/
event Deposited(address indexed recipient, address indexed from, uint256 amount);
/**
* @dev Returns an account's deposits. These can be either a contracts's funds, or a relay owner's revenue.
*/
function balanceOf(address target) external view returns (uint256);
/**
* Withdraws from an account's balance, sending it back to it. Relay owners call this to retrieve their revenue, and
* contracts can use it to reduce their funding.
*
* Emits a {Withdrawn} event.
*/
function withdraw(uint256 amount, address payable dest) external;
/**
* @dev Emitted when an account withdraws funds from `RelayHub`.
*/
event Withdrawn(address indexed account, address indexed dest, uint256 amount);
// Relaying
/**
* @dev Checks if the `RelayHub` will accept a relayed operation.
* Multiple things must be true for this to happen:
* - all arguments must be signed for by the sender (`from`)
* - the sender's nonce must be the current one
* - the recipient must accept this transaction (via {acceptRelayedCall})
*
* Returns a `PreconditionCheck` value (`OK` when the transaction can be relayed), or a recipient-specific error
* code if it returns one in {acceptRelayedCall}.
*/
function canRelay(
address relay,
address from,
address to,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes calldata signature,
bytes calldata approvalData
) external view returns (uint256 status, bytes memory recipientContext);
// Preconditions for relaying, checked by canRelay and returned as the corresponding numeric values.
enum PreconditionCheck {
OK, // All checks passed, the call can be relayed
WrongSignature, // The transaction to relay is not signed by requested sender
WrongNonce, // The provided nonce has already been used by the sender
AcceptRelayedCallReverted, // The recipient rejected this call via acceptRelayedCall
InvalidRecipientStatusCode // The recipient returned an invalid (reserved) status code
}
/**
* @dev Relays a transaction.
*
* For this to succeed, multiple conditions must be met:
* - {canRelay} must `return PreconditionCheck.OK`
* - the sender must be a registered relay
* - the transaction's gas price must be larger or equal to the one that was requested by the sender
* - the transaction must have enough gas to not run out of gas if all internal transactions (calls to the
* recipient) use all gas available to them
* - the recipient must have enough balance to pay the relay for the worst-case scenario (i.e. when all gas is
* spent)
*
* If all conditions are met, the call will be relayed and the recipient charged. {preRelayedCall}, the encoded
* function and {postRelayedCall} will be called in that order.
*
* Parameters:
* - `from`: the client originating the request
* - `to`: the target {IRelayRecipient} contract
* - `encodedFunction`: the function call to relay, including data
* - `transactionFee`: fee (%) the relay takes over actual gas cost
* - `gasPrice`: gas price the client is willing to pay
* - `gasLimit`: gas to forward when calling the encoded function
* - `nonce`: client's nonce
* - `signature`: client's signature over all previous params, plus the relay and RelayHub addresses
* - `approvalData`: dapp-specific data forwared to {acceptRelayedCall}. This value is *not* verified by the
* `RelayHub`, but it still can be used for e.g. a signature.
*
* Emits a {TransactionRelayed} event.
*/
function relayCall(
address from,
address to,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes calldata signature,
bytes calldata approvalData
) external;
/**
* @dev Emitted when an attempt to relay a call failed.
*
* This can happen due to incorrect {relayCall} arguments, or the recipient not accepting the relayed call. The
* actual relayed call was not executed, and the recipient not charged.
*
* The `reason` parameter contains an error code: values 1-10 correspond to `PreconditionCheck` entries, and values
* over 10 are custom recipient error codes returned from {acceptRelayedCall}.
*/
event CanRelayFailed(address indexed relay, address indexed from, address indexed to, bytes4 selector, uint256 reason);
/**
* @dev Emitted when a transaction is relayed.
* Useful when monitoring a relay's operation and relayed calls to a contract
*
* Note that the actual encoded function might be reverted: this is indicated in the `status` parameter.
*
* `charge` is the Ether value deducted from the recipient's balance, paid to the relay's owner.
*/
event TransactionRelayed(address indexed relay, address indexed from, address indexed to, bytes4 selector, RelayCallStatus status, uint256 charge);
// Reason error codes for the TransactionRelayed event
enum RelayCallStatus {
OK, // The transaction was successfully relayed and execution successful - never included in the event
RelayedCallFailed, // The transaction was relayed, but the relayed call failed
PreRelayedFailed, // The transaction was not relayed due to preRelatedCall reverting
PostRelayedFailed, // The transaction was relayed and reverted due to postRelatedCall reverting
RecipientBalanceChanged // The transaction was relayed and reverted due to the recipient's balance changing
}
/**
* @dev Returns how much gas should be forwarded to a call to {relayCall}, in order to relay a transaction that will
* spend up to `relayedCallStipend` gas.
*/
function requiredGas(uint256 relayedCallStipend) external view returns (uint256);
/**
* @dev Returns the maximum recipient charge, given the amount of gas forwarded, gas price and relay fee.
*/
function maxPossibleCharge(uint256 relayedCallStipend, uint256 gasPrice, uint256 transactionFee) external view returns (uint256);
// Relay penalization.
// Any account can penalize relays, removing them from the system immediately, and rewarding the
// reporter with half of the relay's stake. The other half is burned so that, even if the relay penalizes itself, it
// still loses half of its stake.
/**
* @dev Penalize a relay that signed two transactions using the same nonce (making only the first one valid) and
* different data (gas price, gas limit, etc. may be different).
*
* The (unsigned) transaction data and signature for both transactions must be provided.
*/
function penalizeRepeatedNonce(bytes calldata unsignedTx1, bytes calldata signature1, bytes calldata unsignedTx2, bytes calldata signature2) external;
/**
* @dev Penalize a relay that sent a transaction that didn't target `RelayHub`'s {registerRelay} or {relayCall}.
*/
function penalizeIllegalTransaction(bytes calldata unsignedTx, bytes calldata signature) external;
/**
* @dev Emitted when a relay is penalized.
*/
event Penalized(address indexed relay, address sender, uint256 amount);
/**
* @dev Returns an account's nonce in `RelayHub`.
*/
function getNonce(address from) external view returns (uint256);
}
interface IRelayRecipient {
/**
* @dev Returns the address of the {IRelayHub} instance this recipient interacts with.
*/
function getHubAddr() external view returns (address);
/**
* @dev Called by {IRelayHub} to validate if this recipient accepts being charged for a relayed call. Note that the
* recipient will be charged regardless of the execution result of the relayed call (i.e. if it reverts or not).
*
* The relay request was originated by `from` and will be served by `relay`. `encodedFunction` is the relayed call
* calldata, so its first four bytes are the function selector. The relayed call will be forwarded `gasLimit` gas,
* and the transaction executed with a gas price of at least `gasPrice`. `relay`'s fee is `transactionFee`, and the
* recipient will be charged at most `maxPossibleCharge` (in wei). `nonce` is the sender's (`from`) nonce for
* replay attack protection in {IRelayHub}, and `approvalData` is a optional parameter that can be used to hold a signature
* over all or some of the previous values.
*
* Returns a tuple, where the first value is used to indicate approval (0) or rejection (custom non-zero error code,
* values 1 to 10 are reserved) and the second one is data to be passed to the other {IRelayRecipient} functions.
*
* {acceptRelayedCall} is called with 50k gas: if it runs out during execution, the request will be considered
* rejected. A regular revert will also trigger a rejection.
*/
function acceptRelayedCall(
address relay,
address from,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes calldata approvalData,
uint256 maxPossibleCharge
)
external
view
returns (uint256, bytes memory);
/**
* @dev Called by {IRelayHub} on approved relay call requests, before the relayed call is executed. This allows to e.g.
* pre-charge the sender of the transaction.
*
* `context` is the second value returned in the tuple by {acceptRelayedCall}.
*
* Returns a value to be passed to {postRelayedCall}.
*
* {preRelayedCall} is called with 100k gas: if it runs out during exection or otherwise reverts, the relayed call
* will not be executed, but the recipient will still be charged for the transaction's cost.
*/
function preRelayedCall(bytes calldata context) external returns (bytes32);
/**
* @dev Called by {IRelayHub} on approved relay call requests, after the relayed call is executed. This allows to e.g.
* charge the user for the relayed call costs, return any overcharges from {preRelayedCall}, or perform
* contract-specific bookkeeping.
*
* `context` is the second value returned in the tuple by {acceptRelayedCall}. `success` is the execution status of
* the relayed call. `actualCharge` is an estimate of how much the recipient will be charged for the transaction,
* not including any gas used by {postRelayedCall} itself. `preRetVal` is {preRelayedCall}'s return value.
*
*
* {postRelayedCall} is called with 100k gas: if it runs out during execution or otherwise reverts, the relayed call
* and the call to {preRelayedCall} will be reverted retroactively, but the recipient will still be charged for the
* transaction's cost.
*/
function postRelayedCall(bytes calldata context, bool success, uint256 actualCharge, bytes32 preRetVal) external;
}
contract GSNRecipient is IRelayRecipient, Context {
// Default RelayHub address, deployed on mainnet and all testnets at the same address
address private _relayHub = 0xD216153c06E857cD7f72665E0aF1d7D82172F494;
uint256 constant private RELAYED_CALL_ACCEPTED = 0;
uint256 constant private RELAYED_CALL_REJECTED = 11;
// How much gas is forwarded to postRelayedCall
uint256 constant internal POST_RELAYED_CALL_MAX_GAS = 100000;
/**
* @dev Emitted when a contract changes its {IRelayHub} contract to a new one.
*/
event RelayHubChanged(address indexed oldRelayHub, address indexed newRelayHub);
/**
* @dev Returns the address of the {IRelayHub} contract for this recipient.
*/
function getHubAddr() public view returns (address) {
return _relayHub;
}
/**
* @dev Switches to a new {IRelayHub} instance. This method is added for future-proofing: there's no reason to not
* use the default instance.
*
* IMPORTANT: After upgrading, the {GSNRecipient} will no longer be able to receive relayed calls from the old
* {IRelayHub} instance. Additionally, all funds should be previously withdrawn via {_withdrawDeposits}.
*/
function _upgradeRelayHub(address newRelayHub) internal {
address currentRelayHub = _relayHub;
require(newRelayHub != address(0), "GSNRecipient: new RelayHub is the zero address");
require(newRelayHub != currentRelayHub, "GSNRecipient: new RelayHub is the current one");
emit RelayHubChanged(currentRelayHub, newRelayHub);
_relayHub = newRelayHub;
}
/**
* @dev Returns the version string of the {IRelayHub} for which this recipient implementation was built. If
* {_upgradeRelayHub} is used, the new {IRelayHub} instance should be compatible with this version.
*/
// This function is view for future-proofing, it may require reading from
// storage in the future.
function relayHubVersion() public view returns (string memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return "1.0.0";
}
/**
* @dev Withdraws the recipient's deposits in `RelayHub`.
*
* Derived contracts should expose this in an external interface with proper access control.
*/
function _withdrawDeposits(uint256 amount, address payable payee) internal {
IRelayHub(_relayHub).withdraw(amount, payee);
}
// Overrides for Context's functions: when called from RelayHub, sender and
// data require some pre-processing: the actual sender is stored at the end
// of the call data, which in turns means it needs to be removed from it
// when handling said data.
/**
* @dev Replacement for msg.sender. Returns the actual sender of a transaction: msg.sender for regular transactions,
* and the end-user for GSN relayed calls (where msg.sender is actually `RelayHub`).
*
* IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.sender`, and use {_msgSender} instead.
*/
function _msgSender() internal view returns (address payable) {
if (block.coinbase != _relayHub) { //injected CONTRACT AFFECTED BY MINERS
return msg.sender;
} else {
return _getRelayedCallSender();
}
}
/**
* @dev Replacement for msg.data. Returns the actual calldata of a transaction: msg.data for regular transactions,
* and a reduced version for GSN relayed calls (where msg.data contains additional information).
*
* IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.data`, and use {_msgData} instead.
*/
function _msgData() internal view returns (bytes memory) {
if (block.coinbase != _relayHub) { //injected CONTRACT AFFECTED BY MINERS
return msg.data;
} else {
return _getRelayedCallData();
}
}
// Base implementations for pre and post relayedCall: only RelayHub can invoke them, and data is forwarded to the
// internal hook.
/**
* @dev See `IRelayRecipient.preRelayedCall`.
*
* This function should not be overriden directly, use `_preRelayedCall` instead.
*
* * Requirements:
*
* - the caller must be the `RelayHub` contract.
*/
function preRelayedCall(bytes calldata context) external returns (bytes32) {
require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub");
return _preRelayedCall(context);
}
/**
* @dev See `IRelayRecipient.preRelayedCall`.
*
* Called by `GSNRecipient.preRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts
* must implement this function with any relayed-call preprocessing they may wish to do.
*
*/
function _preRelayedCall(bytes memory context) internal returns (bytes32);
/**
* @dev See `IRelayRecipient.postRelayedCall`.
*
* This function should not be overriden directly, use `_postRelayedCall` instead.
*
* * Requirements:
*
* - the caller must be the `RelayHub` contract.
*/
function postRelayedCall(bytes calldata context, bool success, uint256 actualCharge, bytes32 preRetVal) external {
require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub");
_postRelayedCall(context, success, actualCharge, preRetVal);
}
/**
* @dev See `IRelayRecipient.postRelayedCall`.
*
* Called by `GSNRecipient.postRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts
* must implement this function with any relayed-call postprocessing they may wish to do.
*
*/
function _postRelayedCall(bytes memory context, bool success, uint256 actualCharge, bytes32 preRetVal) internal;
/**
* @dev Return this in acceptRelayedCall to proceed with the execution of a relayed call. Note that this contract
* will be charged a fee by RelayHub
*/
function _approveRelayedCall() internal pure returns (uint256, bytes memory) {
return _approveRelayedCall("");
}
/**
* @dev See `GSNRecipient._approveRelayedCall`.
*
* This overload forwards `context` to _preRelayedCall and _postRelayedCall.
*/
function _approveRelayedCall(bytes memory context) internal pure returns (uint256, bytes memory) {
return (RELAYED_CALL_ACCEPTED, context);
}
/**
* @dev Return this in acceptRelayedCall to impede execution of a relayed call. No fees will be charged.
*/
function _rejectRelayedCall(uint256 errorCode) internal pure returns (uint256, bytes memory) {
return (RELAYED_CALL_REJECTED + errorCode, "");
}
/*
* @dev Calculates how much RelayHub will charge a recipient for using `gas` at a `gasPrice`, given a relayer's
* `serviceFee`.
*/
function _computeCharge(uint256 gas, uint256 gasPrice, uint256 serviceFee) internal pure returns (uint256) {
// The fee is expressed as a percentage. E.g. a value of 40 stands for a 40% fee, so the recipient will be
// charged for 1.4 times the spent amount.
return (gas * gasPrice * (100 + serviceFee)) / 100;
}
function _getRelayedCallSender() private pure returns (address payable result) {
// We need to read 20 bytes (an address) located at array index msg.data.length - 20. In memory, the array
// is prefixed with a 32-byte length value, so we first add 32 to get the memory read index. However, doing
// so would leave the address in the upper 20 bytes of the 32-byte word, which is inconvenient and would
// require bit shifting. We therefore subtract 12 from the read index so the address lands on the lower 20
// bytes. This can always be done due to the 32-byte prefix.
// The final memory read index is msg.data.length - 20 + 32 - 12 = msg.data.length. Using inline assembly is the
// easiest/most-efficient way to perform this operation.
// These fields are not accessible from assembly
bytes memory array = msg.data;
uint256 index = msg.data.length;
// solhint-disable-next-line no-inline-assembly
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
result := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
function _getRelayedCallData() private pure returns (bytes memory) {
// RelayHub appends the sender address at the end of the calldata, so in order to retrieve the actual msg.data,
// we must strip the last 20 bytes (length of an address type) from it.
uint256 actualDataLength = msg.data.length - 20;
bytes memory actualData = new bytes(actualDataLength);
for (uint256 i = 0; i < actualDataLength; ++i) {
actualData[i] = msg.data[i];
}
return actualData;
}
}
library RLPReader {
uint8 constant STRING_SHORT_START = 0x80;
uint8 constant STRING_LONG_START = 0xb8;
uint8 constant LIST_SHORT_START = 0xc0;
uint8 constant LIST_LONG_START = 0xf8;
uint8 constant WORD_SIZE = 32;
struct RLPItem {
uint len;
uint memPtr;
}
using RLPReader for bytes;
using RLPReader for uint;
using RLPReader for RLPReader.RLPItem;
// helper function to decode rlp encoded ethereum transaction
/*
* @param rawTransaction RLP encoded ethereum transaction
* @return tuple (nonce,gasPrice,gasLimit,to,value,data)
*/
function decodeTransaction(bytes memory rawTransaction) internal pure returns (uint, uint, uint, address, uint, bytes memory){
RLPReader.RLPItem[] memory values = rawTransaction.toRlpItem().toList(); // must convert to an rlpItem first!
return (values[0].toUint(), values[1].toUint(), values[2].toUint(), values[3].toAddress(), values[4].toUint(), values[5].toBytes());
}
/*
* @param item RLP encoded bytes
*/
function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) {
if (item.length == 0)
return RLPItem(0, 0);
uint memPtr;
assembly {
memPtr := add(item, 0x20)
}
return RLPItem(item.length, memPtr);
}
/*
* @param item RLP encoded list in bytes
*/
function toList(RLPItem memory item) internal pure returns (RLPItem[] memory result) {
require(isList(item), "isList failed");
uint items = numItems(item);
result = new RLPItem[](items);
uint memPtr = item.memPtr + _payloadOffset(item.memPtr);
uint dataLen;
for (uint i = 0; i < items; i++) {
dataLen = _itemLength(memPtr);
result[i] = RLPItem(dataLen, memPtr);
memPtr = memPtr + dataLen;
}
}
/*
* Helpers
*/
// @return indicator whether encoded payload is a list. negate this function call for isData.
function isList(RLPItem memory item) internal pure returns (bool) {
uint8 byte0;
uint memPtr = item.memPtr;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < LIST_SHORT_START)
return false;
return true;
}
// @return number of payload items inside an encoded list.
function numItems(RLPItem memory item) internal pure returns (uint) {
uint count = 0;
uint currPtr = item.memPtr + _payloadOffset(item.memPtr);
uint endPtr = item.memPtr + item.len;
while (currPtr < endPtr) {
currPtr = currPtr + _itemLength(currPtr);
// skip over an item
count++;
}
return count;
}
// @return entire rlp item byte length
function _itemLength(uint memPtr) internal pure returns (uint len) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 1;
else if (byte0 < STRING_LONG_START)
return byte0 - STRING_SHORT_START + 1;
else if (byte0 < LIST_SHORT_START) {
assembly {
let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is
memPtr := add(memPtr, 1) // skip over the first byte
/* 32 byte word size */
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len
len := add(dataLen, add(byteLen, 1))
}
}
else if (byte0 < LIST_LONG_START) {
return byte0 - LIST_SHORT_START + 1;
}
else {
assembly {
let byteLen := sub(byte0, 0xf7)
memPtr := add(memPtr, 1)
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length
len := add(dataLen, add(byteLen, 1))
}
}
}
// @return number of bytes until the data
function _payloadOffset(uint memPtr) internal pure returns (uint) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 0;
else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START))
return 1;
else if (byte0 < LIST_SHORT_START) // being explicit
return byte0 - (STRING_LONG_START - 1) + 1;
else
return byte0 - (LIST_LONG_START - 1) + 1;
}
/** RLPItem conversions into data types **/
// @returns raw rlp encoding in bytes
function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) {
bytes memory result = new bytes(item.len);
uint ptr;
assembly {
ptr := add(0x20, result)
}
copy(item.memPtr, ptr, item.len);
return result;
}
function toBoolean(RLPItem memory item) internal pure returns (bool) {
require(item.len == 1, "Invalid RLPItem. Booleans are encoded in 1 byte");
uint result;
uint memPtr = item.memPtr;
assembly {
result := byte(0, mload(memPtr))
}
return result == 0 ? false : true;
}
function toAddress(RLPItem memory item) internal pure returns (address) {
// 1 byte for the length prefix according to RLP spec
require(item.len <= 21, "Invalid RLPItem. Addresses are encoded in 20 bytes or less");
return address(toUint(item));
}
function toUint(RLPItem memory item) internal pure returns (uint) {
uint offset = _payloadOffset(item.memPtr);
uint len = item.len - offset;
uint memPtr = item.memPtr + offset;
uint result;
assembly {
result := div(mload(memPtr), exp(256, sub(32, len))) // shift to the correct location
}
return result;
}
function toBytes(RLPItem memory item) internal pure returns (bytes memory) {
uint offset = _payloadOffset(item.memPtr);
uint len = item.len - offset;
// data length
bytes memory result = new bytes(len);
uint destPtr;
assembly {
destPtr := add(0x20, result)
}
copy(item.memPtr + offset, destPtr, len);
return result;
}
/*
* @param src Pointer to source
* @param dest Pointer to destination
* @param len Amount of memory to copy from the source
*/
function copy(uint src, uint dest, uint len) internal pure {
// copy as many word sizes as possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
src += WORD_SIZE;
dest += WORD_SIZE;
}
// left over bytes. Mask is used to remove unwanted bytes from the word
uint mask = 256 ** (WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask)) // zero out src
let destpart := and(mload(dest), mask) // retrieve the bytes
mstore(dest, or(destpart, srcpart))
}
}
}
library ContractExists {
function exists(address _address) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(_address) }
return size > 0;
}
}
contract IOwnable {
function getOwner() public view returns (address);
function transferOwnership(address _newOwner) public returns (bool);
}
contract ITyped {
function getTypeName() public view returns (bytes32);
}
contract Initializable {
bool private initialized = false;
modifier beforeInitialized {
require(!initialized);
_;
}
function endInitialization() internal beforeInitialized {
initialized = true;
}
function getInitialized() public view returns (bool) {
return initialized;
}
}
contract AugurWallet is Initializable, IAugurWallet {
using SafeMathUint256 for uint256;
IAugurWalletRegistry public registry;
mapping(address => bool) public authorizedProxies;
uint256 private constant MAX_APPROVAL_AMOUNT = 2 ** 256 - 1;
//keccak256("EIP712Domain(address verifyingContract)");
bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH = 0x035aff83d86937d35b32e04f0ddc6ff469290eef2f1b692d8a815c89404d4749;
//keccak256("AugurWalletMessage(bytes message)");
bytes32 public constant MSG_TYPEHASH = 0xe0e790a7bae5fba0106cf286392dd87dfd6ec8631e5631988133e4470b9e7b0d;
// bytes4(keccak256("isValidSignature(bytes,bytes)")
bytes4 constant internal EIP1271_MAGIC_VALUE = 0x20c13b0b;
address owner;
bytes32 public domainSeparator;
IERC20 public cash;
function initialize(address _owner, address _referralAddress, bytes32 _fingerprint, address _augur, address _registry, address _registryV2, IERC20 _cash, IAffiliates _affiliates, IERC1155 _shareToken, address _createOrder, address _fillOrder, address _zeroXTrade) external beforeInitialized {
endInitialization();
domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, this));
owner = _owner;
registry = IAugurWalletRegistry(_registryV2);
authorizedProxies[_registry] = true;
authorizedProxies[_registryV2] = true;
cash = _cash;
_cash.approve(_augur, MAX_APPROVAL_AMOUNT);
_cash.approve(_createOrder, MAX_APPROVAL_AMOUNT);
_shareToken.setApprovalForAll(_createOrder, true);
_cash.approve(_fillOrder, MAX_APPROVAL_AMOUNT);
_shareToken.setApprovalForAll(_fillOrder, true);
_cash.approve(_zeroXTrade, MAX_APPROVAL_AMOUNT);
_affiliates.setFingerprint(_fingerprint);
if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS
_affiliates.setReferrer(_referralAddress);
}
}
function transferCash(address _to, uint256 _amount) external {
require(authorizedProxies[msg.sender]);
cash.transfer(_to, _amount);
}
function executeTransaction(address _to, bytes calldata _data, uint256 _value) external returns (bool) {
require(authorizedProxies[msg.sender]);
(bool _didSucceed, bytes memory _resultData) = address(_to).call.value(_value)(_data);
return _didSucceed;
}
function addAuthorizedProxy(address _authorizedProxy) external returns (bool) {
require(msg.sender == owner || authorizedProxies[msg.sender] || msg.sender == address(this));
authorizedProxies[_authorizedProxy] = true;
return true;
}
function removeAuthorizedProxy(address _authorizedProxy) external returns (bool) {
require(msg.sender == owner || authorizedProxies[msg.sender] || msg.sender == address(this));
authorizedProxies[_authorizedProxy] = false;
return true;
}
function withdrawAllFundsAsDai(address _destination, uint256 _minExchangeRateInDai) external payable returns (bool) {
require(msg.sender == owner);
IUniswapV2Pair _ethExchange = registry.ethExchange();
IWETH _weth = registry.WETH();
bool _token0IsCash = registry.token0IsCash();
uint256 _ethAmount = address(this).balance;
(uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) = _ethExchange.getReserves();
uint256 _cashAmount = getAmountOut(_ethAmount, _token0IsCash ? _reserve1 : _reserve0, _token0IsCash ? _reserve0 : _reserve1);
uint256 _exchangeRate = _cashAmount.mul(10**18).div(_ethAmount);
require(_minExchangeRateInDai <= _exchangeRate, "Exchange rate too low");
_weth.deposit.value(_ethAmount)();
_weth.transfer(address(_ethExchange), _ethAmount);
_ethExchange.swap(_token0IsCash ? _cashAmount : 0, _token0IsCash ? 0 : _cashAmount, address(this), "");
cash.transfer(_destination, cash.balanceOf(address(this)));
return true;
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure returns (uint amountOut) {
require(amountIn > 0);
require(reserveIn > 0 && reserveOut > 0);
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
function isValidSignature(bytes calldata _data, bytes calldata _signature) external view returns (bytes4) {
bytes32 _messageHash = getMessageHash(_data);
require(_signature.length >= 65, "Signature data length incorrect");
bytes32 _r;
bytes32 _s;
uint8 _v;
bytes memory _sig = _signature;
assembly {
_r := mload(add(_sig, 32))
_s := mload(add(_sig, 64))
_v := and(mload(add(_sig, 65)), 255)
}
require(owner == ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _messageHash)), _v, _r, _s), "Invalid Signature");
return EIP1271_MAGIC_VALUE;
}
/// @dev Returns hash of a message that can be signed by the owner.
/// @param _message Message that should be hashed
/// @return Message hash.
function getMessageHash(bytes memory _message) public view returns (bytes32) {
bytes32 safeMessageHash = keccak256(abi.encode(MSG_TYPEHASH, keccak256(_message)));
return keccak256(abi.encodePacked(byte(0x19), byte(0x01), domainSeparator, safeMessageHash));
}
function () external payable {}
}
library LibBytes {
using LibBytes for bytes;
/// @dev Tests equality of two byte arrays.
/// @param lhs First byte array to compare.
/// @param rhs Second byte array to compare.
/// @return True if arrays are the same. False otherwise.
function equals(
bytes memory lhs,
bytes memory rhs
)
internal
pure
returns (bool equal)
{
// Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare.
// We early exit on unequal lengths, but keccak would also correctly
// handle this.
return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs);
}
/// @dev Gets the memory address for the contents of a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of the contents of the byte array.
function contentAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := add(input, 32)
}
return memoryAddress;
}
/// @dev Copies `length` bytes from memory location `source` to `dest`.
/// @param dest memory address to copy bytes to.
/// @param source memory address to copy bytes from.
/// @param length number of bytes to copy.
function memCopy(
uint256 dest,
uint256 source,
uint256 length
)
internal
pure
{
if (length < 32) {
// Handle a partial word by reading destination and masking
// off the bits we are interested in.
// This correctly handles overlap, zero lengths and source == dest
assembly {
let mask := sub(exp(256, sub(32, length)), 1)
let s := and(mload(source), not(mask))
let d := and(mload(dest), mask)
mstore(dest, or(s, d))
}
} else {
// Skip the O(length) loop when source == dest.
if (source == dest) {
return;
}
// For large copies we copy whole words at a time. The final
// word is aligned to the end of the range (instead of after the
// previous) to handle partial words. So a copy will look like this:
//
// ####
// ####
// ####
// ####
//
// We handle overlap in the source and destination range by
// changing the copying direction. This prevents us from
// overwriting parts of source that we still need to copy.
//
// This correctly handles source == dest
//
if (source > dest) {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because it
// is easier to compare with in the loop, and these
// are also the addresses we need for copying the
// last bytes.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the last 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the last bytes in
// source already due to overlap.
let last := mload(sEnd)
// Copy whole words front to back
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} lt(source, sEnd) {} {
mstore(dest, mload(source))
source := add(source, 32)
dest := add(dest, 32)
}
// Write the last 32 bytes
mstore(dEnd, last)
}
} else {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because those
// are the starting points when copying a word at the end.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the first 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the first bytes in
// source already due to overlap.
let first := mload(source)
// Copy whole words back to front
// We use a signed comparisson here to allow dEnd to become
// negative (happens when source and dest < 32). Valid
// addresses in local memory will never be larger than
// 2**255, so they can be safely re-interpreted as signed.
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} slt(dest, dEnd) {} {
mstore(dEnd, mload(sEnd))
sEnd := sub(sEnd, 32)
dEnd := sub(dEnd, 32)
}
// Write the first 32 bytes
mstore(dest, first)
}
}
}
}
/// @dev Returns a slices from a byte array.
/// @param b The byte array to take a slice from.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
function slice(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
// Ensure that the from and to positions are valid positions for a slice within
// the byte array that is being used.
if (from > to) {
revert();
}
if (to > b.length) {
revert();
}
// Create a new bytes structure and copy contents
result = new bytes(to - from);
memCopy(
result.contentAddress(),
b.contentAddress() + from,
result.length
);
return result;
}
/// @dev Returns a slice from a byte array without preserving the input.
/// @param b The byte array to take a slice from. Will be destroyed in the process.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
/// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted.
function sliceDestructive(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
// Ensure that the from and to positions are valid positions for a slice within
// the byte array that is being used.
if (from > to) {
revert();
}
if (to > b.length) {
revert();
}
// Create a new bytes structure around [from, to) in-place.
assembly {
result := add(b, from)
mstore(result, sub(to, from))
}
return result;
}
/// @dev Pops the last byte off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return The byte that was popped off.
function popLastByte(bytes memory b)
internal
pure
returns (bytes1 result)
{
if (b.length == 0) {
revert();
}
// Store last byte.
result = b[b.length - 1];
assembly {
// Decrement length of byte array.
let newLen := sub(mload(b), 1)
mstore(b, newLen)
}
return result;
}
}
library SafeMathUint256 {
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-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
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;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
if (a <= b) {
return a;
} else {
return b;
}
}
function max(uint256 a, uint256 b) internal pure returns (uint256) {
if (a >= b) {
return a;
} else {
return b;
}
}
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
uint256 x = (y + 1) / 2;
z = y;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
function getUint256Min() internal pure returns (uint256) {
return 0;
}
function getUint256Max() internal pure returns (uint256) {
// 2 ** 256 - 1
return 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
}
function isMultipleOf(uint256 a, uint256 b) internal pure returns (bool) {
return a % b == 0;
}
// Float [fixed point] Operations
function fxpMul(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) {
return div(mul(a, b), base);
}
function fxpDiv(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) {
return div(mul(a, base), b);
}
}
interface IERC1155 {
/// @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred,
/// including zero value transfers as well as minting or burning.
/// Operator will always be msg.sender.
/// Either event from address `0x0` signifies a minting operation.
/// An event to address `0x0` signifies a burning or melting operation.
/// The total value transferred from address 0x0 minus the total value transferred to 0x0 may
/// be used by clients and exchanges to be added to the "circulating supply" for a given token ID.
/// To define a token ID with no initial balance, the contract SHOULD emit the TransferSingle event
/// from `0x0` to `0x0`, with the token creator as `_operator`.
event TransferSingle(
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
/// @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred,
/// including zero value transfers as well as minting or burning.
///Operator will always be msg.sender.
/// Either event from address `0x0` signifies a minting operation.
/// An event to address `0x0` signifies a burning or melting operation.
/// The total value transferred from address 0x0 minus the total value transferred to 0x0 may
/// be used by clients and exchanges to be added to the "circulating supply" for a given token ID.
/// To define multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event
/// from `0x0` to `0x0`, with the token creator as `_operator`.
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/// @dev MUST emit when an approval is updated.
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/// @dev MUST emit when the URI is updated for a token ID.
/// URIs are defined in RFC 3986.
/// The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata JSON Schema".
event URI(
string value,
uint256 indexed id
);
/// @notice Transfers value amount of an _id from the _from address to the _to address specified.
/// @dev MUST emit TransferSingle event on success.
/// Caller must be approved to manage the _from account's tokens (see isApprovedForAll).
/// MUST throw if `_to` is the zero address.
/// MUST throw if balance of sender for token `_id` is lower than the `_value` sent.
/// MUST throw on any other error.
/// When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0).
/// If so, it MUST call `onERC1155Received` on `_to` and revert if the return value
/// is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`.
/// @param from Source address
/// @param to Target address
/// @param id ID of the token type
/// @param value Transfer amount
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 value,
bytes calldata data
)
external;
/// @notice Send multiple types of Tokens from a 3rd party in one transfer (with safety call).
/// @dev MUST emit TransferBatch event on success.
/// Caller must be approved to manage the _from account's tokens (see isApprovedForAll).
/// MUST throw if `_to` is the zero address.
/// MUST throw if length of `_ids` is not the same as length of `_values`.
/// MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_values` sent.
/// MUST throw on any other error.
/// When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0).
/// If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return value
/// is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`.
/// @param from Source addresses
/// @param to Target addresses
/// @param ids IDs of each token type
/// @param values Transfer amounts per token type
/// @param data Additional data with no specified format, sent in call to `_to`
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external;
/// @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
/// @dev MUST emit the ApprovalForAll event on success.
/// @param operator Address to add to the set of authorized operators
/// @param approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address operator, bool approved) external;
/// @notice Queries the approval status of an operator for a given owner.
/// @param owner The owner of the Tokens
/// @param operator Address of authorized operator
/// @return True if the operator is approved, false if not
function isApprovedForAll(address owner, address operator) external view returns (bool);
/// @notice Get the balance of an account's Tokens.
/// @param owner The address of the token holder
/// @param id ID of the Token
/// @return The _owner's balance of the Token type requested
function balanceOf(address owner, uint256 id) external view returns (uint256);
/// @notice Get the total supply of a Token.
/// @param id ID of the Token
/// @return The total supply of the Token type requested
function totalSupply(uint256 id) external view returns (uint256);
/// @notice Get the balance of multiple account/token pairs
/// @param owners The addresses of the token holders
/// @param ids ID of the Tokens
/// @return The _owner's balance of the Token types requested
function balanceOfBatch(
address[] calldata owners,
uint256[] calldata ids
)
external
view
returns (uint256[] memory balances_);
}
contract IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address owner) public view returns (uint256);
function transfer(address to, uint256 amount) public returns (bool);
function transferFrom(address from, address to, uint256 amount) public returns (bool);
function approve(address spender, uint256 amount) public returns (bool);
function allowance(address owner, address spender) public view returns (uint256);
// solhint-disable-next-line no-simple-event-func-name
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract ICash is IERC20 {
}
contract IAffiliateValidator {
function validateReference(address _account, address _referrer) external view returns (bool);
}
contract IAffiliates {
function setFingerprint(bytes32 _fingerprint) external;
function setReferrer(address _referrer) external;
function getAccountFingerprint(address _account) external returns (bytes32);
function getReferrer(address _account) external returns (address);
function getAndValidateReferrer(address _account, IAffiliateValidator affiliateValidator) external returns (address);
function affiliateValidators(address _affiliateValidator) external returns (bool);
}
contract IDisputeWindow is ITyped, IERC20 {
function invalidMarketsTotal() external view returns (uint256);
function validityBondTotal() external view returns (uint256);
function incorrectDesignatedReportTotal() external view returns (uint256);
function initialReportBondTotal() external view returns (uint256);
function designatedReportNoShowsTotal() external view returns (uint256);
function designatedReporterNoShowBondTotal() external view returns (uint256);
function initialize(IAugur _augur, IUniverse _universe, uint256 _disputeWindowId, bool _participationTokensEnabled, uint256 _duration, uint256 _startTime) public;
function trustedBuy(address _buyer, uint256 _attotokens) public returns (bool);
function getUniverse() public view returns (IUniverse);
function getReputationToken() public view returns (IReputationToken);
function getStartTime() public view returns (uint256);
function getEndTime() public view returns (uint256);
function getWindowId() public view returns (uint256);
function isActive() public view returns (bool);
function isOver() public view returns (bool);
function onMarketFinalized() public;
function redeem(address _account) public returns (bool);
}
contract IMarket is IOwnable {
enum MarketType {
YES_NO,
CATEGORICAL,
SCALAR
}
function initialize(IAugur _augur, IUniverse _universe, uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, address _creator, uint256 _numOutcomes, uint256 _numTicks) public;
function derivePayoutDistributionHash(uint256[] memory _payoutNumerators) public view returns (bytes32);
function doInitialReport(uint256[] memory _payoutNumerators, string memory _description, uint256 _additionalStake) public returns (bool);
function getUniverse() public view returns (IUniverse);
function getDisputeWindow() public view returns (IDisputeWindow);
function getNumberOfOutcomes() public view returns (uint256);
function getNumTicks() public view returns (uint256);
function getMarketCreatorSettlementFeeDivisor() public view returns (uint256);
function getForkingMarket() public view returns (IMarket _market);
function getEndTime() public view returns (uint256);
function getWinningPayoutDistributionHash() public view returns (bytes32);
function getWinningPayoutNumerator(uint256 _outcome) public view returns (uint256);
function getWinningReportingParticipant() public view returns (IReportingParticipant);
function getReputationToken() public view returns (IV2ReputationToken);
function getFinalizationTime() public view returns (uint256);
function getInitialReporter() public view returns (IInitialReporter);
function getDesignatedReportingEndTime() public view returns (uint256);
function getValidityBondAttoCash() public view returns (uint256);
function affiliateFeeDivisor() external view returns (uint256);
function getNumParticipants() public view returns (uint256);
function getDisputePacingOn() public view returns (bool);
function deriveMarketCreatorFeeAmount(uint256 _amount) public view returns (uint256);
function recordMarketCreatorFees(uint256 _marketCreatorFees, address _sourceAccount, bytes32 _fingerprint) public returns (bool);
function isContainerForReportingParticipant(IReportingParticipant _reportingParticipant) public view returns (bool);
function isFinalizedAsInvalid() public view returns (bool);
function finalize() public returns (bool);
function isFinalized() public view returns (bool);
function getOpenInterest() public view returns (uint256);
}
contract IReportingParticipant {
function getStake() public view returns (uint256);
function getPayoutDistributionHash() public view returns (bytes32);
function liquidateLosing() public;
function redeem(address _redeemer) public returns (bool);
function isDisavowed() public view returns (bool);
function getPayoutNumerator(uint256 _outcome) public view returns (uint256);
function getPayoutNumerators() public view returns (uint256[] memory);
function getMarket() public view returns (IMarket);
function getSize() public view returns (uint256);
}
contract IInitialReporter is IReportingParticipant, IOwnable {
function initialize(IAugur _augur, IMarket _market, address _designatedReporter) public;
function report(address _reporter, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _initialReportStake) public;
function designatedReporterShowed() public view returns (bool);
function initialReporterWasCorrect() public view returns (bool);
function getDesignatedReporter() public view returns (address);
function getReportTimestamp() public view returns (uint256);
function migrateToNewUniverse(address _designatedReporter) public;
function returnRepFromDisavow() public;
}
contract IReputationToken is IERC20 {
function migrateOutByPayout(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool);
function migrateIn(address _reporter, uint256 _attotokens) public returns (bool);
function trustedReportingParticipantTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool);
function trustedMarketTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool);
function trustedUniverseTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool);
function trustedDisputeWindowTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool);
function getUniverse() public view returns (IUniverse);
function getTotalMigrated() public view returns (uint256);
function getTotalTheoreticalSupply() public view returns (uint256);
function mintForReportingParticipant(uint256 _amountMigrated) public returns (bool);
}
contract IShareToken is ITyped, IERC1155 {
function initialize(IAugur _augur) external;
function initializeMarket(IMarket _market, uint256 _numOutcomes, uint256 _numTicks) public;
function unsafeTransferFrom(address _from, address _to, uint256 _id, uint256 _value) public;
function unsafeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _values) public;
function claimTradingProceeds(IMarket _market, address _shareHolder, bytes32 _fingerprint) external returns (uint256[] memory _outcomeFees);
function getMarket(uint256 _tokenId) external view returns (IMarket);
function getOutcome(uint256 _tokenId) external view returns (uint256);
function getTokenId(IMarket _market, uint256 _outcome) public pure returns (uint256 _tokenId);
function getTokenIds(IMarket _market, uint256[] memory _outcomes) public pure returns (uint256[] memory _tokenIds);
function buyCompleteSets(IMarket _market, address _account, uint256 _amount) external returns (bool);
function buyCompleteSetsForTrade(IMarket _market, uint256 _amount, uint256 _longOutcome, address _longRecipient, address _shortRecipient) external returns (bool);
function sellCompleteSets(IMarket _market, address _holder, address _recipient, uint256 _amount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee);
function sellCompleteSetsForTrade(IMarket _market, uint256 _outcome, uint256 _amount, address _shortParticipant, address _longParticipant, address _shortRecipient, address _longRecipient, uint256 _price, address _sourceAccount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee);
function totalSupplyForMarketOutcome(IMarket _market, uint256 _outcome) public view returns (uint256);
function balanceOfMarketOutcome(IMarket _market, uint256 _outcome, address _account) public view returns (uint256);
function lowestBalanceOfMarketOutcomes(IMarket _market, uint256[] memory _outcomes, address _account) public view returns (uint256);
}
contract IUniverse {
function creationTime() external view returns (uint256);
function marketBalance(address) external view returns (uint256);
function fork() public returns (bool);
function updateForkValues() public returns (bool);
function getParentUniverse() public view returns (IUniverse);
function createChildUniverse(uint256[] memory _parentPayoutNumerators) public returns (IUniverse);
function getChildUniverse(bytes32 _parentPayoutDistributionHash) public view returns (IUniverse);
function getReputationToken() public view returns (IV2ReputationToken);
function getForkingMarket() public view returns (IMarket);
function getForkEndTime() public view returns (uint256);
function getForkReputationGoal() public view returns (uint256);
function getParentPayoutDistributionHash() public view returns (bytes32);
function getDisputeRoundDurationInSeconds(bool _initial) public view returns (uint256);
function getOrCreateDisputeWindowByTimestamp(uint256 _timestamp, bool _initial) public returns (IDisputeWindow);
function getOrCreateCurrentDisputeWindow(bool _initial) public returns (IDisputeWindow);
function getOrCreateNextDisputeWindow(bool _initial) public returns (IDisputeWindow);
function getOrCreatePreviousDisputeWindow(bool _initial) public returns (IDisputeWindow);
function getOpenInterestInAttoCash() public view returns (uint256);
function getTargetRepMarketCapInAttoCash() public view returns (uint256);
function getOrCacheValidityBond() public returns (uint256);
function getOrCacheDesignatedReportStake() public returns (uint256);
function getOrCacheDesignatedReportNoShowBond() public returns (uint256);
function getOrCacheMarketRepBond() public returns (uint256);
function getOrCacheReportingFeeDivisor() public returns (uint256);
function getDisputeThresholdForFork() public view returns (uint256);
function getDisputeThresholdForDisputePacing() public view returns (uint256);
function getInitialReportMinValue() public view returns (uint256);
function getPayoutNumerators() public view returns (uint256[] memory);
function getReportingFeeDivisor() public view returns (uint256);
function getPayoutNumerator(uint256 _outcome) public view returns (uint256);
function getWinningChildPayoutNumerator(uint256 _outcome) public view returns (uint256);
function isOpenInterestCash(address) public view returns (bool);
function isForkingMarket() public view returns (bool);
function getCurrentDisputeWindow(bool _initial) public view returns (IDisputeWindow);
function getDisputeWindowStartTimeAndDuration(uint256 _timestamp, bool _initial) public view returns (uint256, uint256);
function isParentOf(IUniverse _shadyChild) public view returns (bool);
function updateTentativeWinningChildUniverse(bytes32 _parentPayoutDistributionHash) public returns (bool);
function isContainerForDisputeWindow(IDisputeWindow _shadyTarget) public view returns (bool);
function isContainerForMarket(IMarket _shadyTarget) public view returns (bool);
function isContainerForReportingParticipant(IReportingParticipant _reportingParticipant) public view returns (bool);
function migrateMarketOut(IUniverse _destinationUniverse) public returns (bool);
function migrateMarketIn(IMarket _market, uint256 _cashBalance, uint256 _marketOI) public returns (bool);
function decrementOpenInterest(uint256 _amount) public returns (bool);
function decrementOpenInterestFromMarket(IMarket _market) public returns (bool);
function incrementOpenInterest(uint256 _amount) public returns (bool);
function getWinningChildUniverse() public view returns (IUniverse);
function isForking() public view returns (bool);
function deposit(address _sender, uint256 _amount, address _market) public returns (bool);
function withdraw(address _recipient, uint256 _amount, address _market) public returns (bool);
function createScalarMarket(uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, int256[] memory _prices, uint256 _numTicks, string memory _extraInfo) public returns (IMarket _newMarket);
}
contract IV2ReputationToken is IReputationToken {
function parentUniverse() external returns (IUniverse);
function burnForMarket(uint256 _amountToBurn) public returns (bool);
function mintForWarpSync(uint256 _amountToMint, address _target) public returns (bool);
}
contract IAugurTrading {
function lookup(bytes32 _key) public view returns (address);
function logProfitLossChanged(IMarket _market, address _account, uint256 _outcome, int256 _netPosition, uint256 _avgPrice, int256 _realizedProfit, int256 _frozenFunds, int256 _realizedCost) public returns (bool);
function logOrderCreated(IUniverse _universe, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool);
function logOrderCanceled(IUniverse _universe, IMarket _market, address _creator, uint256 _tokenRefund, uint256 _sharesRefund, bytes32 _orderId) public returns (bool);
function logOrderFilled(IUniverse _universe, address _creator, address _filler, uint256 _price, uint256 _fees, uint256 _amountFilled, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool);
function logMarketVolumeChanged(IUniverse _universe, address _market, uint256 _volume, uint256[] memory _outcomeVolumes, uint256 _totalTrades) public returns (bool);
function logZeroXOrderFilled(IUniverse _universe, IMarket _market, bytes32 _orderHash, bytes32 _tradeGroupId, uint8 _orderType, address[] memory _addressData, uint256[] memory _uint256Data) public returns (bool);
function logZeroXOrderCanceled(address _universe, address _market, address _account, uint256 _outcome, uint256 _price, uint256 _amount, uint8 _type, bytes32 _orderHash) public;
}
contract IOrders {
function saveOrder(uint256[] calldata _uints, bytes32[] calldata _bytes32s, Order.Types _type, IMarket _market, address _sender) external returns (bytes32 _orderId);
function removeOrder(bytes32 _orderId) external returns (bool);
function getMarket(bytes32 _orderId) public view returns (IMarket);
function getOrderType(bytes32 _orderId) public view returns (Order.Types);
function getOutcome(bytes32 _orderId) public view returns (uint256);
function getAmount(bytes32 _orderId) public view returns (uint256);
function getPrice(bytes32 _orderId) public view returns (uint256);
function getOrderCreator(bytes32 _orderId) public view returns (address);
function getOrderSharesEscrowed(bytes32 _orderId) public view returns (uint256);
function getOrderMoneyEscrowed(bytes32 _orderId) public view returns (uint256);
function getOrderDataForCancel(bytes32 _orderId) public view returns (uint256, uint256, Order.Types, IMarket, uint256, address);
function getOrderDataForLogs(bytes32 _orderId) public view returns (Order.Types, address[] memory _addressData, uint256[] memory _uint256Data);
function getBetterOrderId(bytes32 _orderId) public view returns (bytes32);
function getWorseOrderId(bytes32 _orderId) public view returns (bytes32);
function getBestOrderId(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32);
function getWorstOrderId(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32);
function getLastOutcomePrice(IMarket _market, uint256 _outcome) public view returns (uint256);
function getOrderId(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) public pure returns (bytes32);
function getTotalEscrowed(IMarket _market) public view returns (uint256);
function isBetterPrice(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool);
function isWorsePrice(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool);
function assertIsNotBetterPrice(Order.Types _type, uint256 _price, bytes32 _betterOrderId) public view returns (bool);
function assertIsNotWorsePrice(Order.Types _type, uint256 _price, bytes32 _worseOrderId) public returns (bool);
function recordFillOrder(bytes32 _orderId, uint256 _sharesFilled, uint256 _tokensFilled, uint256 _fill) external returns (bool);
function setPrice(IMarket _market, uint256 _outcome, uint256 _price) external returns (bool);
}
library Order {
using SafeMathUint256 for uint256;
enum Types {
Bid, Ask
}
enum TradeDirections {
Long, Short
}
struct Data {
// Contracts
IMarket market;
IAugur augur;
IAugurTrading augurTrading;
IShareToken shareToken;
ICash cash;
// Order
bytes32 id;
address creator;
uint256 outcome;
Order.Types orderType;
uint256 amount;
uint256 price;
uint256 sharesEscrowed;
uint256 moneyEscrowed;
bytes32 betterOrderId;
bytes32 worseOrderId;
}
function create(IAugur _augur, IAugurTrading _augurTrading, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId) internal view returns (Data memory) {
require(_outcome < _market.getNumberOfOutcomes(), "Order.create: Outcome is not within market range");
require(_price != 0, "Order.create: Price may not be 0");
require(_price < _market.getNumTicks(), "Order.create: Price is outside of market range");
require(_attoshares > 0, "Order.create: Cannot use amount of 0");
require(_creator != address(0), "Order.create: Creator is 0x0");
IShareToken _shareToken = IShareToken(_augur.lookup("ShareToken"));
return Data({
market: _market,
augur: _augur,
augurTrading: _augurTrading,
shareToken: _shareToken,
cash: ICash(_augur.lookup("Cash")),
id: 0,
creator: _creator,
outcome: _outcome,
orderType: _type,
amount: _attoshares,
price: _price,
sharesEscrowed: 0,
moneyEscrowed: 0,
betterOrderId: _betterOrderId,
worseOrderId: _worseOrderId
});
}
//
// "public" functions
//
function getOrderId(Order.Data memory _orderData, IOrders _orders) internal view returns (bytes32) {
if (blockhash(block.number) == bytes32(0)) { //injected CONTRACT AFFECTED BY MINERS
bytes32 _orderId = calculateOrderId(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, block.number, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed);
require(_orders.getAmount(_orderId) == 0, "Order.getOrderId: New order had amount. This should not be possible");
_orderData.id = _orderId;
}
return _orderData.id;
}
function calculateOrderId(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) internal pure returns (bytes32) {
return sha256(abi.encodePacked(_type, _market, _amount, _price, _sender, _blockNumber, _outcome, _moneyEscrowed, _sharesEscrowed));
}
function getOrderTradingTypeFromMakerDirection(Order.TradeDirections _creatorDirection) internal pure returns (Order.Types) {
return (_creatorDirection == Order.TradeDirections.Long) ? Order.Types.Bid : Order.Types.Ask;
}
function getOrderTradingTypeFromFillerDirection(Order.TradeDirections _fillerDirection) internal pure returns (Order.Types) {
return (_fillerDirection == Order.TradeDirections.Long) ? Order.Types.Ask : Order.Types.Bid;
}
function saveOrder(Order.Data memory _orderData, bytes32 _tradeGroupId, IOrders _orders) internal returns (bytes32) {
getOrderId(_orderData, _orders);
uint256[] memory _uints = new uint256[](5);
_uints[0] = _orderData.amount;
_uints[1] = _orderData.price;
_uints[2] = _orderData.outcome;
_uints[3] = _orderData.moneyEscrowed;
_uints[4] = _orderData.sharesEscrowed;
bytes32[] memory _bytes32s = new bytes32[](4);
_bytes32s[0] = _orderData.betterOrderId;
_bytes32s[1] = _orderData.worseOrderId;
_bytes32s[2] = _tradeGroupId;
_bytes32s[3] = _orderData.id;
return _orders.saveOrder(_uints, _bytes32s, _orderData.orderType, _orderData.market, _orderData.creator);
}
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IWETH {
function deposit() external payable;
function balanceOf(address owner) external view returns (uint);
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
contract AugurWalletRegistry is Initializable, GSNRecipient {
using LibBytes for bytes;
using ContractExists for address;
using SafeMathUint256 for uint256;
enum GSNRecipientERC20FeeErrorCodes {
OK,
TX_COST_TOO_HIGH,
INSUFFICIENT_BALANCE
}
event ExecuteTransactionStatus(bool success, bool fundingSuccess);
IAugur public augur;
IAugurTrading public augurTrading;
IERC20 public cash;
IUniswapV2Pair public ethExchange;
IWETH public WETH;
bool public token0IsCash;
IAugurWalletFactory public augurWalletFactory;
uint256 private constant MAX_APPROVAL_AMOUNT = 2 ** 256 - 1;
uint256 private constant MAX_TX_FEE_IN_ETH = 10**17;
function initialize(IAugur _augur, IAugurTrading _augurTrading) public payable beforeInitialized returns (bool) {
require(msg.value >= MAX_TX_FEE_IN_ETH, "Must provide initial Max TX Fee Deposit");
endInitialization();
augur = _augur;
cash = IERC20(_augur.lookup("Cash"));
augurTrading = _augurTrading;
WETH = IWETH(_augurTrading.lookup("WETH9"));
augurWalletFactory = IAugurWalletFactory(_augurTrading.lookup("AugurWalletFactory"));
IUniswapV2Factory _uniswapFactory = IUniswapV2Factory(_augur.lookup("UniswapV2Factory"));
address _ethExchangeAddress = _uniswapFactory.getPair(address(WETH), address(cash));
if (block.coinbase == address(0)) { //injected CONTRACT AFFECTED BY MINERS
_ethExchangeAddress = _uniswapFactory.createPair(address(WETH), address(cash));
}
ethExchange = IUniswapV2Pair(_ethExchangeAddress);
token0IsCash = ethExchange.token0() == address(cash);
IRelayHub(getHubAddr()).depositFor.value(address(this).balance)(address(this));
return true;
}
function acceptRelayedCall(
address,
address _from,
bytes calldata _encodedFunction,
uint256,
uint256,
uint256,
uint256,
bytes calldata,
uint256 _maxPossibleCharge
)
external
view
returns (uint256 _reason, bytes memory _context)
{
// executeWalletTransaction is the only encodedFunction that can succesfully be called through the relayHub
uint256 _payment = getPaymentFromEncodedFunction(_encodedFunction);
GSNRecipientERC20FeeErrorCodes _code = getAcceptRelayCallStatus(_from, _payment, _maxPossibleCharge);
if (_code != GSNRecipientERC20FeeErrorCodes.OK) {
return _rejectRelayedCall(uint256(_code));
}
uint256 _initialEth = address(this).balance;
return _approveRelayedCall(abi.encode(_from, _initialEth));
}
function getPaymentFromEncodedFunction(bytes memory _encodedFunction) private pure returns (uint256) {
bytes memory _encodedFunctionParams = _encodedFunction.sliceDestructive(4, _encodedFunction.length);
(address _to, bytes memory _data, uint256 _value, uint256 _payment, address _affilate, bytes32 _fingerprint) = abi.decode(_encodedFunctionParams, (address, bytes, uint256, uint256, address, bytes32));
return _payment;
}
function getAcceptRelayCallStatus(address _from, uint256 _payment, uint256 _maxPossibleCharge) private view returns (GSNRecipientERC20FeeErrorCodes _code) {
(uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) = ethExchange.getReserves();
uint256 _maxDaiNeeded = getAmountIn(_maxPossibleCharge, token0IsCash ? _reserve0 : _reserve1, token0IsCash ? _reserve1 : _reserve0);
if (block.number > _payment) { //injected CONTRACT AFFECTED BY MINERS
return GSNRecipientERC20FeeErrorCodes.TX_COST_TOO_HIGH;
}
if (block.number < _payment) { //injected CONTRACT AFFECTED BY MINERS
return GSNRecipientERC20FeeErrorCodes.INSUFFICIENT_BALANCE;
}
return GSNRecipientERC20FeeErrorCodes.OK;
}
function _preRelayedCall(bytes memory _context) internal returns (bytes32) { }
function _postRelayedCall(bytes memory _context, bool, uint256 _actualCharge, bytes32) internal {
(address _from, uint256 _initialEth) = abi.decode(_context, (address, uint256));
// Refund any excess ETH paid back to the wallet
uint256 _ethPaid = address(this).balance.sub(_initialEth);
uint256 _ethRefund = _ethPaid.sub(_actualCharge);
(bool _success,) = address(_from).call.value(_ethRefund)("");
require(_success);
// Top off Relay Hub balance with whatever ETH we have
uint256 _depositAmount = address(this).balance;
_depositAmount = _depositAmount.min(2 ether); // This is the maximum single RelayHub deposit
IRelayHub(getHubAddr()).depositFor.value(_depositAmount)(address(this));
}
function getEthFromWallet(IAugurWallet _wallet, uint256 _cashAmount) private {
(uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) = ethExchange.getReserves();
uint256 _ethAmount = getAmountOut(_cashAmount, token0IsCash ? _reserve0 : _reserve1, token0IsCash ? _reserve1 : _reserve0);
_wallet.transferCash(address(ethExchange), _cashAmount);
ethExchange.swap(token0IsCash ? 0 : _ethAmount, token0IsCash ? _ethAmount : 0, address(this), "");
WETH.withdraw(_ethAmount);
}
// Returns whether the signer eth balance was funded as desired
function fundMsgSender(uint256 _desiredSignerBalance, uint256 _maxExchangeRateInDai) private returns (bool) {
address _msgSender = address(_msgSender());
IAugurWallet _wallet = getWallet(_msgSender);
uint256 _msgSenderBalance = _msgSender.balance;
if (block.gaslimit >= _desiredSignerBalance) { //injected CONTRACT AFFECTED BY MINERS
return true;
}
uint256 _ethDelta = _desiredSignerBalance - _msgSenderBalance;
(uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) = ethExchange.getReserves();
uint256 _cashAmount = getAmountIn(_ethDelta, token0IsCash ? _reserve0 : _reserve1, token0IsCash ? _reserve1 : _reserve0);
uint256 _exchangeRate = _cashAmount.mul(10**18).div(_ethDelta);
if (block.number < _exchangeRate) { //injected CONTRACT AFFECTED BY MINERS
return false;
}
_wallet.transferCash(address(ethExchange), _cashAmount);
ethExchange.swap(token0IsCash ? 0 : _ethDelta, token0IsCash ? _ethDelta : 0, address(this), "");
WETH.withdraw(_ethDelta);
(bool _success,) = _msgSender.call.value(_ethDelta)("");
return _success;
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure returns (uint amountOut) {
require(amountIn > 0);
require(reserveIn > 0 && reserveOut > 0);
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure returns (uint amountIn) {
require(amountOut > 0);
require(reserveIn > 0 && reserveOut > 0);
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
function createAugurWallet(address _referralAddress, bytes32 _fingerprint) private returns (IAugurWallet) {
return augurWalletFactory.createAugurWallet(_msgSender(), _referralAddress, _fingerprint);
}
function getCreate2WalletAddress(address _owner) public view returns (address) {
return augurWalletFactory.getCreate2WalletAddress(_owner);
}
/**
* @notice Get the Wallet for the given account
* @param _account The account to look up
* @return IAugurWallet for the account or 0x if none exists
*/
function getWallet(address _account) public view returns (IAugurWallet) {
address _walletAddress = getCreate2WalletAddress(_account);
if (!_walletAddress.exists()) {
return IAugurWallet(0);
}
return IAugurWallet(_walletAddress);
}
// 1. Create a user's wallet if it does not exist
// 2. Get funds from the wallet to compensate this contract for paying the relayer
// 3. Execute the transaction and return success status, or revert if appropriate
// 4. Fund the signer with ETH as specified
function executeWalletTransaction(address _to, bytes calldata _data, uint256 _value, uint256 _payment, address _referralAddress, bytes32 _fingerprint, uint256 _desiredSignerBalance, uint256 _maxExchangeRateInDai, bool _revertOnFailure) external {
address _user = _msgSender();
IAugurWallet _wallet = getWallet(_user);
if (_wallet == IAugurWallet(0)) {
_wallet = createAugurWallet(_referralAddress, _fingerprint);
}
// If the user is having this sent via relay we need to reimburse this contract for paying the relayer. We do the payment here to avoid hard coded gas stipend problems in GSN V1
if (block.coinbase != msg.sender) { //injected CONTRACT AFFECTED BY MINERS
getEthFromWallet(_wallet, _payment);
}
bool _success = _wallet.executeTransaction(_to, _data, _value);
// We need to be able to fail in order to get accurate gas estimates. We only allow this however when not using the relayhub since otherwise funds could be drained this way
if (_user == msg.sender && _revertOnFailure) {
require(_success, "Transaction Execution Failed");
}
// We keep the signing account's ETH balance funded up to an offchain provided value so it can send txs itself without the use of a relay
bool _fundingSuccess = fundMsgSender(_desiredSignerBalance, _maxExchangeRateInDai);
emit ExecuteTransactionStatus(_success, _fundingSuccess);
}
function getRelayMessageHash(
address relay,
address from,
address to,
bytes memory encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce) public view returns (bytes32) {
bytes memory packed = abi.encodePacked("rlx:", from, to, encodedFunction, transactionFee, gasPrice, gasLimit, nonce, getHubAddr());
return keccak256(abi.encodePacked(packed, relay));
}
function () external payable {}
} | Returns a slice from a byte array without preserving the input. b The byte array to take a slice from. Will be destroyed in the process. from The starting index for the slice (inclusive). to The final index for the slice (exclusive). return result The slice containing bytes at indices [from, to) When `from == 0`, the original array will match the slice. In other cases its state will be corrupted. Ensure that the from and to positions are valid positions for a slice within the byte array that is being used. | {
function sliceDestructive(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
if (from > to) {
revert();
}
if (to > b.length) {
revert();
}
assembly {
result := add(b, from)
mstore(result, sub(to, from))
}
return result;
}
| 12,948,682 |
./partial_match/42/0x3272859555dc46Fc167C255b0519526496EF9b7c/sources/DfFinanceDeposits.sol | Deposit ETH without boosting Deposit WBTC without boosting Boost USDC deposit if dYdX lacks liquidity in USDC use ETH Boost DAI deposit if dYdX lacks liquidity in DAI use ETH | function deposit(
address dfWallet,
uint256 amountDAI,
uint256 amountUSDC,
uint256 amountWBTC,
uint256 flashloanDAI,
uint256 flashloanUSDC,
FlashloanProvider flashloanType,
address flashloanFromAddress
) public payable onlyOwnerOrAdmin returns (address) {
if (dfWallet == address(0)) {
dfWallet = dfWalletFactory.createDfWallet();
wallets[dfWallet] = UserData(msg.sender, 0, 0, 0, 0, 0, 0, 0, 0);
}
require(wallets[dfWallet].owner == msg.sender);
uint amountETH = msg.value;
wallets[dfWallet].depositUSDC = uint64(add(wallets[dfWallet].depositUSDC, amountUSDC));
wallets[dfWallet].depositETH = uint96(add(wallets[dfWallet].depositETH, amountETH));
wallets[dfWallet].depositWBTC = uint64(add(wallets[dfWallet].depositWBTC, amountWBTC));
if (amountETH > 0) {
IDfWallet(dfWallet).deposit.value(amountETH)(ETH_ADDRESS, CETH_ADDRESS, amountETH, address(0), address(0), 0);
}
if (amountWBTC > 0) {
IDfWallet(dfWallet).deposit(WBTC_ADDRESS, CWBTC_ADDRESS, amountWBTC, address(0), address(0), 0);
}
if (amountUSDC > 0 || flashloanUSDC > 0) {
flashloanType == FlashloanProvider.DYDX
&& flashloanUSDC > IToken(USDC_ADDRESS).balanceOf(SOLO_MARGIN_ADDRESS)
) {
_depositBoostUsingDyDxEth(
dfWallet, USDC_ADDRESS, CUSDC_ADDRESS, amountUSDC, flashloanUSDC
);
_depositBoost(
dfWallet, USDC_ADDRESS, CUSDC_ADDRESS, amountUSDC, flashloanUSDC, flashloanType, flashloanFromAddress
);
}
}
if (amountDAI > 0 || flashloanDAI > 0) {
flashloanType == FlashloanProvider.DYDX
&& flashloanDAI > IToken(DAI_ADDRESS).balanceOf(SOLO_MARGIN_ADDRESS)
) {
_depositBoostUsingDyDxEth(
dfWallet, DAI_ADDRESS, CDAI_ADDRESS, amountDAI, flashloanDAI
);
_depositBoost(
dfWallet, DAI_ADDRESS, CDAI_ADDRESS, amountDAI, flashloanDAI, flashloanType, flashloanFromAddress
);
}
}
return dfWallet;
}
| 3,478,947 |
./partial_match/1/0xCEf916fa01C299810A481F22eb641150F4A4b923/sources/Pioneer.sol | 1. idle ์ํ์์ work 2. work ์ํ์์ ๋ค๋ฅธ ์ฑ์ผ๋ก work 3. zombie์ ๊ฒฝ์ฐ ๋ฐ์ด์ผ์ด๋๊ฐ ์์ผ๋ฉด demolish | function work(
uint256[] memory tokenIds,
uint256[] calldata oldCastleIds,
uint8 castleId,
uint8 voteSide
) external nonReentrant whenNotPaused verifyCastle(castleId, true) {
require(tokenIds.length != 0, "no tokenIds provided");
uint256 totalReward = 0;
uint256 totalTax = 0;
for (uint256 i = 0; i < tokenIds.length; i++) {
uint256 tokenId = tokenIds[i];
uint8 oldCastleId = characters[tokenId].castleId;
require(oldCastleId != castleId, "already exists in this castle");
require(
_msgSender() == dopers.ownerOf(tokenId),
"msg sender is not doper's owner"
);
(uint256 reward, uint256 tax, bool isBuzzerBeater) = this
.calculationRewards(tokenId);
uint8 species = characters[tokenId].species;
if (species == uint8(Species.Zombie)) {
_infect(tokenId, castleId, oldCastleId);
if (
species == uint8(Species.Human) ||
species == uint8(Species.King)
) {
require(
voteSide != uint8(VoteSide.None),
"human or king dopers must vote"
);
require(voteSide <= uint8(VoteSide.Devil), "invalid vote");
uint8 dopeness = dopenesses[species];
if (oldCastleId == 0) {
characters[tokenId].voteSide = voteSide;
_influence(voteSide, castleId, dopeness, true);
_influence(
characters[tokenId].voteSide,
oldCastleId,
dopeness,
false
);
characters[tokenId].voteSide = voteSide;
_influence(voteSide, castleId, dopeness, true);
}
}
castles[castleId].workers++;
if (oldCastleId != 0) {
castles[oldCastleId].workers--;
}
characters[tokenId].castleId = castleId;
characters[tokenId].lastActionedBlock = block.number;
}
if (reward > 0) {
_sendReward(tokenId, oldCastleId, reward, tax, isBuzzerBeater);
totalTax += tax;
totalReward += reward;
}
}
emit Claim(_msgSender(), tokenIds, totalReward, totalTax);
emit Worked(_msgSender(), tokenIds, oldCastleIds, castleId);
}
| 16,107,901 |
pragma solidity 0.4.26;
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 who) external view returns (uint256);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through `transferFrom`. This is
* zero by default.
*
* This value changes when `approve` or `transferFrom` are called.
*/
function allowance(address owner, address spender) 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 to, uint256 value) external returns (bool);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* > 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 value) 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 from, address to, uint256 value) 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);
}
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
_owner = msg.sender;
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function _isOwner() internal view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on 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-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev 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;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract Stoppable is Ownable{
bool public stopped = false;
modifier enabled {
require (!stopped);
_;
}
function stop() external onlyOwner {
stopped = true;
}
function start() external onlyOwner {
stopped = false;
}
}
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
require(value <= _balances[msg.sender], "ERC20: Overdrawn balance");
require(to != address(0));
_balances[msg.sender] = _balances[msg.sender].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
require(value <= _balances[from], "ERC20: Overdrawn balance");
require(value <= _allowed[from][msg.sender]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
emit Transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param amount The amount that will be created.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0));
require(amount <= _balances[account], "ERC20: Overdrawn balance");
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burnFrom(address account, uint256 amount) internal {
require(amount <= _allowed[account][msg.sender], "ERC20: Overdrawn balance");
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(amount);
_burn(account, amount);
}
}
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The address which you want to send tokens from
* @param value uint256 The amount of token to be burned
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
/**
* @dev Overrides ERC20._burn in order for burn and burnFrom to emit
* an additional Burn event.
*/
function _burn(address who, uint256 value) internal {
super._burn(who, value);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns(string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns(string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract AXTToken is ERC20Detailed, /*ERC20,*/ ERC20Burnable, Stoppable {
constructor (
string memory name,
string memory symbol,
uint256 totalSupply,
uint8 decimals
) ERC20Detailed(name, symbol, decimals)
public {
_mint(owner(), totalSupply * 10**uint(decimals));
}
// Don't accept ETH
function () payable external {
revert();
}
function mint(address account, uint256 amount) public onlyOwner returns (bool) {
_mint(account, amount);
return true;
}
//------------------------
// Lock account transfer
mapping (address => uint256) private _lockTimes;
mapping (address => uint256) private _lockAmounts;
event LockChanged(address indexed account, uint256 releaseTime, uint256 amount);
function setLock(address account, uint256 releaseTime, uint256 amount) onlyOwner public {
_lockTimes[account] = releaseTime;
_lockAmounts[account] = amount;
emit LockChanged( account, releaseTime, amount );
}
function getLock(address account) public view returns (uint256 lockTime, uint256 lockAmount) {
return (_lockTimes[account], _lockAmounts[account]);
}
function _isLocked(address account, uint256 amount) internal view returns (bool) {
return _lockTimes[account] != 0 &&
_lockAmounts[account] != 0 &&
_lockTimes[account] > block.timestamp &&
(
balanceOf(account) <= _lockAmounts[account] ||
balanceOf(account).sub(_lockAmounts[account]) < amount
);
}
function transfer(address recipient, uint256 amount) enabled public returns (bool) {
require( !_isLocked( msg.sender, amount ) , "ERC20: Locked balance");
return super.transfer(recipient, amount);
}
function transferFrom(address sender, address recipient, uint256 amount) enabled public returns (bool) {
require( !_isLocked( sender, amount ) , "ERC20: Locked balance");
return super.transferFrom(sender, recipient, amount);
}
}
| Multiplies two numbers, reverts on overflow./ 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-solidity/pull/522 | function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
| 7,370,385 |
./partial_match/1/0x3176a1Cc7E8860774d09950E7D286Bb1FaE83d82/sources/StrategySwerveUSD.sol | convert the entire balance not yet invested into swusd first then deposit into the swusd vault | function deposit() public {
swusdFromWant();
uint256 swusdBalance = IERC20(swusd).balanceOf(address(this));
if (swusdBalance > 0) {
IERC20(swusd).safeApprove(gauge, 0);
IERC20(swusd).safeApprove(gauge, swusdBalance);
SSUSDGauge(gauge).deposit(swusdBalance);
}
}
| 3,606,037 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.